Handle a long-polling GET request from the client.
549574
def handle_get_request(self, environ, start_response):
        """"""
        connections = [
            s.strip()
            for s in environ.get('HTTP_CONNECTION', '').lower().split(',')]
        transport = environ.get('HTTP_UPGRADE', '').lower()
        if 'upgrade' in connections and transport in self.upgrade_protocols:
            self.server.logger.info('%s: Received request to upgrade to %s',
                                    self.sid, transport)
            return getattr(self, '_upgrade_' + transport)(environ,
                                                          start_response)
        try:
            packets = self.poll()
        except exceptions.QueueEmpty:
            exc = sys.exc_info()
            self.close(wait=False)
            six.reraise(*exc)
        return packets
11481
def handle(self):
        """"""
        self.close_connection = 1

        self.handle_one_request()
        while not self.close_connection:
            self.handle_one_request()
25771
def _handle_request(self, request):
        """"""

        # Check if this is a persistent connection.
        if request['version'] == 'HTTP/1.1':
            self.keepalive = not request.get('Connection') == 'close'
        elif request['version'] == 'HTTP/1.0':
            self.keepalive = request.get('Connection') == 'Keep-Alive'

        # Check if we're getting a sane request
        if request['method'] not in ('GET'):
            raise InvalidRequestError(501, 'Method not implemented')
        if request['version'] not in ('HTTP/1.0', 'HTTP/1.1'):
            raise InvalidRequestError(
                505, 'Version not supported. Supported versions are: {}, {}'
                .format('HTTP/1.0', 'HTTP/1.1'))

        host, location = self._get_request_uri(request)

        # We must ignore the Host header if a host is specified in GET
        if host is None:
            host = request.get('Host')

        # Check if this request is intended for this webserver
        if host is not None and not host == self.host:
            self.logger.info('Got a request for unknown host %s', host)
            raise InvalidRequestError(404, "We don't serve this host")

        filename = os.path.join(self.folder, unquote(location))
        self.logger.debug('trying to serve %s', filename)

        if os.path.isdir(filename):
            filename = os.path.join(filename, 'index.html')

        if not os.path.isfile(filename):
            raise InvalidRequestError(404, 'Not Found')

        # Start response with version
        response = _get_response(version=request['version'])

        # timeout negotiation
        match = re.match(r'timeout=(\d+)', request.get('Keep-Alive', ''))
        if match is not None:
            requested_timeout = int(match.group(1))
            if requested_timeout < self._timeout:
                self._timeout = requested_timeout

        # tell the client our timeout
        if self.keepalive:
            response['headers'][
                'Keep-Alive'] = 'timeout={}'.format(self._timeout)

        # Set Content-Type
        response['headers']['Content-Type'] = mimetypes.guess_type(
            filename)[0] or 'text/plain'

        # Generate E-tag
        sha1 = hashlib.sha1()
        with open(filename, 'rb') as fp:
            response['body'] = fp.read()
            sha1.update(response['body'])
        etag = sha1.hexdigest()

        # Create 304 response if if-none-match matches etag
        if request.get('If-None-Match') == '"{}"'.format(etag):
            # 304 responses shouldn't contain many headers we might already
            # have added.
            response = _get_response(code=304)

        response['headers']['Etag'] = '"{}"'.format(etag)

        self._write_response(response)
24288
def _handle_get(self, request):
        # type: (Get) -> CallbackResponses
        """"""
        data = self._block

        for i, endpoint in enumerate(request.path[1:]):
            try:
                data = data[endpoint]
            except KeyError:
                if hasattr(data, "typeid"):
                    typ = data.typeid
                else:
                    typ = type(data)
                raise UnexpectedError(
                    "Object %s of type %r has no attribute %r" % (
                        request.path[:i+1], typ, endpoint))
        # Important to serialize now with the lock so we get a consistent set
        serialized = serialize_object(data)
        ret = [request.return_response(serialized)]
        return ret
159456
def poll(self, offset=None, poll_timeout=600, cooldown=60, debug=False):
        '''

        '''
        if self.config['api_key'] is None:
            raise ValueError('config api_key is undefined')

        if offset or self.config.get('offset', None):
            self.offset = offset or self.config.get('offset', None)

        self._start()

        while True:
            try:
                response = self.get_updates(poll_timeout, self.offset)
                if response.get('ok', False) is False:
                    raise ValueError(response['error'])
                else:
                    self.process_updates(response)
            except Exception as e:
                print('Error: Unknown Exception')
                print(e)
                if debug:
                    raise e
                else:
                    time.sleep(cooldown)
490196
def poll(self, timeout):
        
        now = time.time()
        end_time = now + float(timeout)
        prev_timeout = self.stream.gettimeout()
        self.stream.settimeout(self._poll_period)
        incoming = None
        try:
            while (end_time - now) >= 0:
                try:
                    incoming = self.stream.recv(self._max_read)
                except socket.timeout:
                    pass
                if incoming:
                    return incoming
                now = time.time()
            raise ExpectTimeout()
        finally:
            self.stream.settimeout(prev_timeout)
74005
def handle_get_request(self):
        
        self.objects = self.get_objects()
        self.response = self.get_response_handler()

        self.response.process(self.objects)

        return self.list_response()
1283950
@Override
  public void requestPollRead()
  {
    /*
    if (log.isLoggable(Level.FINEST)) {
      log.finest("request-wake " + getName()
                 + " (count=" + _port.getThreadCount()
                 + ", idle=" + _port.getIdleThreadCount() + ")");
    }
    */

    try {
      requestLoop();
    } catch (Exception e) {
      log.log(Level.WARNING, e.toString(), e);
    }

    /*
    if (_stateRef.get().toWake(_stateRef)) {
      offer(getConnectionTask());
    }
    */
  }
1258715
def handle(self):
        """"""
        rv = None
        try:
            rv = BaseHTTPRequestHandler.handle(self)
        except (_ConnectionError, socket.timeout) as e:
            self.connection_dropped(e)
        except Exception as e:
            if self.server.ssl_context is None or not is_ssl_error(e):
                raise
        if self.server.shutdown_signal:
            self.initiate_shutdown()
        return rv
161911
def serve_forever(self, poll_interval=0.5):
        
        self._serving_event.set()
        self._shutdown_request_event.clear()
        TCPServer.serve_forever(self, poll_interval=poll_interval)
1298179
def _handle_get(self, request_data):
        
        der = base64.b64decode(request_data)
        ocsp_request = self._parse_ocsp_request(der)
        return self._build_http_response(ocsp_request)
1294770
def handle_request(self, msgtype, msgid, method, args, kwargs):
        """"""
        response = None
        error = None
        exception = None

        try:
            response = self.dispatch.call(method, args, kwargs)
        except Exception as e:
            error = (e.__class__.__name__, str(e))
            exception = e

        if isinstance(response, Deferred):
            response.add_callback(self.send_response, msgid)
            response.add_errback(self.send_error, msgid)
        else:
            if exception is None:
                self.send_response(msgid, response)
            else:
                self.send_error(msgid, exception)
144565
def do_GET(self):
        """"""
        thread_local.clock_start = get_time()
        thread_local.status_code = 200
        thread_local.message = None
        thread_local.headers = []
        thread_local.end_headers = []
        thread_local.size = -1
        thread_local.method = 'GET'
        try:
            self.cross_origin_headers()
            if self.handle_special(True, 'GET'):
                return
            SimpleHTTPRequestHandler.do_GET(self)
        except PreventDefaultResponse as pdr:
            if pdr.code:
                self.send_error(pdr.code, pdr.msg)
        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception:
            self.handle_error()
580718
def polling_loop(timeout, interval=1):
    """"""
    start_time = time.time()
    iteration = 0
    end_time = start_time + timeout
    while time.time() < end_time:
        yield iteration
        iteration += 1
        time.sleep(interval)
962658
def make_request(self, handle, value, timeout=DEFAULT_TIMEOUT, with_response=True):
        """"""
        try:
            with self:
                _LOGGER.debug("Writing %s to %s with with_response=%s", codecs.encode(value, 'hex'), handle, with_response)
                self._conn.writeCharacteristic(handle, value, withResponse=with_response)
                if timeout:
                    _LOGGER.debug("Waiting for notifications for %s", timeout)
                    self._conn.waitForNotifications(timeout)
        except btle.BTLEException as ex:
            _LOGGER.debug("Got exception from bluepy while making a request: %s", ex)
            raise
747233
def handle_response(self, msgtype, msgid, response):
        """"""
        self._proxy.response(msgid, response)
625240
def _perform_call(self, query_url, default_response=None, timeout=10):
        """"""
        try:
            response = requests.get(query_url, timeout=timeout)
        except socket.timeout:
            current_plugin.logger.warning("Timeout contacting Piwik server")
            return default_response
        except Exception:
            current_plugin.logger.exception("Unable to connect")
            return default_response
        return response.content