/*
@see org.browsermob.proxy.jetty.http.HttpHandler#handle(java.lang.String, java.lang.String, org.browsermob.proxy.jetty.http.HttpRequest, org.browsermob.proxy.jetty.http.HttpResponse)
501154
public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException
    {
    }
302980
protected void handleResponse(HttpRequest<?> request, MutableHttpResponse<?> response) {
        HttpHeaders headers = request.getHeaders();
        Optional<String> originHeader = headers.getOrigin();
        originHeader.ifPresent(requestOrigin -> {

            Optional<CorsOriginConfiguration> optionalConfig = getConfiguration(requestOrigin);

            if (optionalConfig.isPresent()) {
                CorsOriginConfiguration config = optionalConfig.get();

                if (CorsUtil.isPreflightRequest(request)) {
                    Optional<HttpMethod> result = headers.getFirst(ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.class);
                    setAllowMethods(result.get(), response);
                    Argument<List> type = Argument.of(List.class, String.class);
                    Optional<List> allowedHeaders = headers.get(ACCESS_CONTROL_REQUEST_HEADERS, type);
                    allowedHeaders.ifPresent(val ->
                        setAllowHeaders(val, response)
                    );

                    setMaxAge(config.getMaxAge(), response);
                }

                setOrigin(requestOrigin, response);
                setVary(response);
                setExposeHeaders(config.getExposedHeaders(), response);
                setAllowCredentials(config, response);
            }
        });
    }
1202438
@SuppressWarnings("unchecked")
  protected <T extends RaftRequest> void handleResponse(T request, BiFunction sender, int count, int selectionId, MemberId node, RaftResponse response, Throwable error, CompletableFuture future) {
    if (error == null) {
      log.trace("Received {} from {}", response, node);
      if (COMPLETE_PREDICATE.test(response)) {
        future.complete(response);
        selector.reset();
      } else {
        retryRequest(response.error().createException(), request, sender, count + 1, selectionId, future);
      }
    } else {
      if (error instanceof CompletionException) {
        error = error.getCause();
      }
      log.debug("{} failed! Reason: {}", request, error);
      if (error instanceof SocketException || error instanceof TimeoutException || error instanceof ClosedChannelException) {
        if (count < selector.members().size() + 1) {
          retryRequest(error, request, sender, count + 1, selectionId, future);
        } else {
          future.completeExceptionally(error);
        }
      } else {
        future.completeExceptionally(error);
      }
    }
  }
844909
public boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception {
        logResponse("Sending SOAP response", messageContext, false);
        
        return true;
    }
426959
protected void handleResponse(Object control) {
		byte[] result = (byte[]) invokeMethod("getCookie", responseControlClass, control);
        if(result == null) {
            more = false;
        }
		this.cookie = new PagedResultsCookie(result);
        this.resultSize = (Integer) invokeMethod("getResultSize", responseControlClass, control);
	}
1196864
def handle(self, url, method):
        
        if not self.serve:
            return HTTPError(503, "Server stopped")

        handler, args = self.match_url(url, method)
        if not handler:
            return HTTPError(404, "Not found:" + url)

        try:
            return handler(**args)
        except HTTPResponse, e:
            return e
        except Exception, e:
            if isinstance(e, (KeyboardInterrupt, SystemExit, MemoryError))\
            or not self.catchall:
                raise
            return HTTPError(500, 'Unhandled exception', e, format_exc(10))
781741
@Override
  public void addHttpHandler(final HttpHandler httpHandler) {
    LOG.log(Level.INFO, "addHttpHandler: {0}", httpHandler.getUriSpecification());
    jettyHandler.addHandler(httpHandler);
  }
494261
@Override
  public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry)
      throws IOException {
    if (!supportsRetry) {
      return false;
    }
    // check if back-off is required for this response
    if (backOffRequired.isRequired(response)) {
      try {
        return BackOffUtils.next(sleeper, backOff);
      } catch (InterruptedException exception) {
        // ignore
      }
    }
    return false;
  }
432962
public void handle(
        String pathInContext,
        String pathParams,
        HttpRequest request,
        HttpResponse response)
        throws HttpException, IOException
    {
        String userAgent = request.getField(HttpFields.__UserAgent);
        
        if(userAgent != null &&  
           userAgent.indexOf( userAgentSubString)>=0 &&
           HttpRequest.__SSL_SCHEME.equalsIgnoreCase(request.getScheme()))
        {
            if (log.isDebugEnabled())
                log.debug("Force close");
            response.setField(HttpFields.__Connection, HttpFields.__Close);
            request.getHttpConnection().forceClose();
        }
    }
738254
protected void handle(HttpConnection httpConnection) throws IOException {
		try {
			getServerThread().handleIncomingHttp(httpConnection);
			httpConnection.waitForResponse();
		}
		catch (ConnectException ex) {
			httpConnection.respond(HttpStatus.GONE);
		}
	}
188882
public void handle(String pathInContext, String pathParams, HttpRequest request,
            HttpResponse response) throws HttpException, IOException
    {

        // exempt error pages
        // TODO This probably should be more general?
        if (request.getAttribute("javax.servlet.error.status_code") != null) return;

        try
        {

            String ip = request.getRemoteAddr();
            boolean authorized = checkIP(ip);

            if (!authorized)
            {
                // The IP is NOT allowed
                response.sendError(HttpResponse.__403_Forbidden);
                request.setHandled(true);
                return;
            }
            else
            {
                // The IP is allowed
                return;
            }
        }
        catch (Exception ex)
        {
            System.out.println(ex);
            response.sendError(HttpResponse.__500_Internal_Server_Error);
            request.setHandled(true);
        }
    }
277287
@Override
    public void handle() throws HandlerException {
        String repository = getAuditEvent().getRepository();
        boolean writeInDefaultTable = !separate || repository == null;
        String tableName = writeInDefaultTable ? default_table_name : generateTableName(repository);

        getDaoForTable(tableName).writeEvent(getAuditEvent());
    }
1202497
public static void handle(String s, AnnotationHandler ah) {
        Map<String, Map<String, String>> l = new LinkedHashMap<String, Map<String, String>>();
        Matcher m = annPattern.matcher(s);
        while (m.find()) {
//            for (int i = 1; i <= m.groupCount(); i++) {
//                System.out.println("Group " + i + " '" + m.group(i) + "'");
//            }

            String rest = s.substring(m.end(0)).trim();
            String srcLine = null;
            if (rest.indexOf('\n') > -1) {
                srcLine = rest.substring(0, rest.indexOf('\n'));
            } else {
                srcLine = rest;
            }

            Map<String, String> val = new LinkedHashMap<String, String>();
            String annArgs = m.group(3);
            if (annArgs == null) {
                // no annotations arguments
                // e.g   '@Function'
            } else if (annArgs.indexOf('=') > -1) {
                // KVP annotation
                // e.g.  '@Function(name="test", scope="global")'
                StringTokenizer t = new StringTokenizer(annArgs, ",");
                while (t.hasMoreTokens()) {
                    String arg = t.nextToken();
                    String key = arg.substring(0, arg.indexOf('='));
                    String value = arg.substring(arg.indexOf('=') + 1);
                    val.put(key.trim(), value.trim());
                }
            } else {
                // single value annotation
                // e.g.  '@Function("test");
                val.put(AnnotationHandler.VALUE, annArgs);
            }

            l.put(m.group(1), val);

            // If the next line also has an annotation
            // no source line will be passed into the handler
            if (!annTestPattern.matcher(srcLine).find()) {
                ah.handle(l, srcLine);
                ah.log(" Ann -> " + l);
                ah.log(" Src -> " + srcLine);
                l = new LinkedHashMap<String, Map<String, String>>();
            }
        }
    }
430633
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
        // Don't pollute the logging with the favicon.ico requests that browsers issue.
        if (target.equals("/favicon.ico")) {
            response.sendError(404);
            return;
        }

        // Log the request path.
        String requestPath = target;
        if (request.getQueryString() != null) {
            requestPath += "?" + request.getQueryString();
        }
        common.log.println("-- Request: " + request.getMethod() + " " + requestPath);

        if (target.equals("/")) {
            doIndex(request, response);
        } else if (target.equals("/login")) {
            doLogin(request, response);
        } else if (target.equals("/home")) {
            doHome(request, response);
        } else if (target.equals("/logout")) {
            doLogout(request, response);
        // Dropbox authorize routes
        } else if (target.equals("/dropbox-auth-start")) {
            dropboxAuth.doStart(request, response);
        } else if (target.equals("/dropbox-auth-finish")) {
            dropboxAuth.doFinish(request, response);
        } else if (target.equals("/dropbox-unlink")) {
            dropboxAuth.doUnlink(request, response);
        // Dropbox file browsing routes.
        } else if (target.equals("/browse")) {
            dropboxBrowse.doBrowse(request, response);
        } else if (target.equals("/upload")) {
            dropboxBrowse.doUpload(request, response);
        } else {
            response.sendError(404);
        }
    }
1074865
@Override
    public void handle(WebContext webContext) throws Exception {
        Request request = webContext.getRequest();

        ChannelHandlerContext ctx = webContext.getChannelHandlerContext();

        if (!HttpConst.METHOD_GET.equals(request.method())) {
            sendError(ctx, METHOD_NOT_ALLOWED);
            return;
        }

        Instant start = Instant.now();

        String uri      = URLDecoder.decode(request.uri(), "UTF-8");
        String method   = StringKit.padRight(request.method(), 6);
        String cleanURL = getCleanURL(request, uri);

        // webjars
        if (cleanURL.startsWith(Const.WEB_JARS)) {
            InputStream input = getResourceStreamFromJar(uri);
            writeWithJarFile(request, ctx, uri, start, cleanURL, method, input);
            return;
        }

        // jar file
        if (BladeKit.runtimeIsJAR()) {
            InputStream input = StaticFileHandler.class.getResourceAsStream(cleanURL);
            writeWithJarFile(request, ctx, uri, start, cleanURL, method, input);
            return;
        }

        // disk file
        final String path = sanitizeUri(cleanURL);
        if (path == null) {
            log403(log, method, uri);
            throw new ForbiddenException();
        }

        File file = new File(path);
        if (file.isHidden() || !file.exists()) {
            // gradle resources path
            File resourcesDirectory = getGradleResourcesDirectory();
            if (resourcesDirectory.isDirectory()) {
                file = new File(resourcesDirectory.getPath() + "/" + cleanURL.substring(1));
                if (file.isHidden() || !file.exists()) {
                    throw new NotFoundException(uri);
                }
            } else {
                throw new NotFoundException(uri);
            }
        }

        if (file.isDirectory() && showFileList) {
            sendListing(ctx, uri, getFileMetas(file), cleanURL);
            return;
        }

        if (!file.isFile()) {
            sendError(ctx, FORBIDDEN);
            return;
        }

        // Cache Validation
        if (isHttp304(ctx, request, file.length(), file.lastModified())) {
            log304(log, method, uri);
            return;
        }

        HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        setContentTypeHeader(httpResponse, file);
        setDateAndCacheHeaders(httpResponse, file);

        if (request.useGZIP()) {
            File output = new File(file.getPath() + ".gz");
            IOKit.compressGZIP(file, output);
            file = output;
            setGzip(httpResponse);
        }

        RandomAccessFile raf;
        try {
            raf = new RandomAccessFile(file, "r");
        } catch (FileNotFoundException ignore) {
            sendError(ctx, NOT_FOUND);
            return;
        }

        long fileLength = raf.length();

        httpResponse.headers().set(HttpConst.CONTENT_LENGTH, fileLength);
        if (request.keepAlive()) {
            httpResponse.headers().set(HttpConst.CONNECTION, HttpConst.KEEP_ALIVE);
        }

        // Write the initial line and the header.
        ctx.write(httpResponse);

        // Write the content.
        ChannelFuture sendFileFuture;
        ChannelFuture lastContentFuture;
        if (ctx.pipeline().get(SslHandler.class) == null) {
            sendFileFuture = ctx.write(
                    new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                    ctx.newProgressivePromise()
            );

            // Write the end marker.
            lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

        } else {
            sendFileFuture = ctx.writeAndFlush(
                    new HttpChunkedInput(
                            new ChunkedFile(raf, 0, fileLength, 8192)
                    ),
                    ctx.newProgressivePromise());
            // HttpChunkedInput will write the end marker (LastHttpContent) for us.
            lastContentFuture = sendFileFuture;
        }

        sendFileFuture.addListener(ProgressiveFutureListener.build(raf));

        // Decide whether to close the connection or not.
        if (!request.keepAlive()) {
            lastContentFuture.addListener(ChannelFutureListener.CLOSE);
        }
        log200AndCost(log, start, method, uri);
    }
780690
public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.debug("Handling HttpServletRequest {}", request);
		response.setContentType(contentType);
		OutputStream output = response.getOutputStream();
		InputStream input = getRequestStream(request);
		int result = ErrorResolver.JsonError.PARSE_ERROR.code;
		int contentLength = 0;
		ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
		try {
			String acceptEncoding = request.getHeader(ACCEPT_ENCODING);
			result = handleRequest0(input, output, acceptEncoding, response, byteOutput);

			contentLength = byteOutput.size();
		} catch (Throwable t) {
			if (StreamEndedException.class.isInstance(t)) {
				logger.debug("Bad request: empty contents!");
			} else {
				logger.error(t.getMessage(), t);
			}
		}
		int httpStatusCode = httpStatusCodeProvider == null ? DefaultHttpStatusCodeProvider.INSTANCE.getHttpStatusCode(result)
				: httpStatusCodeProvider.getHttpStatusCode(result);
		response.setStatus(httpStatusCode);
		response.setContentLength(contentLength);
		byteOutput.writeTo(output);
		output.flush();
	}
418593
public void handle(String pathInContext,
                       String pathParams,
                       HttpRequest request,
                       HttpResponse response)
        throws HttpException, IOException
    {
        log.debug("Not Found");
        String method=request.getMethod();
        
        // Not found  requests.
        if (method.equals(HttpRequest.__GET)    ||
            method.equals(HttpRequest.__HEAD)   ||
            method.equals(HttpRequest.__POST)   ||
            method.equals(HttpRequest.__PUT)    ||
            method.equals(HttpRequest.__DELETE) ||
            method.equals(HttpRequest.__MOVE)   )
        {
            response.sendError(HttpResponse.__404_Not_Found,
                               request.getPath()+" Not Found");
        }
        
        else if (method.equals(HttpRequest.__OPTIONS))
        {
            // Handle OPTIONS request for entire server
            if ("*".equals(request.getPath()))
            {
                // 9.2
                response.setIntField(HttpFields.__ContentLength,0);
                response.setField(HttpFields.__Allow,
                                  "GET, HEAD, POST, PUT, DELETE, MOVE, OPTIONS, TRACE");
                response.commit();
            }
            else
                response.sendError(HttpResponse.__404_Not_Found);
        }
        else if (method.equals(HttpRequest.__TRACE))
        {
            handleTrace(request,response);
        }
        else
        {
            // Unknown METHOD
            response.setField(HttpFields.__Allow,
                              "GET, HEAD, POST, PUT, DELETE, MOVE, OPTIONS, TRACE");
            response.sendError(HttpResponse.__405_Method_Not_Allowed);
        }
    }