Event handler that is called when receiving a http request.
542007
@Override
  public void onHttpRequest(
      final ParsedHttpRequest parsedHttpRequest,
      final HttpServletResponse response) throws IOException, ServletException {

    LOG.log(Level.INFO, "HttpServerReefEventHandler in webserver onHttpRequest is called: {0}",
        parsedHttpRequest.getRequestUri());

    final String version = parsedHttpRequest.getVersion().toLowerCase();
    final String target = parsedHttpRequest.getTargetEntity().toLowerCase();

    switch (target) {
    case "evaluators": {
      final String queryStr = parsedHttpRequest.getQueryString();
      if (queryStr == null || queryStr.isEmpty()) {
        if (version.equals(VER)) {
          writeEvaluatorsJsonOutput(response);
        } else {
          writeEvaluatorsWebOutput(response);
        }
      } else {
        handleQueries(response, parsedHttpRequest.getQueryMap(), version);
      }
      break;
    }
    case "driver":
      if (version.equals(VER)) {
        writeDriverJsonInformation(response);
      } else {
        writeDriverWebInformation(response);
      }
      break;
    case "close":
      for (final EventHandler<Void> e : clientCloseHandlers) {
        e.onNext(null);
      }
      response.getWriter().println("Enforced closing");
      break;
    case "kill":
      reefStateManager.onClientKill();
      response.getWriter().println("Killing");
      break;
    case "duration":
      final ArrayList<String> lines =
          LogParser.getFilteredLinesFromFile(driverStderrFile, LoggingScopeImpl.DURATION, LoggingScopeImpl.TOKEN, null);
      writeLines(response, lines, "Performance...");
      break;
    case "stages":
      final ArrayList<String> starts =
          LogParser.getFilteredLinesFromFile(driverStderrFile, LoggingScopeImpl.START_PREFIX, logLevelPrefix, null);
      final ArrayList<String> exits =
          LogParser.getFilteredLinesFromFile(driverStderrFile, LoggingScopeImpl.EXIT_PREFIX, logLevelPrefix,
              LoggingScopeImpl.DURATION);
      final ArrayList<String> startsStages = LogParser.findStages(starts, LogParser.START_INDICATORS);
      final ArrayList<String> endStages = LogParser.findStages(exits, LogParser.END_INDICATORS);
      final ArrayList<String> result = LogParser.mergeStages(startsStages, endStages);
      writeLines(response, result, "Current Stages...");
      break;
    case "logfile":
      final List<String> names = parsedHttpRequest.getQueryMap().get("filename");
      final PrintWriter writer = response.getWriter();
      if (names == null || names.size() == 0) {
        writer.println("File name is not provided");
      } else {
        final String fileName = names.get(0);
        if (!fileName.equals(driverStdoutFile) && !fileName.equals(driverStderrFile)) {
          writer.println(String.format("Unsupported file names: [%s] ", fileName));
        } else {
          try {
            final byte[] outputBody = readFile(fileName).getBytes(StandardCharsets.UTF_8);
            writer.print(Arrays.toString(outputBody));
          } catch (final IOException e) {
            writer.println(String.format("Cannot find the log file: [%s].", fileName));
          }
        }
      }
      break;
    case "progress":
      response.getWriter().println(progressProvider.get().getProgress());
      break;
    default:
      response.getWriter().println(String.format("Unsupported query for entity: [%s].", target));
    }
  }
431846
private void handleEvent(PrimitiveEvent event) {
    log.trace("Received {}", event);
    Set<Consumer<PrimitiveEvent>> listeners = eventListeners.get(event.type());
    if (listeners != null) {
      listeners.forEach(l -> l.accept(event));
    }
  }
702381
function (event) {
                // Send the HttpResponseHeaders event if it hasn't been sent already.
                if (!sentHeaders) {
                    observer.next(partialFromXhr());
                    sentHeaders = true;
                }
                // Start building the download progress event to deliver on the response
                // event stream.
                var progressEvent = {
                    type: HttpEventType.DownloadProgress,
                    loaded: event.loaded,
                };
                // Set the total number of bytes in the event if it's available.
                if (event.lengthComputable) {
                    progressEvent.total = event.total;
                }
                // If the request was for text content and a partial response is
                // available on XMLHttpRequest, include it in the progress event
                // to allow for streaming reads.
                if (req.responseType === 'text' && !!xhr.responseText) {
                    progressEvent.partialText = xhr.responseText;
                }
                // Finally, fire the event.
                observer.next(progressEvent);
            }
566693
public void processResponseEvent(ResponseEvent event, HttpClientActivity activity) throws ActivityIsEndingException {

        HttpClientActivityHandle ah = new HttpClientActivityHandle(activity.getSessionId());

        if (tracer.isFineEnabled())
            tracer.fine("==== FIRING ResponseEvent EVENT TO LOCAL SLEE, Event: " + event + " ====");

        try {
            resourceAdaptorContext.getSleeEndpoint().fireEvent(ah, fireableEventType, event, null, null, EVENT_FLAGS);
        } catch (Throwable e) {
            throw new ActivityIsEndingException();
        }
    }
934523
async def handler(event):
    """"""
    q1 = event.pattern_match.group(1)
    q2 = urllib.parse.quote(q1)
    await asyncio.wait([
        event.delete(),
        event.respond(DOCS.format(q1, q2), reply_to=event.reply_to_msg_id)
    ])
766115
def exec_event_handler(self, event, transactional=False):
        """"""
        # QUESTION: Should we raise an exception if `event` is not in some
        # known event-type list?

        callbacks = self._options.get('callbacks', {})

        handler = callbacks.get(event)

        if not handler:
            raise Exception('Handler not defined!!!')

        handler.start(transactional=transactional)
1152439
def on_event(event_handler = nil, &block)
      event_handler ||= block
      raise ArgumentError, "no event_handler provided" if event_handler.nil?
      @event_handler = event_handler
    end
1209497
function () {
        this.addResult = function (event) {
            var fullUrl = event.homeURL + url;
            http.get(fullUrl, function (response) {
                var content = "";
                response.on("data", function (chunk) {
                    content += chunk;
                });
                response.on("end", function () {
                    callback(content);
                });
            });
        };
        this.checkFinished = function () {
            return false;
        };
        events.EventEmitter.call(this);
    }
347826
function HttpHeaderResponse(init) {
        if (init === void 0) { init = {}; }
        var _this = _super.call(this, init) || this;
        _this.type = HttpEventType.ResponseHeader;
        return _this;
    }
462187
def _handle_request(self, msg_id, method, params):
        """"""
        try:
            handler = self._dispatcher[method]
        except KeyError:
            raise JsonRpcMethodNotFound.of(method)

        handler_result = handler(params)

        if callable(handler_result):
            log.debug("Executing async request handler %s", handler_result)
            request_future = self._executor_service.submit(handler_result)
            self._client_request_futures[msg_id] = request_future
            request_future.add_done_callback(self._request_callback(msg_id))
        else:
            log.debug("Got result from synchronous request handler: %s", handler_result)
            self._consumer({
                'jsonrpc': JSONRPC_VERSION,
                'id': msg_id,
                'result': handler_result
            })
828264
function onHeaders(ev, status, newUrl, oldUrl, statusCode, method, referrer, headers, resourceType) {
    if (resourceType !== 'mainFrame') return;

    let headerArray = [];

    Object.keys(headers).forEach(name => {
      headers[name].forEach(value => {
        headerArray.push({ name, value });
      });
    });

    response = {
      url: newUrl,
      method,
      status: statusCode,
      contentType: headers['content-type'][0],
      headers: headerArray
    };

    notify([ 'header event', status, newUrl, oldUrl, statusCode, method, referrer, headers, resourceType ]);
  }
7603
def on_headers(self, response, exc=None):
        ''''''

        if response.status_code == 101:
            connection = response.connection
            request = response.request
            handler = request.websocket_handler
            if not handler:
                handler = WS()
            parser = request.client.frame_parser(kind=1)
            consumer = partial(WebSocketClient.create,
                               response, handler, parser)
            connection.upgrade(consumer)
            response.event('post_request').fire()
            websocket = connection.current_consumer()
            response.request_again = lambda r: websocket
1310960
function onReadystatechange(e) {

	if (!(e instanceof Event)) {
		throw new TypeError('Invalid event was given');
	}

	if (document.readyState == 'interactive') {
		makeReady.call(this);
	}

	if (document.readyState == 'complete') {
		makeLoaded.call(this);
	}
}
863864
function (event) {
                // Do nothing if the request has been cancelled.
                if (cancelled) {
                    return;
                }
                // Cleanup the page.
                cleanup();
                // Check whether the response callback has run.
                if (!finished) {
                    // It hasn't, something went wrong with the request. Return an error via
                    // the Observable error path. All JSONP errors have status 0.
                    observer.error(new HttpErrorResponse({
                        url: url,
                        status: 0,
                        statusText: 'JSONP Error',
                        error: new Error(JSONP_ERR_NO_CALLBACK),
                    }));
                    return;
                }
                // Success. body either contains the response body or null if none was
                // returned.
                observer.next(new HttpResponse({
                    body: body,
                    status: 200,
                    statusText: 'OK', url: url,
                }));
                // Complete the stream, the response is over.
                observer.complete();
            }
422188
function handleRequestBody(request) {
        var body = "";
        request.on('data', function(chunk) {
            body += chunk.toString();
        });
        return new Promise(function (fulfill, reject) {
            request.on('end', function () {
                fulfill(body);
            });
        });
    }
1307226
function handler(req, res) {

        var path = cog.getConfig('options.api_data');
        var urlRegex = cog.getConfig('options.api_url_regex');
        var url = req.url.replace(/^\//, '').replace(/\/$/, '');

        console.log(req.method + ' ' + req.url);

        // Find the JSON-data file and serve it, if URL points to the API.
        if (path && urlRegex && urlRegex.test(url)) {
            var file = path + '/' + url + '.json';
            if (grunt.file.exists(file)) {
                res.end(grunt.file.read(file));
                return;
            }
        }

        if (req.method == 'POST') {
            // TODO: This needs fixing, since it throws an error.
            res.end('{"message": "OK"}');
        }

    }
1303500
function handler(req, res, next) {
    next = next || send

    if (pending) return pending.once('ready', function(err) {
      if (err) return next(err)
      return handler(req, res, next)
    })

    if (prevError) return next(prevError)

    res.setHeader('content-type', 'text/css')
    return next(null, buffer)

    function send(err, body) {
      if (err) return res.emit(err)
      res.end(body)
    }
  }