Class: Manticore::Response
- Inherits:
-
Object
- Object
- Manticore::Response
- 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
Instance Attribute Summary collapse
-
#callback_result ⇒ Object
readonly
Value returned from any given on_success/response block.
-
#called ⇒ Object
readonly
Returns the value of attribute called.
-
#code ⇒ Integer
readonly
Return the response code from this request as an integer.
-
#context ⇒ HttpContext
readonly
Context associated with this request/response.
-
#headers ⇒ Array<string, obj>
readonly
Return a hash of headers from this response.
-
#request ⇒ Object
readonly
Returns the value of attribute request.
Instance Method Summary collapse
-
#[](key) ⇒ String
Return the value of a single response header.
-
#body(&block) ⇒ String
(also: #read_body)
Fetch the body content of this response.
-
#call ⇒ Object
Implementation of Callable#call Used by Manticore::Client to invoke the request tied to this response.
-
#called? ⇒ Boolean
Returns true if this response has been called (requested and populated) yet.
-
#cookies ⇒ Array<Manticore::Cookie>
Returns an array of Cookies associated with this request’s execution context.
-
#final_url ⇒ String
Fetch the final resolved URL for this response.
- #fire_and_forget ⇒ Object
-
#initialize(client, request, context, &block) ⇒ Response
constructor
Creates a new Response.
-
#length ⇒ Integer
Returns the length of the response body.
-
#message ⇒ String
Return the response text for a request as a string (Not Found, Ok, Bad Request, etc).
-
#on_cancelled(&block) ⇒ Object
(also: #cancelled, #cancellation, #on_cancellation)
Set handler for cancelled requests.
-
#on_complete(&block) ⇒ Object
(also: #complete, #completed, #on_completed)
Set handler for cancelled requests.
-
#on_failure(&block) ⇒ Object
(also: #failure, #fail)
Set handler for failure responses.
-
#on_success(&block) ⇒ Object
(also: #success)
Set handler for success responses.
- #times_retried ⇒ Object
Constructor Details
#initialize(client, request, context, &block) ⇒ Response
Creates a new Response
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_result ⇒ Object (readonly)
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 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 |
# 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. def call raise "Already called" if @called @called = true begin @client.execute @request, self, @context rescue Java::JavaNet::SocketTimeoutException => e ex = Manticore::SocketTimeout rescue Java::OrgApacheHttpConn::ConnectTimeoutException => e ex = Manticore::ConnectTimeout rescue Java::JavaNet::SocketException => e ex = Manticore::SocketException rescue Java::OrgApacheHttpClient::ClientProtocolException, Java::JavaxNetSsl::SSLHandshakeException, Java::OrgApacheHttpConn::HttpHostConnectException, Java::OrgApacheHttp::NoHttpResponseException, Java::OrgApacheHttp::ConnectionClosedException => e ex = Manticore::ClientProtocolException rescue Java::JavaNet::UnknownHostException => e ex = Manticore::ResolutionFailure rescue Java::JavaLang::IllegalArgumentException => e ex = Manticore::InvalidArgumentException rescue Java::JavaLang::Exception => e # Handle anything we may have missed from java ex = Manticore::UnknownException rescue StandardError => e @exception = e end # TODO: If calling async, execute_complete may fail and then silently swallow exceptions. How do we fix that? if ex || @exception @exception ||= ex.new(e.cause || e.) @handlers[:failure].call @exception execute_complete nil else execute_complete self end 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.}") # 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 value of a single response header. Will call the request if it has not been called yet. # # @return [String] Value of the header, or nil if not present def [](key) headers[key.downcase] 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 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 call_once @cookies ||= begin @context...inject({}) do |all, | c = Cookie.from_java() 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 {|h| h.call(self) } end end |
#called ⇒ Object (readonly)
Returns the value of attribute called.
23 24 25 |
# File 'lib/manticore/response.rb', line 23 def called @called end |
#code ⇒ Integer (readonly)
Return the response code from this request as an integer. Will call the request if it has not been called yet.
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 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 |
# 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. def call raise "Already called" if @called @called = true begin @client.execute @request, self, @context rescue Java::JavaNet::SocketTimeoutException => e ex = Manticore::SocketTimeout rescue Java::OrgApacheHttpConn::ConnectTimeoutException => e ex = Manticore::ConnectTimeout rescue Java::JavaNet::SocketException => e ex = Manticore::SocketException rescue Java::OrgApacheHttpClient::ClientProtocolException, Java::JavaxNetSsl::SSLHandshakeException, Java::OrgApacheHttpConn::HttpHostConnectException, Java::OrgApacheHttp::NoHttpResponseException, Java::OrgApacheHttp::ConnectionClosedException => e ex = Manticore::ClientProtocolException rescue Java::JavaNet::UnknownHostException => e ex = Manticore::ResolutionFailure rescue Java::JavaLang::IllegalArgumentException => e ex = Manticore::InvalidArgumentException rescue Java::JavaLang::Exception => e # Handle anything we may have missed from java ex = Manticore::UnknownException rescue StandardError => e @exception = e end # TODO: If calling async, execute_complete may fail and then silently swallow exceptions. How do we fix that? if ex || @exception @exception ||= ex.new(e.cause || e.) @handlers[:failure].call @exception execute_complete nil else execute_complete self end 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.}") # 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 value of a single response header. Will call the request if it has not been called yet. # # @return [String] Value of the header, or nil if not present def [](key) headers[key.downcase] 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 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 call_once @cookies ||= begin @context...inject({}) do |all, | c = Cookie.from_java() 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 {|h| h.call(self) } end end |
#context ⇒ HttpContext (readonly)
Returns 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 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 |
# 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. def call raise "Already called" if @called @called = true begin @client.execute @request, self, @context rescue Java::JavaNet::SocketTimeoutException => e ex = Manticore::SocketTimeout rescue Java::OrgApacheHttpConn::ConnectTimeoutException => e ex = Manticore::ConnectTimeout rescue Java::JavaNet::SocketException => e ex = Manticore::SocketException rescue Java::OrgApacheHttpClient::ClientProtocolException, Java::JavaxNetSsl::SSLHandshakeException, Java::OrgApacheHttpConn::HttpHostConnectException, Java::OrgApacheHttp::NoHttpResponseException, Java::OrgApacheHttp::ConnectionClosedException => e ex = Manticore::ClientProtocolException rescue Java::JavaNet::UnknownHostException => e ex = Manticore::ResolutionFailure rescue Java::JavaLang::IllegalArgumentException => e ex = Manticore::InvalidArgumentException rescue Java::JavaLang::Exception => e # Handle anything we may have missed from java ex = Manticore::UnknownException rescue StandardError => e @exception = e end # TODO: If calling async, execute_complete may fail and then silently swallow exceptions. How do we fix that? if ex || @exception @exception ||= ex.new(e.cause || e.) @handlers[:failure].call @exception execute_complete nil else execute_complete self end 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.}") # 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 value of a single response header. Will call the request if it has not been called yet. # # @return [String] Value of the header, or nil if not present def [](key) headers[key.downcase] 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 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 call_once @cookies ||= begin @context...inject({}) do |all, | c = Cookie.from_java() 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 {|h| h.call(self) } end end |
#headers ⇒ Array<string, obj> (readonly)
Return a hash of headers from this response. Will call the request if it has not been called yet.
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 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 |
# 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. def call raise "Already called" if @called @called = true begin @client.execute @request, self, @context rescue Java::JavaNet::SocketTimeoutException => e ex = Manticore::SocketTimeout rescue Java::OrgApacheHttpConn::ConnectTimeoutException => e ex = Manticore::ConnectTimeout rescue Java::JavaNet::SocketException => e ex = Manticore::SocketException rescue Java::OrgApacheHttpClient::ClientProtocolException, Java::JavaxNetSsl::SSLHandshakeException, Java::OrgApacheHttpConn::HttpHostConnectException, Java::OrgApacheHttp::NoHttpResponseException, Java::OrgApacheHttp::ConnectionClosedException => e ex = Manticore::ClientProtocolException rescue Java::JavaNet::UnknownHostException => e ex = Manticore::ResolutionFailure rescue Java::JavaLang::IllegalArgumentException => e ex = Manticore::InvalidArgumentException rescue Java::JavaLang::Exception => e # Handle anything we may have missed from java ex = Manticore::UnknownException rescue StandardError => e @exception = e end # TODO: If calling async, execute_complete may fail and then silently swallow exceptions. How do we fix that? if ex || @exception @exception ||= ex.new(e.cause || e.) @handlers[:failure].call @exception execute_complete nil else execute_complete self end 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.}") # 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 value of a single response header. Will call the request if it has not been called yet. # # @return [String] Value of the header, or nil if not present def [](key) headers[key.downcase] 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 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 call_once @cookies ||= begin @context...inject({}) do |all, | c = Cookie.from_java() 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 {|h| h.call(self) } end end |
#request ⇒ Object (readonly)
Returns the value of attribute request.
23 24 25 |
# File 'lib/manticore/response.rb', line 23 def request @request end |
Instance Method Details
#[](key) ⇒ String
Return the value of a single response header. Will call the request if it has not been called yet.
140 141 142 |
# File 'lib/manticore/response.rb', line 140 def [](key) headers[key.downcase] end |
#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.
110 111 112 113 114 115 116 117 118 119 120 121 |
# File 'lib/manticore/response.rb', line 110 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.}") # ensure # @request.release_connection end end |
#call ⇒ Object
Implementation of Callable#call Used by Manticore::Client to invoke the request tied to this response.
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 |
# File 'lib/manticore/response.rb', line 43 def call raise "Already called" if @called @called = true begin @client.execute @request, self, @context rescue Java::JavaNet::SocketTimeoutException => e ex = Manticore::SocketTimeout rescue Java::OrgApacheHttpConn::ConnectTimeoutException => e ex = Manticore::ConnectTimeout rescue Java::JavaNet::SocketException => e ex = Manticore::SocketException rescue Java::OrgApacheHttpClient::ClientProtocolException, Java::JavaxNetSsl::SSLHandshakeException, Java::OrgApacheHttpConn::HttpHostConnectException, Java::OrgApacheHttp::NoHttpResponseException, Java::OrgApacheHttp::ConnectionClosedException => e ex = Manticore::ClientProtocolException rescue Java::JavaNet::UnknownHostException => e ex = Manticore::ResolutionFailure rescue Java::JavaLang::IllegalArgumentException => e ex = Manticore::InvalidArgumentException rescue Java::JavaLang::Exception => e # Handle anything we may have missed from java ex = Manticore::UnknownException rescue StandardError => e @exception = e end # TODO: If calling async, execute_complete may fail and then silently swallow exceptions. How do we fix that? if ex || @exception @exception ||= ex.new(e.cause || e.) @handlers[:failure].call @exception execute_complete nil else execute_complete self end end |
#called? ⇒ Boolean
Returns true if this response has been called (requested and populated) yet
125 126 127 |
# File 'lib/manticore/response.rb', line 125 def called? !!@called end |
#cookies ⇒ Array<Manticore::Cookie>
Returns an array of Cookies associated with this request’s execution context
170 171 172 173 174 175 176 177 178 179 180 |
# File 'lib/manticore/response.rb', line 170 def call_once @cookies ||= begin @context...inject({}) do |all, | c = Cookie.from_java() all[c.name] ||= [] all[c.name] << c all end end end |
#final_url ⇒ String
Fetch the final resolved URL for this response. Will call the request if it has not been called yet.
86 87 88 89 90 91 92 93 |
# File 'lib/manticore/response.rb', line 86 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_forget ⇒ Object
79 80 81 |
# File 'lib/manticore/response.rb', line 79 def fire_and_forget @client.executor.submit self end |
#length ⇒ Integer
Returns the length of the response body. Returns -1 if content-length is not present in the response.
163 164 165 |
# File 'lib/manticore/response.rb', line 163 def length (headers["content-length"] || -1).to_i end |
#message ⇒ String
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.
155 156 157 158 |
# File 'lib/manticore/response.rb', line 155 def call_once @message end |
#on_cancelled(&block) ⇒ Object Also known as: cancelled, cancellation, on_cancellation
Set handler for cancelled requests
207 208 209 210 |
# File 'lib/manticore/response.rb', line 207 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
219 220 221 222 |
# File 'lib/manticore/response.rb', line 219 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
196 197 198 199 |
# File 'lib/manticore/response.rb', line 196 def on_failure(&block) @handlers[:failure] = block self end |
#on_success(&block) ⇒ Object Also known as: success
Set handler for success responses
186 187 188 189 |
# File 'lib/manticore/response.rb', line 186 def on_success(&block) @handlers[:success] = block self end |
#times_retried ⇒ Object
227 228 229 |
# File 'lib/manticore/response.rb', line 227 def times_retried @context.get_attribute("retryCount") || 0 end |