Package core :: Module http |
[hide private]
[frames] | no frames]

# Source Code for Module core.http

       1  # Copyright 2011-2012 the original author or authors.
       2  #
       3  # Licensed under the Apache License, Version 2.0 (the "License");
       4  # you may not use this file except in compliance with the License.
       5  # You may obtain a copy of the License at
       6  #
       7  #      http://www.apache.org/licenses/LICENSE-2.0
       8  #
       9  # Unless required by applicable law or agreed to in writing, software
      10  # distributed under the License is distributed on an "AS IS" BASIS,
      11  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      12  # See the License for the specific language governing permissions and
      13  # limitations under the License.
      14
      15  """
      16  This module adds the http support to the python vert.x platform
      17  """
      18
      19  import org.vertx.java.deploy.impl.VertxLocator
      20  import org.vertx.java.core.http
      21  import core.tcp_support
      22  import core.ssl_support
      23  import core.buffer
      24  import core.streams
      25
      26  from core.javautils import map_from_java, map_to_java
      27  from core.handlers import CloseHandler, ClosedHandler, ExceptionHandler
      28  from core.handlers import DoneHandler, ContinueHandler, BufferHandler
      29
      30  __author__ = "Scott Horn"
      31  __email__ = "scott@hornmicro.com"
      32  __credits__ = "Based entirely on work by Tim Fox http://tfox.org"
      33
      34 -class HttpServer(core.tcp_support.TCPSupport, core.ssl_support.SSLSupport, object):
      35      """ An HTTP and websockets server """
      36 -    def __init__(self, **kwargs):
      37          self.java_obj = org.vertx.java.deploy.impl.VertxLocator.vertx.createHttpServer()
      38          for item in kwargs.keys():
      39             setattr(self, item, kwargs[item])
      40
      41 -    def request_handler(self, handler):
      42          """Set the HTTP request handler for the server.
      43          As HTTP requests arrive on the server a new HttpServerRequest instance will be created and passed to the handler.
      44
      45          Keyword arguments:
      46          @param handler: the function used to handle the request.
      47
      48          @return: self
      49          """
      50          self.java_obj.requestHandler(HttpServerRequestHandler(handler))
      51          return self
      52
      53 -    def websocket_handler(self, handler):
      54          """Set the websocket handler for the server.
      55          As websocket requests arrive on the server a new ServerWebSocket instance will be created and passed to the handler.
      56
      57          Keyword arguments:
      58          @param handler: the function used to handle the request.
      59
      60          """
      61          self.java_obj.websocketHandler(ServerWebSocketHandler(handler))
      62          return self
      63
      64 -    def listen(self, port, host=None):
      65          """Instruct the server to listen for incoming connections. If host is None listens on all.
      66
      67          Keyword arguments:
      68          @param port: The port to listen on.
      69          @param host: The host name or ip address to listen on. (default None)
      70
      71          """
      72          if host is None:
      73              self.java_obj.listen(port)
      74          else:
      75              self.java_obj.listen(port, host)
      76
      77 -    def client_auth_required(self, val):
      78          """ Client authentication is an extra level of security in SSL, and requires clients to provide client certificates.
      79          Those certificates must be added to the server trust store.
      80
      81          Keyword arguments:
      82          @param val: If true then the server will request client authentication from any connecting clients, if they
      83          do not authenticate then they will not make a connection.
      84
      85          """
      86          self.java_obj.setClientAuthRequired(val)
      87          return self
      88
      89 -    def close(self, handler=None):
      90          """ Close the server. Any open HTTP connections will be closed. This can be used as a decorator.
      91
      92          Keyword arguments:
      93          @param handler: a handler that is called when the connection is closed. The handler is wrapped in a ClosedHandler.
      94
      95          """
      96          if handler is None:
      97              self.java_obj.close()
      98          else:
      99              self.java_obj.close(CloseHandler(handler))
     100
     101 -    def _to_java_server(self):
     102          """ private """
     103          return self.java_obj
     104
     105 -class HttpClient(core.ssl_support.SSLSupport, core.tcp_support.TCPSupport, object):
     106      """ An HTTP client.
     107       A client maintains a pool of connections to a specific host, at a specific port. The HTTP connections can act
     108       as pipelines for HTTP requests.
     109       It is used as a factory for HttpClientRequest instances which encapsulate the actual HTTP requests. It is also
     110       used as a factory for HTML5 WebSocket websockets.
     111      """
     112 -    def __init__(self, **kwargs):
     113          self.java_obj = org.vertx.java.deploy.impl.VertxLocator.vertx.createHttpClient()
     114          for item in kwargs.keys():
     115             setattr(self, item, kwargs[item])
     116
     117 -    def exception_handler(self, handler):
     118          """ Set the exception handler.
     119
     120          Keyword arguments:
     121          @param handler: function to be used as the handler
     122          """
     123          self.java_obj.exceptionHandler(ExceptionHandler(handler))
     124          return self
     125
     126 -    def get_max_pool_size(self):
     127          """The maxium number of connections this client will pool."""
     128          return self.java_obj.getMaxPoolSize
     129
     130 -    def set_max_pool_size(self, val):
     131          """ Set the maximum pool size.
     132          The client will maintain up to this number of HTTP connections in an internal pool
     133
     134          Keyword arguments:
     135          @param val: The maximum number of connections (default to 1).
     136          """
     137          self.java_obj.setMaxPoolSize(val)
     138          return self
     139
     140      max_pool_size = property(get_max_pool_size, set_max_pool_size)
     141
     142 -    def set_keep_alive(self, val):
     143          """If val is true then, after the request has ended the connection will be returned to the pool
     144          where it can be used by another request. In this manner, many HTTP requests can be pipe-lined over an HTTP connection.
     145          Keep alive connections will not be closed until the close method is invoked.
     146          If val is false then a new connection will be created for each request and it won't ever go in the pool,
     147          the connection will closed after the response has been received. Even with no keep alive, the client will not allow more
     148          than max_pool_size connections to be created at any one time.
     149
     150          Keyword arguments:
     151          @param val: The value to use for keep_alive
     152          """
     153          self.java_obj.setTCPKeepAlive(val)
     154          return self
     155
     156      keep_alive = property(fset=set_keep_alive)
     157
     158 -    def set_trust_all(self, val):
     159          """Should the client trust ALL server certificates?
     160
     161          Keyword arguments:
     162          @param val: If val is set to true then the client will trust ALL server certificates and will not attempt to authenticate them
     163          against it's local client trust store. The default value is false.
     164          Use this method with caution!
     165          """
     166          self.java_obj.setTrustAll(val)
     167          return self
     168
     169      trust_all = property(fset=set_trust_all)
     170
     171 -    def set_port(self, val):
     172          """Set the port that the client will attempt to connect to on the server on. The default value is 80
     173
     174          Keyword arguments:
     175          @param val: The port value.
     176          """
     177          self.java_obj.setPort(val)
     178          return self
     179
     180      port = property(fset=set_port)
     181
     182 -    def set_host(self, val):
     183          """Set the host name or ip address that the client will attempt to connect to on the server on.
     184
     185          Keyword arguments:
     186          @param val: The host name or ip address to connect to.
     187          """
     188          self.java_obj.setHost(val)
     189          return self
     190
     191      host = property(fset=set_host)
     192
     193 -    def connect_web_socket(self, uri, handler):
     194          """Attempt to connect an HTML5 websocket to the specified URI.
     195          The connect is done asynchronously and the handler is called with a WebSocket on success.
     196
     197          Keyword arguments:
     198          @param uri: A relative URI where to connect the websocket on the host, e.g. /some/path
     199          @param handler: The handler to be called with the WebSocket
     200          """
     201          self.java_obj.connectWebsocket(uri, WebSocketHandler(handler))
     202
     203 -    def get_now(self, uri, handler, **headers):
     204          """This is a quick version of the get method where you do not want to do anything with the request
     205          before sing.
     206          With this method the request is immediately sent.
     207          When an HTTP response is received from the server the handler is called passing in the response.
     208
     209          Keyword arguments:
     210          @param uri: A relative URI where to perform the GET on the server.
     211          @param handler: The handler to be called with the HttpClientResponse
     212          @param headers: A dictionary of headers to pass with the request.
     213          """
     214          if len(headers) == 0:
     215              self.java_obj.getNow(uri, HttpClientResponseHandler(handler))
     216          else:
     217              self.java_obj.getNow(uri, map_to_java(headers), HttpClientResponseHandler(handler))
     218
     219 -    def options(self, uri, handler):
     220          """This method returns an HttpClientRequest instance which represents an HTTP OPTIONS request with the specified uri.
     221          When an HTTP response is received from the server the handler is called passing in the response.
     222
     223          Keyword arguments:
     224          @param uri: A relative URI where to perform the OPTIONS on the server.
     225          @param handler: The handler to be called with the HttpClientResponse
     226          """
     227          return HttpClientRequest(self.java_obj.options(uri, HttpClientResponseHandler(handler)))
     228
     229 -    def get(self, uri, handler):
     230          """This method returns an HttpClientRequest instance which represents an HTTP GET request with the specified uri.
     231          When an HTTP response is received from the server the handler is called passing in the response.
     232
     233          Keyword arguments:
     234          @param uri: A relative URI where to perform the GET on the server.
     235          @param handler: The handler to be called with the HttpClientResponse
     236          """
     237          return HttpClientRequest(self.java_obj.get(uri, HttpClientResponseHandler(handler)))
     238
     239 -    def head(self, uri, handler):
     240          """This method returns an HttpClientRequest instance which represents an HTTP HEAD request with the specified uri.
     241          When an HTTP response is received from the server the handler is called passing in the response.
     242
     243          Keyword arguments:
     244          @param uri: A relative URI where to perform the HEAD on the server.
     245          @param handler: The handler to be called with the HttpClientResponse
     246          """
     247          return HttpClientRequest(self.java_obj.head(uri, HttpClientResponseHandler(handler)))
     248
     249 -    def post(self, uri, handler):
     250          """This method returns an HttpClientRequest instance which represents an HTTP POST request with the specified uri.
     251          When an HTTP response is received from the server the handler is called passing in the response.
     252
     253          Keyword arguments:
     254          @param uri: A relative URI where to perform the POST on the server.
     255          @param handler: The handler to be called with the HttpClientResponse
     256          """
     257          return HttpClientRequest(self.java_obj.post(uri, HttpClientResponseHandler(handler)))
     258
     259 -    def put(self, uri, handler):
     260          """This method returns an HttpClientRequest instance which represents an HTTP PUT request with the specified uri.
     261          When an HTTP response is received from the server the handler is called passing in the response.
     262
     263          Keyword arguments:
     264          @param uri: A relative URI where to perform the PUT on the server.
     265          @param handler: The handler to be called with the HttpClientResponse
     266          """
     267          return HttpClientRequest(self.java_obj.put(uri, HttpClientResponseHandler(handler)))
     268
     269 -    def delete(self, uri, handler):
     270          """This method returns an HttpClientRequest instance which represents an HTTP DELETE request with the specified uri.
     271          When an HTTP response is received from the server the handler is called passing in the response.
     272
     273          Keyword arguments:
     274          @param uri: A relative URI where to perform the DELETE on the server.
     275          @param handler: The handler to be called with the HttpClientResponse
     276          """
     277          return HttpClientRequest(self.java_obj.delete(uri, HttpClientResponseHandler(handler)))
     278
     279 -    def trace(self, uri, handler):
     280          """ This method returns an HttpClientRequest instance which represents an HTTP TRACE request with the specified uri.
     281          When an HTTP response is received from the server the handler is called passing in the response.
     282
     283          Keyword arguments:
     284          @param uri: A relative URI where to perform the TRACE on the server.
     285          handler. The handler to be called with the HttpClientResponse
     286          """
     287          return HttpClientRequest(self.java_obj.trace(uri, HttpClientResponseHandler(handler)))
     288
     289 -    def connect(self, uri, handler):
     290          """ This method returns an HttpClientRequest instance which represents an HTTP CONNECT request with the specified uri.
     291          When an HTTP response is received from the server the handler is called passing in the response.
     292
     293          Keyword arguments:
     294          @param uri: A relative URI where to perform the CONNECT on the server.
     295          @param handler: The handler to be called with the HttpClientResponse
     296          """
     297          return HttpClientRequest(self.java_obj.connect(uri, HttpClientResponseHandler(handler)))
     298
     299 -    def patch(self, uri, handler):
     300          """ This method returns an HttpClientRequest instance which represents an HTTP PATCH request with the specified uri.
     301          When an HTTP response is received from the server the handler is called passing in the response.
     302
     303          Keyword arguments:
     304          @param uri: A relative URI where to perform the PATCH on the server.
     305          @param handler: The handler to be called with the HttpClientResponse
     306          """
     307          return HttpClientRequest(self.java_obj.patch(uri, HttpClientResponseHandler(handler)))
     308
     309 -    def request(self, method, uri, handler):
     310          """This method returns an HttpClientRequest instance which represents an HTTP request with the specified method and uri.
     311          When an HTTP response is received from the server the handler is called passing in the response.
     312          method. The HTTP method. Can be one of OPTIONS, HEAD, GET, POST, PUT, DELETE, TRACE, CONNECT.
     313
     314          Keyword arguments:
     315          @param uri: A relative URI where to perform the OPTIONS on the server.
     316          @param handler: The handler to be called with the HttpClientResponse
     317          """
     318          return HttpClientRequest(self.java_obj.request(method, uri, HttpClientResponseHandler(handler)))
     319
     320 -    def close(self):
     321          """Close the client. Any unclosed connections will be closed."""
     322          self.java_obj.close()
     323
     324 -class HttpClientRequest(core.streams.WriteStream):
     325      """Instances of this class are created by an HttpClient instance, via one of the methods corresponding to the
     326       specific HTTP methods, or the generic HttpClient request method.
     327
     328       Once an instance of this class has been obtained, headers can be set on it, and data can be written to its body,
     329       if required. Once you are ready to send the request, the end method must called.
     330
     331       Nothing is sent until the request has been internally assigned an HTTP connection. The HttpClient instance
     332       will return an instance of this class immediately, even if there are no HTTP connections available in the pool. Any requests
     333       sent before a connection is assigned will be queued internally and actually sent when an HTTP connection becomes
     334       available from the pool.
     335
     336       The headers of the request are actually sent either when the end method is called, or, when the first
     337       part of the body is written, whichever occurs first.
     338
     339       This class supports both chunked and non-chunked HTTP.
     340      """
     341 -    def __init__(self, java_obj):
     342          self.java_obj = java_obj
     343          self.headers_dict = None
     344
     345      @property
     346 -    def headers(self):
     347          """ Hash of headers for the request"""
     348          if self.headers_dict is None:
     349              self.headers_dict = map_from_java(self.java_obj.headers())
     350          return self.headers_dict
     351
     352 -    def put_header(self, key, value):
     353          """Inserts a header into the request.
     354
     355          Keyword arguments:
     356          @param key: The header key
     357          @param value: The header value. to_s will be called on the value to determine the actual String value to insert.
     358
     359          @return: self so multiple operations can be chained.
     360          """
     361          self.java_obj.putHeader(key, value)
     362          return self
     363
     364 -    def write_buffer(self, chunk, handler=None):
     365          """Write a to the request body.
     366
     367          Keyword arguments:
     368          @param chunk: The buffer to write.
     369          @param handler: The handler will be called when the buffer has actually been written to the wire.
     370
     371          @return:  self So multiple operations can be chained.
     372          """
     373          self.java_obj.write(chunk._to_java_buffer(), DoneHandler(handler))
     374          return self
     375
     376 -    def write_str(self, str, enc="UTF-8", handler=None):
     377          """Write a to the request body.
     378
     379          Keyword arguments:
     380          @param str: The string to write.
     381          @param enc: The encoding to use.
     382          @param handler: The handler will be called when the buffer has actually been written to the wire.
     383
     384          @return: self So multiple operations can be chained.
     385          """
     386          if handler is None:
     387              self.java_obj.write(str, enc)
     388          else:
     389              self.java_obj.write(str, enc, DoneHandler(handler))
     390          return self
     391
     392 -    def send_head(self):
     393          """Forces the head of the request to be written before end is called on the request. This is normally used
     394          to implement HTTP 100-continue handling, see continue_handler for more information.
     395
     396          @return: self So multiple operations can be chained.
     397          """
     398          self.java_obj.sendHead()
     399          return self
     400
     401 -    def end(self):
     402          """Ends the request. If no data has been written to the request body, and send_head has not been called then
     403          the actual request won't get written until this method gets called.
     404          Once the request has ended, it cannot be used any more, and if keep alive is true the underlying connection will
     405          be returned to the HttpClient pool so it can be assigned to another request.
     406          """
     407          self.java_obj.end()
     408
     409 -    def write_str_and_end(self, str, enc="UTF-8"):
     410          """Same as write_buffer_and_end but writes a String
     411
     412          Keyword arguments:
     413          @param str: The String to write
     414          @param enc: The encoding
     415          """
     416          self.java_obj.end(str, enc)
     417
     418 -    def write_buffer_and_end(self, chunk):
     419          """Same as end but writes some data to the response body before ending. If the response is not chunked and
     420          no other data has been written then the Content-Length header will be automatically set
     421
     422          Keyword arguments:
     423          @param chunk: The Buffer to write
     424          """
     425          self.java_obj.end(chunk._to_java_buffer())
     426
     427 -    def set_chunked(self, val):
     428          """Sets whether the request should used HTTP chunked encoding or not.
     429
     430          Keyword arguments:
     431          @param val: If val is true, this request will use HTTP chunked encoding, and each call to write to the body
     432          will correspond to a new HTTP chunk sent on the wire. If chunked encoding is used the HTTP header
     433          'Transfer-Encoding' with a value of 'Chunked' will be automatically inserted in the request.
     434
     435          If chunked is false, this request will not use HTTP chunked encoding, and therefore if any data is written the
     436          body of the request, the total size of that data must be set in the 'Content-Length' header before any
     437          data is written to the request body.
     438
     439          @return: self So multiple operations can be chained.
     440          """
     441          self.java_obj.setChunked(val)
     442          return self
     443
     444      chunked = property(fset=set_chunked)
     445
     446 -    def continue_handler(self, handler):
     447          """If you send an HTTP request with the header 'Expect' set to the value '100-continue'
     448          and the server responds with an interim HTTP response with a status code of '100' and a continue handler
     449          has been set using this method, then the handler will be called.
     450          You can then continue to write data to the request body and later end it. This is normally used in conjunction with
     451          the send_head method to force the request header to be written before the request has ended.
     452
     453          Keyword arguments:
     454          @param handler: The handler
     455          """
     456          self.java_obj.continueHandler(ContinueHandler(handler))
     457
     458
     459 -class HttpClientResponse(core.streams.ReadStream):
     460      """Encapsulates a client-side HTTP response.
     461
     462      An instance of this class is provided to the user via a handler that was specified when one of the
     463      HTTP method operations, or the generic HttpClientrequest method was called on an instance of HttpClient.
     464      """
     465 -    def __init__(self, java_obj):
     466          self.java_obj = java_obj
     467          self.headers_dict = None
     468          self.trailers_dict = None
     469
     470      @property
     471 -    def status_code(self):
     472          """return the HTTP status code of the response."""
     473          return self.java_obj.statusCode
     474
     475 -    def header(self, key):
     476          """Get a header value
     477
     478          Keyword arguments:
     479          @param key: The key of the header.
     480
     481          return the header value.
     482          """
     483          return self.java_obj.getHeader(key)
     484
     485      @property
     486 -    def headers(self):
     487          """Get all the headers in the response.
     488          If the response contains multiple headers with the same key, the values
     489          will be concatenated together into a single header with the same key value, with each value separated by a comma,
     490          as specified by {http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.htmlsec4.2}.
     491          return a dictionary of headers.
     492          """
     493          if self.headers_dict is None:
     494              self.headers_dict = map_from_java(self.java_obj.headers())
     495          return self.headers_dict
     496
     497      @property
     498 -    def trailers(self):
     499          """Get all the trailers in the response.
     500          If the response contains multiple trailers with the same key, the values
     501          will be concatenated together into a single header with the same key value, with each value separated by a comma,
     502          as specified by {http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.htmlsec4.2}.
     503          Trailers will only be available in the response if the server has sent a HTTP chunked response where headers have
     504          been inserted by the server on the last chunk. In such a case they won't be available on the client until the last chunk has
     505          been received.
     506
     507          return a dictionary of trailers."""
     508          if self.trailers_dict is None:
     509            self.trailers_dict = map_from_java(self.java_obj.trailers())
     510          return self.trailers_dict
     511
     512 -    def body_handler(self, handler):
     513          """Set a handler to receive the entire body in one go - do not use this for large bodies"""
     514          self.java_obj.bodyHandler(BufferHandler(handler))
     515
     516 -class HttpServerRequest(core.streams.ReadStream):
     517      """ Encapsulates a server-side HTTP request.
     518
     519      An instance of this class is created for each request that is handled by the server and is passed to the user via the
     520      handler specified using HttpServer.request_handler.
     521
     522      Each instance of this class is associated with a corresponding HttpServerResponse instance via the property response.
     523      """
     524 -    def __init__(self, java_obj):
     525          self.java_obj = java_obj
     526          self.http_server_response = HttpServerResponse(java_obj.response)
     527          self.headers_dict = None
     528          self.params_dict = None
     529
     530      @property
     531 -    def method(self):
     532          """ The HTTP method, one of HEAD, OPTIONS, GET, POST, PUT, DELETE, CONNECT, TRACE """
     533          return self.java_obj.method
     534
     535      @property
     536 -    def uri(self):
     537          """ The uri of the request. For example 'http://www.somedomain.com/somepath/somemorepath/somresource.foo?someparam=32&someotherparam=x """
     538          return self.java_obj.uri
     539
     540      @property
     541 -    def path(self):
     542          """ The path part of the uri. For example /somepath/somemorepath/somresource.foo """
     543          return self.java_obj.path
     544
     545      @property
     546 -    def query(self):
     547          """ The query part of the uri. For example someparam=32&someotherparam=x """
     548          return self.java_obj.query
     549
     550      @property
     551 -    def params(self):
     552          """ The request parameters as a dictionary """
     553          if self.params_dict is None:
     554              self.params_dict = map_from_java(self.java_obj.params())
     555          return self.params_dict
     556
     557      @property
     558 -    def response(self):
     559          """ The response HttpServerResponse object."""
     560          return self.http_server_response
     561
     562      @property
     563 -    def headers(self):
     564          """ The request headers as a dictionary """
     565          if self.headers_dict is None:
     566              self.headers_dict = map_from_java(self.java_obj.headers())
     567          return self.headers_dict
     568
     569 -    def body_handler(self, handler):
     570          """ Set the body handler for this request, the handler receives a single Buffer object as a parameter.
     571          This can be used as a decorator.
     572
     573          Keyword arguments:
     574          @param handler: a handler that is called when the body has been received. The handler is wrapped in a BufferHandler.
     575
     576          """
     577          self.java_obj.bodyHandler(BufferHandler(handler))
     578
     579 -    def _to_java_request(self):
     580          return self.java_obj
     581
     582 -class HttpServerResponse(core.streams.WriteStream):
     583      """Encapsulates a server-side HTTP response.
     584
     585      An instance of this class is created and associated to every instance of HttpServerRequest that is created.
     586
     587      It allows the developer to control the HTTP response that is sent back to the client for the corresponding HTTP
     588      request. It contains methods that allow HTTP headers and trailers to be set, and for a body to be written out
     589      to the response.
     590
     591      It also allows a file to be streamed by the kernel directly from disk to the outgoing HTTP connection,
     592      bypassing user space altogether (where supported by the underlying operating system). This is a very efficient way of
     593      serving files from the server since buffers do not have to be read one by one from the file and written to the outgoing
     594      socket.
     595
     596      """
     597 -    def __init__(self, java_obj):
     598          self.java_obj = java_obj
     599
     600 -    def get_status_code(self):
     601          """ Get the status code of the response. """
     602          return self.java_obj.statusCode
     603
     604 -    def set_status_code(self, code):
     605          """ Set the status code of the response. Default is 200 """
     606          self.java_obj.statusCode = code
     607
     608      status_code = property(get_status_code, set_status_code)
     609
     610 -    def get_status_message(self):
     611          """ Get the status message the goes with status code """
     612          return self.java_obj.statusMessage
     613
     614 -    def set_status_message(self, message):
     615          """ Set the status message for a response """
     616          self.java_obj.statusMessage = message
     617
     618      status_message = property(get_status_message, set_status_message)
     619
     620      @property
     621 -    def headers(self):
     622          """ Get a copy of the reponse headers as a dictionary """
     623          return map_from_java(self.java_obj.headers())
     624
     625 -    def put_header(self, key, value):
     626          """ Inserts a header into the response.
     627
     628          Keyword arguments:
     629          @param key: The header key
     630          @param value: The header value.
     631
     632          @return: HttpServerResponse so multiple operations can be chained.
     633          """
     634          self.java_obj.putHeader(key, value)
     635          return self
     636
     637      @property
     638 -    def trailers(self):
     639          """ Get a copy of the trailers as a dictionary """
     640          return map_from_java(self.java_obj.trailers())
     641
     642 -    def put_trailer(self, key, value):
     643          """ Inserts a trailer into the response.
     644
     645          Keyword arguments:
     646          @param key: The header key
     647          @param value: The header value.
     648          @return: HttpServerResponse so multiple operations can be chained.
     649
     650          """
     651          self.java_obj.putTrailer(key, value)
     652          return self
     653
     654 -    def write_buffer(self, buffer, handler=None):
     655          """ Write a buffer to the response. The handler (if supplied) will be called when the buffer has actually been written to the wire.
     656
     657          Keyword arguments:
     658          @param buffer: The buffer to write
     659          @param handler: The handler to be called when writing has been completed. It is wrapped in a DoneHandler (default None)
     660
     661          @return: a HttpServerResponse so multiple operations can be chained.
     662          """
     663          if handler is None:
     664              self.java_obj.writeBuffer(buffer._to_java_buffer())
     665          else:
     666              self.java_obj.writeBuffer(buffer._to_java_buffer(), DoneHandler(handler))
     667          return self
     668
     669 -    def write_str(self, str, enc="UTF-8", handler=None):
     670          """ Write a String to the response. The handler will be called when the String has actually been written to the wire.
     671
     672          Keyword arguments:
     673          @param str: The string to write
     674          @param enc: Encoding to use.
     675
     676          @param handler: The handler to be called when writing has been completed. It is wrapped in a DoneHandler (default None)
     677
     678          @return: a HttpServerResponse so multiple operations can be chained.
     679          """
     680          if handler is None:
     681              self.java_obj.write(str, enc)
     682          else:
     683              self.java_obj.write(str, enc, DoneHandler(handler))
     684          return self
     685
     686 -    def send_file(self, path):
     687          """ Tell the kernel to stream a file directly from disk to the outgoing connection, bypassing userspace altogether
     688          (where supported by the underlying operating system. This is a very efficient way to serve files.
     689
     690          Keyword arguments:
     691          @param path: Path to file to send.
     692
     693          @return: a HttpServerResponse so multiple operations can be chained.
     694          """
     695          self.java_obj.sendFile(path)
     696          return self
     697
     698 -    def set_chunked(self, val):
     699          """ Sets whether this response uses HTTP chunked encoding or not.
     700
     701          Keyword arguments:
     702          @param val: If val is true, this response will use HTTP chunked encoding, and each call to write to the body
     703          will correspond to a new HTTP chunk sent on the wire. If chunked encoding is used the HTTP header
     704          'Transfer-Encoding' with a value of 'Chunked' will be automatically inserted in the response.
     705
     706          If chunked is false, this response will not use HTTP chunked encoding, and therefore if any data is written the
     707          body of the response, the total size of that data must be set in the 'Content-Length' header before any
     708          data is written to the response body.
     709          An HTTP chunked response is typically used when you do not know the total size of the request body up front.
     710
     711          @return: a HttpServerResponse so multiple operations can be chained.
     712          """
     713          self.java_obj.setChunked(val)
     714          return self
     715
     716 -    def get_chunked(self):
     717          """ Get whether this response uses HTTP chunked encoding or not. """
     718          return self.java_obj.getChunked()
     719
     720      chunked = property(get_chunked, set_chunked)
     721
     722 -    def end(self, data=None):
     723          """ Ends the response. If no data has been written to the response body, the actual response won't get written until this method gets called.
     724          Once the response has ended, it cannot be used any more, and if keep alive is true the underlying connection will
     725          be closed.
     726
     727          Keywords arguments
     728          @param data: Optional String or Buffer to write before ending the response
     729
     730          """
     731          if data is None:
     732              self.java_obj.end()
     733          else:
     734              self.java_obj.end(data)
     735
     736 -    def close(self):
     737          """ Close the underlying TCP connection """
     738          self.java_obj.close()
     739
     740 -class WebSocket(core.streams.ReadStream, core.streams.WriteStream):
     741      """ Encapsulates an HTML 5 Websocket.
     742
     743      Instances of this class are created by an HttpClient instance when a client succeeds in a websocket handshake with a server.
     744      Once an instance has been obtained it can be used to s or receive buffers of data from the connection,
     745      a bit like a TCP socket.
     746      """
     747 -    def __init__(self, websocket):
     748          self.java_obj = websocket
     749
     750 -    def write_binary_frame(self, buffer):
     751          """
     752          Write data to the websocket as a binary frame
     753
     754          Keyword arguments:
     755          @param buffer: Buffer data to write to socket.
     756
     757          """
     758          self.java_obj.writeBinaryFrame(buffer._to_java_buffer())
     759
     760 -    def write_text_frame(self, text):
     761          """
     762          Write data to the websocket as a text frame
     763
     764          Keyword arguments:
     765          @param text: text to write to socket
     766          """
     767          self.java_obj.writeTextFrame(text)
     768
     769 -    def close(self):
     770          """ Close the websocket """
     771          self.java_obj.close()
     772
     773 -    def closed_handler(self, handler):
     774          """ Set a closed handler on the connection, the handler receives a no parameters.
     775          This can be used as a decorator.
     776
     777          Keyword arguments:
     778          handler - The handler to be called when writing has been completed. It is wrapped in a ClosedHandler.
     779          """
     780          self.java_obj.closedHandler(ClosedHandler(handler))
     781
     782 -class ServerWebSocket(WebSocket):
     783      """ Instances of this class are created when a WebSocket is accepted on the server.
     784      It extends WebSocket and adds methods to reject the WebSocket and an
     785      attribute for the path.
     786
     787      """
     788 -    def __init__(self, websocket):
     789          self.java_obj = websocket
     790
     791 -    def reject(self):
     792          """ Reject the WebSocket. Sends 404 to client """
     793          self.java_obj.reject()
     794
     795      @property
     796 -    def path(self):
     797          """ The path the websocket connect was attempted at. """
     798          return self.java_obj.path
     799
     800 -class HttpServerRequestHandler(org.vertx.java.core.Handler):
     801      """ A handler for Http Server Requests"""
     802 -    def __init__(self, handler):
     803          self.handler = handler
     804
     805 -    def handle(self, req):
     806          """ Called when a request is being handled. Argument is a HttpServerRequest object """
     807          self.handler(HttpServerRequest(req))
     808
     809 -class HttpClientResponseHandler(org.vertx.java.core.Handler):
     810      """ A handler for Http Client Responses"""
     811 -    def __init__(self, handler):
     812          self.handler = handler
     813
     814 -    def handle(self, res):
     815          """ Called when a response is being handled. Argument is a HttpClientResponse object """
     816          self.handler(HttpClientResponse(res))
     817
     818 -class ServerWebSocketHandler(org.vertx.java.core.Handler):
     819      """ A handler for WebSocket Server Requests"""
     820 -    def __init__(self, handler):
     821          self.handler = handler
     822
     823 -    def handle(self, req):
     824          """ Calls the Handler with the ServerWebSocket when connected """
     825          self.handler(ServerWebSocket(req))
     826
     827 -class WebSocketHandler(org.vertx.java.core.Handler):
     828      """ A handler for WebSocket  Requests"""
     829 -    def __init__(self, handler):
     830          self.handler = handler
     831
     832 -    def handle(self, req):
     833          """ Calls the Handler with the WebSocket when connected """
     834          self.handler(WebSocket(req))
     835
     836 -class RouteMatcher(object):
     837      """This class allows you to do route requests based on the HTTP verb and the request URI, in a manner similar
     838      to <a href="http://www.sinatrarb.com/">Sinatra</a> or <a href="http://expressjs.com/">Express</a>.
     839
     840      RouteMatcher also lets you extract paramaters from the request URI either a simple pattern or using
     841      regular expressions for more complex matches. Any parameters extracted will be added to the requests parameters
     842      which will be available to you in your request handler.
     843
     844      It's particularly useful when writing REST-ful web applications.
     845
     846      To use a simple pattern to extract parameters simply prefix the parameter name in the pattern with a ':' (colon).
     847
     848      Different handlers can be specified for each of the HTTP verbs, GET, POST, PUT, DELETE etc.
     849
     850      For more complex matches regular expressions can be used in the pattern. When regular expressions are used, the extracted
     851      parameters do not have a name, so they are put into the HTTP request with names of param0, param1, param2 etc.
     852
     853      Multiple matches can be specified for each HTTP verb. In the case there are more than one matching patterns for
     854      a particular request, the first matching one will be used.
     855      """
     856 -    def __init__(self):
     857          self.java_obj = org.vertx.java.core.http.RouteMatcher()
     858
     859 -    def __call__(self, data):
     860          self.input(data)
     861
     862 -    def input(self, request):
     863          """This method is called to provide the matcher with data.
     864
     865          Keyword arguments:
     866          @param request: input request to the parser.
     867          """
     868          self.java_obj.handle(request._to_java_request())
     869
     870 -    def get(self, pattern, handler):
     871          """Specify a handler that will be called for a matching HTTP GET
     872
     873          Keyword arguments:
     874          @param pattern: pattern to match
     875          @param handler: handler for match
     876          """
     877          self.java_obj.get(pattern, HttpServerRequestHandler(handler))
     878
     879 -    def put(self, pattern, handler):
     880          """Specify a handler that will be called for a matching HTTP PUT
     881
     882          Keyword arguments:
     883          @param pattern: pattern to match
     884          @param handler: http server request handler
     885          """
     886          self.java_obj.put(pattern, HttpServerRequestHandler(handler))
     887
     888 -    def post(self, pattern, handler):
     889          """Specify a handler that will be called for a matching HTTP POST
     890
     891          Keyword arguments:
     892          @param pattern: pattern to match
     893          @param handler: http server request handler
     894          """
     895          self.java_obj.post(pattern, HttpServerRequestHandler(handler))
     896
     897 -    def delete(self, pattern, handler):
     898          """Specify a handler that will be called for a matching HTTP DELETE
     899
     900          Keyword arguments:
     901          @param pattern: pattern to match
     902          @param handler: http server request handler
     903          """
     904          self.java_obj.delete(pattern, HttpServerRequestHandler(handler))
     905
     906 -    def options(self, pattern, handler):
     907          """Specify a handler that will be called for a matching HTTP OPTIONS
     908
     909          Keyword arguments:
     910          @param pattern: pattern to match
     911          @param handler: http server request handler"""
     912          self.java_obj.options(pattern, HttpServerRequestHandler(handler))
     913
     914 -    def head(self, pattern, handler):
     915          """Specify a handler that will be called for a matching HTTP HEAD
     916
     917          Keyword arguments:
     918          @param pattern: pattern to match
     919          @param handler: http server request handler
     920          """
     921          self.java_obj.head(pattern, HttpServerRequestHandler(handler))
     922
     923 -    def trace(self, pattern, handler):
     924          """Specify a handler that will be called for a matching HTTP TRACE
     925
     926          Keyword arguments:
     927          @param pattern: pattern to match
     928          @param handler: http server request handler
     929          """
     930          self.java_obj.trace(pattern, HttpServerRequestHandler(handler))
     931
     932 -    def patch(self, pattern, handler):
     933          """Specify a handler that will be called for a matching HTTP PATCH
     934
     935          Keyword arguments:
     936          @param pattern: pattern to match
     937          @param handler: http server request handler
     938          """
     939          self.java_obj.patch(pattern, HttpServerRequestHandler(handler))
     940
     941 -    def connect(self, pattern, handler):
     942          """Specify a handler that will be called for a matching HTTP CONNECT
     943
     944          Keyword arguments:
     945          @param pattern: pattern to match
     946          @param handler: http server request handler
     947          """
     948          self.java_obj.connect(pattern, HttpServerRequestHandler(handler))
     949
     950 -    def all(self, pattern, handler):
     951          """Specify a handler that will be called for any matching HTTP request
     952
     953          Keyword arguments:
     954          @param pattern: pattern to match
     955          @param handler: http server request handler"""
     956          self.java_obj.all(pattern, HttpServerRequestHandler(handler))
     957
     958 -    def get_re(self, pattern, handler):
     959          """Specify a handler that will be called for a matching HTTP GET
     960
     961
     962          Keyword arguments:
     963          @param pattern: pattern to match
     964          @param handler: http server request handler
     965          """
     966          self.java_obj.getWithRegEx(pattern, HttpServerRequestHandler(handler))
     967
     968 -    def put_re(self, pattern, handler):
     969          """Specify a handler that will be called for a matching HTTP PUT
     970
     971          Keyword arguments:
     972          @param pattern: pattern to match
     973          @param handler: http server request handler
     974          """
     975          self.java_obj.putWithRegEx(pattern, HttpServerRequestHandler(handler))
     976
     977 -    def post_re(self, pattern, handler):
     978          """Specify a handler that will be called for a matching HTTP POST
     979
     980          Keyword arguments:
     981          @param pattern: pattern to match
     982          @param handler: http server request handler
     983          """
     984          self.java_obj.postWithRegEx(pattern, HttpServerRequestHandler(handler))
     985
     986 -    def delete_re(self, pattern, handler):
     987          """Specify a handler that will be called for a matching HTTP DELETE
     988
     989          Keyword arguments:
     990          @param pattern: pattern to match
     991          @param handler: http server request handler
     992          """
     993          self.java_obj.deleteWithRegEx(pattern, HttpServerRequestHandler(handler))
     994
     995
     996 -    def options_re(self, pattern, handler):
     997          """Specify a handler that will be called for a matching HTTP OPTIONS
     998
     999          Keyword arguments:
    1000          @param pattern: pattern to match
    1001          @param handler: http server request handler
    1002          """
    1003          self.java_obj.optionsWithRegEx(pattern, HttpServerRequestHandler(handler))
    1004
    1005 -    def head_re(self, pattern, handler):
    1006          """Specify a handler that will be called for a matching HTTP HEAD
    1007
    1008          Keyword arguments:
    1009          @param pattern: pattern to match
    1010          @param handler: http server request handler
    1011          """
    1012          self.java_obj.headWithRegEx(pattern, HttpServerRequestHandler(handler))
    1013
    1014 -    def trace_re(self, pattern, handler):
    1015          """Specify a handler that will be called for a matching HTTP TRACE
    1016
    1017          Keyword arguments:
    1018          @param pattern: pattern to match
    1019          @param handler: http server request handler
    1020          """
    1021          self.java_obj.traceWithRegEx(pattern, HttpServerRequestHandler(handler))
    1022
    1023 -    def patch_re(self, pattern, handler):
    1024          """Specify a handler that will be called for a matching HTTP PATCH
    1025
    1026          Keyword arguments:
    1027          @param pattern: pattern to match
    1028          @param handler: http server request handler
    1029          """
    1030          self.java_obj.patchWithRegEx(pattern, HttpServerRequestHandler(handler))
    1031
    1032 -    def connect_re(self, pattern, handler):
    1033          """Specify a handler that will be called for a matching HTTP CONNECT
    1034
    1035          Keyword arguments:
    1036          @param pattern: pattern to match
    1037          @param handler: http server request handler
    1038          """
    1039          self.java_obj.connectWithRegEx(pattern, HttpServerRequestHandler(handler))
    1040
    1041 -    def all_re(self, pattern, handler):
    1042          """Specify a handler that will be called for any matching HTTP request
    1043
    1044          Keyword arguments:
    1045          @param pattern: pattern to match
    1046          @param handler: http server request handler
    1047          """
    1048          self.java_obj.allWithRegEx(pattern, HttpServerRequestHandler(handler))
    1049
    1050 -    def no_match(self, handler):
    1051          """Specify a handler that will be called when nothing matches
    1052          Default behaviour is to return a 404
    1053
    1054          Keyword arguments:
    1055          @param handler: http server request handler"""
    1056          self.java_obj.noMatch(HttpServerRequestHandler(handler))
    1057