Class: Manticore::Response

Inherits:
Object
  • Object
show all
Includes:
Callable, ResponseHandler
Defined in:
lib/manticore/response.rb

Overview

Implementation of ResponseHandler which serves as a Ruby proxy for HTTPClient responses.

Direct Known Subclasses

StubbedResponse

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client, request, context, &block) ⇒ Response

Creates a new Response

Parameters:

  • request (HttpRequestBase)

    The underlying request object

  • context (HttpContext)

    The underlying HttpContext



29
30
31
32
33
34
35
36
37
38
39
# File 'lib/manticore/response.rb', line 29

def initialize(client, request, context, &block)
  @client  = client
  @request = request
  @context = context
  @handlers = {
    success:   block || Proc.new {|resp| resp.body },
    failure:   Proc.new {|ex| raise ex },
    cancelled: Proc.new {},
    complete:  []
  }
end

Instance Attribute Details

#callback_resultObject (readonly)

Returns Value returned from any given on_success/response block.

Returns:

  • Value returned from any given on_success/response block



13
14
15
16
17
18
19
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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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
# File 'lib/manticore/response.rb', line 13

class Response
  include_package "org.apache.http.client"
  include_package "org.apache.http.util"
  include_package "org.apache.http.protocol"
  java_import "org.apache.http.client.protocol.HttpClientContext"
  java_import 'java.util.concurrent.Callable'

  include ResponseHandler
  include Callable

  attr_reader :context, :request, :callback_result, :called

  # Creates a new Response
  #
  # @param  request            [HttpRequestBase] The underlying request object
  # @param  context            [HttpContext] The underlying HttpContext
  def initialize(client, request, context, &block)
    @client  = client
    @request = request
    @context = context
    @handlers = {
      success:   block || Proc.new {|resp| resp.body },
      failure:   Proc.new {|ex| raise ex },
      cancelled: Proc.new {},
      complete:  []
    }
  end

  # Implementation of Callable#call
  # Used by Manticore::Client to invoke the request tied to this response. Users should never call this directly.
  def call
    raise "Already called" if @called
    @called = true
    begin
      @client.execute @request, self, @context
      execute_complete
      return self
    rescue Java::JavaNet::SocketTimeoutException, Java::OrgApacheHttpConn::ConnectTimeoutException => e
      ex = Manticore::Timeout.new(e.cause || e.message)
    rescue Java::JavaNet::SocketException => e
      ex = Manticore::SocketException.new(e.cause || e.message)
    rescue Java::OrgApacheHttpClient::ClientProtocolException, Java::JavaxNetSsl::SSLHandshakeException, Java::OrgApacheHttpConn::HttpHostConnectException,
           Java::OrgApacheHttp::NoHttpResponseException, Java::OrgApacheHttp::ConnectionClosedException => e
      ex = Manticore::ClientProtocolException.new(e.cause || e.message)
    rescue Java::JavaNet::UnknownHostException => e
      ex = Manticore::ResolutionFailure.new(e.cause || e.message)
    end
    @exception = ex
    @handlers[:failure].call ex
    execute_complete
  end

  def fire_and_forget
    @client.executor.submit self
  end

  # Fetch the final resolved URL for this response. Will call the request if it has not been called yet.
  #
  # @return [String]
  def final_url
    call_once
    last_request = context.get_attribute ExecutionContext.HTTP_REQUEST
    last_host    = context.get_attribute ExecutionContext.HTTP_TARGET_HOST
    host         = last_host.to_uri
    url          = last_request.get_uri
    URI.join(host, url.to_s)
  end

  # Fetch the body content of this response. Will call the request if it has not been called yet.
  # This fetches the input stream in Ruby; this isn't optimal, but it's faster than
  # fetching the whole thing in Java then UTF-8 encoding it all into a giant Ruby string.
  #
  # This permits for streaming response bodies, as well.
  #
  # @example Streaming response
  #
  #     client.get("http://example.com/resource").on_success do |response|
  #       response.body do |chunk|
  #         # Do something with chunk, which is a parsed portion of the returned body
  #       end
  #     end
  #
  # @return [String] Reponse body
  def body(&block)
    call_once
    @body ||= begin
      if entity = @response.get_entity
        EntityConverter.new.read_entity(entity, &block)
      end
    rescue Java::JavaIo::IOException, Java::JavaNet::SocketException, IOError => e
      raise StreamClosedException.new("Could not read from stream: #{e.message}")
    # ensure
    #   @request.release_connection
    end
  end
  alias_method :read_body, :body

  # Returns true if this response has been called (requested and populated) yet
  def called?
    !!@called
  end

  # Return a hash of headers from this response. Will call the request if it has not been called yet.
  #
  # @return [Array<string, obj>] Hash of headers. Keys will be lower-case.
  def headers
    call_once
    @headers
  end

  # Return the response code from this request as an integer. Will call the request if it has not been called yet.
  #
  # @return [Integer] The response code
  def code
    call_once
    @code
  end

  # Return the response text for a request as a string (Not Found, Ok, Bad Request, etc). Will call the request if it has not been called yet.
  #
  # @return [String] The response code text
  def message
    call_once
    @message
  end

  # Returns the length of the response body. Returns -1 if content-length is not present in the response.
  #
  # @return [Integer]
  def length
    (headers["content-length"] || -1).to_i
  end

  # Returns an array of {Manticore::Cookie Cookies} associated with this request's execution context
  #
  # @return [Array<Manticore::Cookie>]
  def cookies
    call_once
    @cookies ||= begin
      @context.get_cookie_store.get_cookies.inject({}) do |all, java_cookie|
        c = Cookie.from_java(java_cookie)
        all[c.name] ||= []
        all[c.name] << c
        all
      end
    end
  end

  # Set handler for success responses
  # @param block Proc which will be invoked on a successful response. Block will receive |response, request|
  #
  # @return self
  def on_success(&block)
    @handlers[:success] = block
    self
  end
  alias_method :success, :on_success

  # Set handler for failure responses
  # @param block Proc which will be invoked on a on a failed response. Block will receive an exception object.
  #
  # @return self
  def on_failure(&block)
    @handlers[:failure] = block
    self
  end
  alias_method :failure, :on_failure
  alias_method :fail,    :on_failure

  # Set handler for cancelled requests
  # @param block Proc which will be invoked on a on a cancelled response.
  #
  # @return self
  def on_cancelled(&block)
    @handlers[:cancelled] = block
    self
  end
  alias_method :cancelled,       :on_cancelled
  alias_method :cancellation,    :on_cancelled
  alias_method :on_cancellation, :on_cancelled

  # Set handler for cancelled requests
  # @param block Proc which will be invoked on a on a cancelled response.
  #
  # @return self
  def on_complete(&block)
    @handlers[:complete] = Array(@handlers[:complete]).compact + [block]
    self
  end
  alias_method :complete,     :on_complete
  alias_method :completed,    :on_complete
  alias_method :on_completed, :on_complete

  def times_retried
    @context.get_attribute("retryCount") || 0
  end

  private

  # Implementation of {http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/ResponseHandler.html#handleResponse(org.apache.http.HttpResponse) ResponseHandler#handleResponse}
  # @param  response [Response] The underlying Java Response object
  def handleResponse(response)
    @response        = response
    @code            = response.get_status_line.get_status_code
    @message         = response.get_status_line.get_reason_phrase
    @headers         = Hash[* response.get_all_headers.flat_map {|h| [h.get_name.downcase, h.get_value]} ]
    @callback_result = @handlers[:success].call(self)
    nil
  end

  def call_once
    call unless called?
    @called = true
  end

  def execute_complete
    @handlers[:complete].each &:call
  end
end

#calledObject (readonly)

Returns the value of attribute called.



23
24
25
# File 'lib/manticore/response.rb', line 23

def called
  @called
end

#codeInteger (readonly)

Return the response code from this request as an integer. Will call the request if it has not been called yet.

Returns:

  • (Integer)

    The response code



13
14
15
16
17
18
19
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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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
# File 'lib/manticore/response.rb', line 13

class Response
  include_package "org.apache.http.client"
  include_package "org.apache.http.util"
  include_package "org.apache.http.protocol"
  java_import "org.apache.http.client.protocol.HttpClientContext"
  java_import 'java.util.concurrent.Callable'

  include ResponseHandler
  include Callable

  attr_reader :context, :request, :callback_result, :called

  # Creates a new Response
  #
  # @param  request            [HttpRequestBase] The underlying request object
  # @param  context            [HttpContext] The underlying HttpContext
  def initialize(client, request, context, &block)
    @client  = client
    @request = request
    @context = context
    @handlers = {
      success:   block || Proc.new {|resp| resp.body },
      failure:   Proc.new {|ex| raise ex },
      cancelled: Proc.new {},
      complete:  []
    }
  end

  # Implementation of Callable#call
  # Used by Manticore::Client to invoke the request tied to this response. Users should never call this directly.
  def call
    raise "Already called" if @called
    @called = true
    begin
      @client.execute @request, self, @context
      execute_complete
      return self
    rescue Java::JavaNet::SocketTimeoutException, Java::OrgApacheHttpConn::ConnectTimeoutException => e
      ex = Manticore::Timeout.new(e.cause || e.message)
    rescue Java::JavaNet::SocketException => e
      ex = Manticore::SocketException.new(e.cause || e.message)
    rescue Java::OrgApacheHttpClient::ClientProtocolException, Java::JavaxNetSsl::SSLHandshakeException, Java::OrgApacheHttpConn::HttpHostConnectException,
           Java::OrgApacheHttp::NoHttpResponseException, Java::OrgApacheHttp::ConnectionClosedException => e
      ex = Manticore::ClientProtocolException.new(e.cause || e.message)
    rescue Java::JavaNet::UnknownHostException => e
      ex = Manticore::ResolutionFailure.new(e.cause || e.message)
    end
    @exception = ex
    @handlers[:failure].call ex
    execute_complete
  end

  def fire_and_forget
    @client.executor.submit self
  end

  # Fetch the final resolved URL for this response. Will call the request if it has not been called yet.
  #
  # @return [String]
  def final_url
    call_once
    last_request = context.get_attribute ExecutionContext.HTTP_REQUEST
    last_host    = context.get_attribute ExecutionContext.HTTP_TARGET_HOST
    host         = last_host.to_uri
    url          = last_request.get_uri
    URI.join(host, url.to_s)
  end

  # Fetch the body content of this response. Will call the request if it has not been called yet.
  # This fetches the input stream in Ruby; this isn't optimal, but it's faster than
  # fetching the whole thing in Java then UTF-8 encoding it all into a giant Ruby string.
  #
  # This permits for streaming response bodies, as well.
  #
  # @example Streaming response
  #
  #     client.get("http://example.com/resource").on_success do |response|
  #       response.body do |chunk|
  #         # Do something with chunk, which is a parsed portion of the returned body
  #       end
  #     end
  #
  # @return [String] Reponse body
  def body(&block)
    call_once
    @body ||= begin
      if entity = @response.get_entity
        EntityConverter.new.read_entity(entity, &block)
      end
    rescue Java::JavaIo::IOException, Java::JavaNet::SocketException, IOError => e
      raise StreamClosedException.new("Could not read from stream: #{e.message}")
    # ensure
    #   @request.release_connection
    end
  end
  alias_method :read_body, :body

  # Returns true if this response has been called (requested and populated) yet
  def called?
    !!@called
  end

  # Return a hash of headers from this response. Will call the request if it has not been called yet.
  #
  # @return [Array<string, obj>] Hash of headers. Keys will be lower-case.
  def headers
    call_once
    @headers
  end

  # Return the response code from this request as an integer. Will call the request if it has not been called yet.
  #
  # @return [Integer] The response code
  def code
    call_once
    @code
  end

  # Return the response text for a request as a string (Not Found, Ok, Bad Request, etc). Will call the request if it has not been called yet.
  #
  # @return [String] The response code text
  def message
    call_once
    @message
  end

  # Returns the length of the response body. Returns -1 if content-length is not present in the response.
  #
  # @return [Integer]
  def length
    (headers["content-length"] || -1).to_i
  end

  # Returns an array of {Manticore::Cookie Cookies} associated with this request's execution context
  #
  # @return [Array<Manticore::Cookie>]
  def cookies
    call_once
    @cookies ||= begin
      @context.get_cookie_store.get_cookies.inject({}) do |all, java_cookie|
        c = Cookie.from_java(java_cookie)
        all[c.name] ||= []
        all[c.name] << c
        all
      end
    end
  end

  # Set handler for success responses
  # @param block Proc which will be invoked on a successful response. Block will receive |response, request|
  #
  # @return self
  def on_success(&block)
    @handlers[:success] = block
    self
  end
  alias_method :success, :on_success

  # Set handler for failure responses
  # @param block Proc which will be invoked on a on a failed response. Block will receive an exception object.
  #
  # @return self
  def on_failure(&block)
    @handlers[:failure] = block
    self
  end
  alias_method :failure, :on_failure
  alias_method :fail,    :on_failure

  # Set handler for cancelled requests
  # @param block Proc which will be invoked on a on a cancelled response.
  #
  # @return self
  def on_cancelled(&block)
    @handlers[:cancelled] = block
    self
  end
  alias_method :cancelled,       :on_cancelled
  alias_method :cancellation,    :on_cancelled
  alias_method :on_cancellation, :on_cancelled

  # Set handler for cancelled requests
  # @param block Proc which will be invoked on a on a cancelled response.
  #
  # @return self
  def on_complete(&block)
    @handlers[:complete] = Array(@handlers[:complete]).compact + [block]
    self
  end
  alias_method :complete,     :on_complete
  alias_method :completed,    :on_complete
  alias_method :on_completed, :on_complete

  def times_retried
    @context.get_attribute("retryCount") || 0
  end

  private

  # Implementation of {http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/ResponseHandler.html#handleResponse(org.apache.http.HttpResponse) ResponseHandler#handleResponse}
  # @param  response [Response] The underlying Java Response object
  def handleResponse(response)
    @response        = response
    @code            = response.get_status_line.get_status_code
    @message         = response.get_status_line.get_reason_phrase
    @headers         = Hash[* response.get_all_headers.flat_map {|h| [h.get_name.downcase, h.get_value]} ]
    @callback_result = @handlers[:success].call(self)
    nil
  end

  def call_once
    call unless called?
    @called = true
  end

  def execute_complete
    @handlers[:complete].each &:call
  end
end

#contextHttpContext (readonly)

Returns Context associated with this request/response.

Returns:

  • (HttpContext)

    Context associated with this request/response



13
14
15
16
17
18
19
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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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
# File 'lib/manticore/response.rb', line 13

class Response
  include_package "org.apache.http.client"
  include_package "org.apache.http.util"
  include_package "org.apache.http.protocol"
  java_import "org.apache.http.client.protocol.HttpClientContext"
  java_import 'java.util.concurrent.Callable'

  include ResponseHandler
  include Callable

  attr_reader :context, :request, :callback_result, :called

  # Creates a new Response
  #
  # @param  request            [HttpRequestBase] The underlying request object
  # @param  context            [HttpContext] The underlying HttpContext
  def initialize(client, request, context, &block)
    @client  = client
    @request = request
    @context = context
    @handlers = {
      success:   block || Proc.new {|resp| resp.body },
      failure:   Proc.new {|ex| raise ex },
      cancelled: Proc.new {},
      complete:  []
    }
  end

  # Implementation of Callable#call
  # Used by Manticore::Client to invoke the request tied to this response. Users should never call this directly.
  def call
    raise "Already called" if @called
    @called = true
    begin
      @client.execute @request, self, @context
      execute_complete
      return self
    rescue Java::JavaNet::SocketTimeoutException, Java::OrgApacheHttpConn::ConnectTimeoutException => e
      ex = Manticore::Timeout.new(e.cause || e.message)
    rescue Java::JavaNet::SocketException => e
      ex = Manticore::SocketException.new(e.cause || e.message)
    rescue Java::OrgApacheHttpClient::ClientProtocolException, Java::JavaxNetSsl::SSLHandshakeException, Java::OrgApacheHttpConn::HttpHostConnectException,
           Java::OrgApacheHttp::NoHttpResponseException, Java::OrgApacheHttp::ConnectionClosedException => e
      ex = Manticore::ClientProtocolException.new(e.cause || e.message)
    rescue Java::JavaNet::UnknownHostException => e
      ex = Manticore::ResolutionFailure.new(e.cause || e.message)
    end
    @exception = ex
    @handlers[:failure].call ex
    execute_complete
  end

  def fire_and_forget
    @client.executor.submit self
  end

  # Fetch the final resolved URL for this response. Will call the request if it has not been called yet.
  #
  # @return [String]
  def final_url
    call_once
    last_request = context.get_attribute ExecutionContext.HTTP_REQUEST
    last_host    = context.get_attribute ExecutionContext.HTTP_TARGET_HOST
    host         = last_host.to_uri
    url          = last_request.get_uri
    URI.join(host, url.to_s)
  end

  # Fetch the body content of this response. Will call the request if it has not been called yet.
  # This fetches the input stream in Ruby; this isn't optimal, but it's faster than
  # fetching the whole thing in Java then UTF-8 encoding it all into a giant Ruby string.
  #
  # This permits for streaming response bodies, as well.
  #
  # @example Streaming response
  #
  #     client.get("http://example.com/resource").on_success do |response|
  #       response.body do |chunk|
  #         # Do something with chunk, which is a parsed portion of the returned body
  #       end
  #     end
  #
  # @return [String] Reponse body
  def body(&block)
    call_once
    @body ||= begin
      if entity = @response.get_entity
        EntityConverter.new.read_entity(entity, &block)
      end
    rescue Java::JavaIo::IOException, Java::JavaNet::SocketException, IOError => e
      raise StreamClosedException.new("Could not read from stream: #{e.message}")
    # ensure
    #   @request.release_connection
    end
  end
  alias_method :read_body, :body

  # Returns true if this response has been called (requested and populated) yet
  def called?
    !!@called
  end

  # Return a hash of headers from this response. Will call the request if it has not been called yet.
  #
  # @return [Array<string, obj>] Hash of headers. Keys will be lower-case.
  def headers
    call_once
    @headers
  end

  # Return the response code from this request as an integer. Will call the request if it has not been called yet.
  #
  # @return [Integer] The response code
  def code
    call_once
    @code
  end

  # Return the response text for a request as a string (Not Found, Ok, Bad Request, etc). Will call the request if it has not been called yet.
  #
  # @return [String] The response code text
  def message
    call_once
    @message
  end

  # Returns the length of the response body. Returns -1 if content-length is not present in the response.
  #
  # @return [Integer]
  def length
    (headers["content-length"] || -1).to_i
  end

  # Returns an array of {Manticore::Cookie Cookies} associated with this request's execution context
  #
  # @return [Array<Manticore::Cookie>]
  def cookies
    call_once
    @cookies ||= begin
      @context.get_cookie_store.get_cookies.inject({}) do |all, java_cookie|
        c = Cookie.from_java(java_cookie)
        all[c.name] ||= []
        all[c.name] << c
        all
      end
    end
  end

  # Set handler for success responses
  # @param block Proc which will be invoked on a successful response. Block will receive |response, request|
  #
  # @return self
  def on_success(&block)
    @handlers[:success] = block
    self
  end
  alias_method :success, :on_success

  # Set handler for failure responses
  # @param block Proc which will be invoked on a on a failed response. Block will receive an exception object.
  #
  # @return self
  def on_failure(&block)
    @handlers[:failure] = block
    self
  end
  alias_method :failure, :on_failure
  alias_method :fail,    :on_failure

  # Set handler for cancelled requests
  # @param block Proc which will be invoked on a on a cancelled response.
  #
  # @return self
  def on_cancelled(&block)
    @handlers[:cancelled] = block
    self
  end
  alias_method :cancelled,       :on_cancelled
  alias_method :cancellation,    :on_cancelled
  alias_method :on_cancellation, :on_cancelled

  # Set handler for cancelled requests
  # @param block Proc which will be invoked on a on a cancelled response.
  #
  # @return self
  def on_complete(&block)
    @handlers[:complete] = Array(@handlers[:complete]).compact + [block]
    self
  end
  alias_method :complete,     :on_complete
  alias_method :completed,    :on_complete
  alias_method :on_completed, :on_complete

  def times_retried
    @context.get_attribute("retryCount") || 0
  end

  private

  # Implementation of {http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/ResponseHandler.html#handleResponse(org.apache.http.HttpResponse) ResponseHandler#handleResponse}
  # @param  response [Response] The underlying Java Response object
  def handleResponse(response)
    @response        = response
    @code            = response.get_status_line.get_status_code
    @message         = response.get_status_line.get_reason_phrase
    @headers         = Hash[* response.get_all_headers.flat_map {|h| [h.get_name.downcase, h.get_value]} ]
    @callback_result = @handlers[:success].call(self)
    nil
  end

  def call_once
    call unless called?
    @called = true
  end

  def execute_complete
    @handlers[:complete].each &:call
  end
end

#headersArray<string, obj> (readonly)

Return a hash of headers from this response. Will call the request if it has not been called yet.

Returns:

  • (Array<string, obj>)

    Hash of headers. Keys will be lower-case.



13
14
15
16
17
18
19
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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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
# File 'lib/manticore/response.rb', line 13

class Response
  include_package "org.apache.http.client"
  include_package "org.apache.http.util"
  include_package "org.apache.http.protocol"
  java_import "org.apache.http.client.protocol.HttpClientContext"
  java_import 'java.util.concurrent.Callable'

  include ResponseHandler
  include Callable

  attr_reader :context, :request, :callback_result, :called

  # Creates a new Response
  #
  # @param  request            [HttpRequestBase] The underlying request object
  # @param  context            [HttpContext] The underlying HttpContext
  def initialize(client, request, context, &block)
    @client  = client
    @request = request
    @context = context
    @handlers = {
      success:   block || Proc.new {|resp| resp.body },
      failure:   Proc.new {|ex| raise ex },
      cancelled: Proc.new {},
      complete:  []
    }
  end

  # Implementation of Callable#call
  # Used by Manticore::Client to invoke the request tied to this response. Users should never call this directly.
  def call
    raise "Already called" if @called
    @called = true
    begin
      @client.execute @request, self, @context
      execute_complete
      return self
    rescue Java::JavaNet::SocketTimeoutException, Java::OrgApacheHttpConn::ConnectTimeoutException => e
      ex = Manticore::Timeout.new(e.cause || e.message)
    rescue Java::JavaNet::SocketException => e
      ex = Manticore::SocketException.new(e.cause || e.message)
    rescue Java::OrgApacheHttpClient::ClientProtocolException, Java::JavaxNetSsl::SSLHandshakeException, Java::OrgApacheHttpConn::HttpHostConnectException,
           Java::OrgApacheHttp::NoHttpResponseException, Java::OrgApacheHttp::ConnectionClosedException => e
      ex = Manticore::ClientProtocolException.new(e.cause || e.message)
    rescue Java::JavaNet::UnknownHostException => e
      ex = Manticore::ResolutionFailure.new(e.cause || e.message)
    end
    @exception = ex
    @handlers[:failure].call ex
    execute_complete
  end

  def fire_and_forget
    @client.executor.submit self
  end

  # Fetch the final resolved URL for this response. Will call the request if it has not been called yet.
  #
  # @return [String]
  def final_url
    call_once
    last_request = context.get_attribute ExecutionContext.HTTP_REQUEST
    last_host    = context.get_attribute ExecutionContext.HTTP_TARGET_HOST
    host         = last_host.to_uri
    url          = last_request.get_uri
    URI.join(host, url.to_s)
  end

  # Fetch the body content of this response. Will call the request if it has not been called yet.
  # This fetches the input stream in Ruby; this isn't optimal, but it's faster than
  # fetching the whole thing in Java then UTF-8 encoding it all into a giant Ruby string.
  #
  # This permits for streaming response bodies, as well.
  #
  # @example Streaming response
  #
  #     client.get("http://example.com/resource").on_success do |response|
  #       response.body do |chunk|
  #         # Do something with chunk, which is a parsed portion of the returned body
  #       end
  #     end
  #
  # @return [String] Reponse body
  def body(&block)
    call_once
    @body ||= begin
      if entity = @response.get_entity
        EntityConverter.new.read_entity(entity, &block)
      end
    rescue Java::JavaIo::IOException, Java::JavaNet::SocketException, IOError => e
      raise StreamClosedException.new("Could not read from stream: #{e.message}")
    # ensure
    #   @request.release_connection
    end
  end
  alias_method :read_body, :body

  # Returns true if this response has been called (requested and populated) yet
  def called?
    !!@called
  end

  # Return a hash of headers from this response. Will call the request if it has not been called yet.
  #
  # @return [Array<string, obj>] Hash of headers. Keys will be lower-case.
  def headers
    call_once
    @headers
  end

  # Return the response code from this request as an integer. Will call the request if it has not been called yet.
  #
  # @return [Integer] The response code
  def code
    call_once
    @code
  end

  # Return the response text for a request as a string (Not Found, Ok, Bad Request, etc). Will call the request if it has not been called yet.
  #
  # @return [String] The response code text
  def message
    call_once
    @message
  end

  # Returns the length of the response body. Returns -1 if content-length is not present in the response.
  #
  # @return [Integer]
  def length
    (headers["content-length"] || -1).to_i
  end

  # Returns an array of {Manticore::Cookie Cookies} associated with this request's execution context
  #
  # @return [Array<Manticore::Cookie>]
  def cookies
    call_once
    @cookies ||= begin
      @context.get_cookie_store.get_cookies.inject({}) do |all, java_cookie|
        c = Cookie.from_java(java_cookie)
        all[c.name] ||= []
        all[c.name] << c
        all
      end
    end
  end

  # Set handler for success responses
  # @param block Proc which will be invoked on a successful response. Block will receive |response, request|
  #
  # @return self
  def on_success(&block)
    @handlers[:success] = block
    self
  end
  alias_method :success, :on_success

  # Set handler for failure responses
  # @param block Proc which will be invoked on a on a failed response. Block will receive an exception object.
  #
  # @return self
  def on_failure(&block)
    @handlers[:failure] = block
    self
  end
  alias_method :failure, :on_failure
  alias_method :fail,    :on_failure

  # Set handler for cancelled requests
  # @param block Proc which will be invoked on a on a cancelled response.
  #
  # @return self
  def on_cancelled(&block)
    @handlers[:cancelled] = block
    self
  end
  alias_method :cancelled,       :on_cancelled
  alias_method :cancellation,    :on_cancelled
  alias_method :on_cancellation, :on_cancelled

  # Set handler for cancelled requests
  # @param block Proc which will be invoked on a on a cancelled response.
  #
  # @return self
  def on_complete(&block)
    @handlers[:complete] = Array(@handlers[:complete]).compact + [block]
    self
  end
  alias_method :complete,     :on_complete
  alias_method :completed,    :on_complete
  alias_method :on_completed, :on_complete

  def times_retried
    @context.get_attribute("retryCount") || 0
  end

  private

  # Implementation of {http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/ResponseHandler.html#handleResponse(org.apache.http.HttpResponse) ResponseHandler#handleResponse}
  # @param  response [Response] The underlying Java Response object
  def handleResponse(response)
    @response        = response
    @code            = response.get_status_line.get_status_code
    @message         = response.get_status_line.get_reason_phrase
    @headers         = Hash[* response.get_all_headers.flat_map {|h| [h.get_name.downcase, h.get_value]} ]
    @callback_result = @handlers[:success].call(self)
    nil
  end

  def call_once
    call unless called?
    @called = true
  end

  def execute_complete
    @handlers[:complete].each &:call
  end
end

#requestObject (readonly)

Returns the value of attribute request.



23
24
25
# File 'lib/manticore/response.rb', line 23

def request
  @request
end

Instance Method Details

#body(&block) ⇒ String Also known as: read_body

Fetch the body content of this response. Will call the request if it has not been called yet. This fetches the input stream in Ruby; this isn’t optimal, but it’s faster than fetching the whole thing in Java then UTF-8 encoding it all into a giant Ruby string.

This permits for streaming response bodies, as well.

Examples:

Streaming response


client.get("http://example.com/resource").on_success do |response|
  response.body do |chunk|
    # Do something with chunk, which is a parsed portion of the returned body
  end
end

Returns:

  • (String)

    Reponse body



96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/manticore/response.rb', line 96

def body(&block)
  call_once
  @body ||= begin
    if entity = @response.get_entity
      EntityConverter.new.read_entity(entity, &block)
    end
  rescue Java::JavaIo::IOException, Java::JavaNet::SocketException, IOError => e
    raise StreamClosedException.new("Could not read from stream: #{e.message}")
  # ensure
  #   @request.release_connection
  end
end

#callObject

Implementation of Callable#call Used by Manticore::Client to invoke the request tied to this response. Users should never call this directly.



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/manticore/response.rb', line 43

def call
  raise "Already called" if @called
  @called = true
  begin
    @client.execute @request, self, @context
    execute_complete
    return self
  rescue Java::JavaNet::SocketTimeoutException, Java::OrgApacheHttpConn::ConnectTimeoutException => e
    ex = Manticore::Timeout.new(e.cause || e.message)
  rescue Java::JavaNet::SocketException => e
    ex = Manticore::SocketException.new(e.cause || e.message)
  rescue Java::OrgApacheHttpClient::ClientProtocolException, Java::JavaxNetSsl::SSLHandshakeException, Java::OrgApacheHttpConn::HttpHostConnectException,
         Java::OrgApacheHttp::NoHttpResponseException, Java::OrgApacheHttp::ConnectionClosedException => e
    ex = Manticore::ClientProtocolException.new(e.cause || e.message)
  rescue Java::JavaNet::UnknownHostException => e
    ex = Manticore::ResolutionFailure.new(e.cause || e.message)
  end
  @exception = ex
  @handlers[:failure].call ex
  execute_complete
end

#called?Boolean

Returns true if this response has been called (requested and populated) yet

Returns:

  • (Boolean)


111
112
113
# File 'lib/manticore/response.rb', line 111

def called?
  !!@called
end

#cookiesArray<Manticore::Cookie>

Returns an array of Cookies associated with this request’s execution context

Returns:



149
150
151
152
153
154
155
156
157
158
159
# File 'lib/manticore/response.rb', line 149

def cookies
  call_once
  @cookies ||= begin
    @context.get_cookie_store.get_cookies.inject({}) do |all, java_cookie|
      c = Cookie.from_java(java_cookie)
      all[c.name] ||= []
      all[c.name] << c
      all
    end
  end
end

#final_urlString

Fetch the final resolved URL for this response. Will call the request if it has not been called yet.

Returns:

  • (String)


72
73
74
75
76
77
78
79
# File 'lib/manticore/response.rb', line 72

def final_url
  call_once
  last_request = context.get_attribute ExecutionContext.HTTP_REQUEST
  last_host    = context.get_attribute ExecutionContext.HTTP_TARGET_HOST
  host         = last_host.to_uri
  url          = last_request.get_uri
  URI.join(host, url.to_s)
end

#fire_and_forgetObject



65
66
67
# File 'lib/manticore/response.rb', line 65

def fire_and_forget
  @client.executor.submit self
end

#lengthInteger

Returns the length of the response body. Returns -1 if content-length is not present in the response.

Returns:

  • (Integer)


142
143
144
# File 'lib/manticore/response.rb', line 142

def length
  (headers["content-length"] || -1).to_i
end

#messageString

Return the response text for a request as a string (Not Found, Ok, Bad Request, etc). Will call the request if it has not been called yet.

Returns:

  • (String)

    The response code text



134
135
136
137
# File 'lib/manticore/response.rb', line 134

def message
  call_once
  @message
end

#on_cancelled(&block) ⇒ Object Also known as: cancelled, cancellation, on_cancellation

Set handler for cancelled requests

Parameters:

  • block

    Proc which will be invoked on a on a cancelled response.

Returns:

  • self



186
187
188
189
# File 'lib/manticore/response.rb', line 186

def on_cancelled(&block)
  @handlers[:cancelled] = block
  self
end

#on_complete(&block) ⇒ Object Also known as: complete, completed, on_completed

Set handler for cancelled requests

Parameters:

  • block

    Proc which will be invoked on a on a cancelled response.

Returns:

  • self



198
199
200
201
# File 'lib/manticore/response.rb', line 198

def on_complete(&block)
  @handlers[:complete] = Array(@handlers[:complete]).compact + [block]
  self
end

#on_failure(&block) ⇒ Object Also known as: failure, fail

Set handler for failure responses

Parameters:

  • block

    Proc which will be invoked on a on a failed response. Block will receive an exception object.

Returns:

  • self



175
176
177
178
# File 'lib/manticore/response.rb', line 175

def on_failure(&block)
  @handlers[:failure] = block
  self
end

#on_success(&block) ⇒ Object Also known as: success

Set handler for success responses

Parameters:

  • block

    Proc which will be invoked on a successful response. Block will receive |response, request|

Returns:

  • self



165
166
167
168
# File 'lib/manticore/response.rb', line 165

def on_success(&block)
  @handlers[:success] = block
  self
end

#times_retriedObject



206
207
208
# File 'lib/manticore/response.rb', line 206

def times_retried
  @context.get_attribute("retryCount") || 0
end