/*
@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)
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();
        }
    }
487540
public final boolean handle(HttpServletRequest req, HttpServletResponse res) {
		return handle(req, res, Request.getPath(req));
	}
1354362
private void handleResponse(PowerShellResponseHandler response, PowerShellResponse powerShellResponse) {
        try {
            response.handle(powerShellResponse);
        } catch (Exception ex) {
            logger.log(Level.SEVERE, "PowerShell not available", ex);
        }
    }
1167733
public void handle(Request request, Response response) throws Exception {
		if (Environment.isDevelopment()) {
			this.middlewares = this.middlewareFactory.create();
		}
		
		try {
			handle(request, response, new ArrayList<Middleware>(Arrays.asList(middlewares)));
		} catch (Exception e) {
			if (exceptionHandler != null) {
				exceptionHandler.handle(e, request, response);
			} else {
				throw e;
			}
		}
	}
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>>();
            }
        }
    }
461492
public XcapResponseImpl handleResponse(HttpResponse httpResponse)
			throws ClientProtocolException, IOException {

		int statusCode = httpResponse.getStatusLine().getStatusCode();

		String eTag = null;
		String mimetype = null;
		if (statusCode == 200 || statusCode == 201) {
			// sucessful response
			org.apache.http.Header eTagHeader = httpResponse
					.getFirstHeader(XcapConstant.HEADER_ETAG);
			if (eTagHeader != null) {
				eTag = eTagHeader.getValue();
			}
			org.apache.http.Header mimetypeHeader = httpResponse
			.getFirstHeader(XcapConstant.HEADER_CONTENT_TYPE);
			if (mimetypeHeader != null) {
				mimetype = mimetypeHeader.getValue();
			}
		}

		final org.apache.http.Header[] apacheHeaders = httpResponse
				.getAllHeaders();
		final Header[] headers = new Header[apacheHeaders.length];
		for (int i = 0; i < headers.length; i++) {
			headers[i] = new HeaderImpl(apacheHeaders[i]);
		}

		final HttpEntity httpEntity = httpResponse.getEntity();

		final XcapEntityImpl xcapEntity = httpEntity != null ? new XcapEntityImpl(
				httpEntity)
				: null;

		return new XcapResponseImpl(statusCode, eTag, mimetype, headers, xcapEntity);
	}
1327590
@Override
    public void handle(T result, HttpResponse response) {
        String transitionHeader = response.getHeaders().get(Headers.IBM_TRANSITION);
        if (transitionHeader != null) {
            result.setTransitionDate(parseDate(transitionHeader));
            String transition = parseTransition(transitionHeader);
            if (transition != null) {
                result.setTransition(transition);
            }
        }
    }
1259529
@Override
    public void handleRequest(HttpServletRequest request, HttpServletResponse response) {
        handleRequest(request, response, null, null, false);
    }
1243046
private void handleResponse(ByteBuf response, ChannelHandlerContext context) {
    NettyConnection connection = getConnection(context.channel());
    if (connection != null) {
      connection.handleResponse(response);
    }
  }
1167754
@Override
    public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
        if (serverCallbackHandler.getValue() != null) {
            serverCallbackHandler.getValue().handle((callbacks));
        }
    }
683142
@RequestMapping(method = POST)
    public void handle(@Valid @RequestBody P payload) {
        logger.debug("{} handlers", handlers.size());
        for (H handler : handlers) {
            executor.execute(runnableHandler(handler, payload));
        }
    }
1263184
public void handle(String pathInContext,
                       String pathParams,
                       HttpRequest request,
                       HttpResponse response)
            throws HttpException,IOException
    {
        String user=null;
        String password=null;
        boolean IPValid=true;

        if(log.isDebugEnabled())log.debug("HTAccessHandler pathInContext="+pathInContext);

        String credentials=request.getField(HttpFields.__Authorization);

        if (credentials!=null)
        {
            credentials=credentials.substring(credentials.indexOf(' ')+1);
            credentials=B64Code.decode(credentials,StringUtil.__ISO_8859_1);
            int i=credentials.indexOf(':');
            user=credentials.substring(0,i);
            password=credentials.substring(i+1);

            if(log.isDebugEnabled())log.debug("User="+user+", password="+
                    "******************************".substring(0,password.length()));
        }

        HTAccess ht=null;

        try
        {
            Resource resource=null;
            String directory=pathInContext.endsWith("/")
                    ?pathInContext:
                    URI.parentPath(pathInContext);

            // Look for htAccess resource
            while (directory!=null)
            {
                String htPath=directory+_accessFile;
                resource=getHttpContext().getResource(htPath);
                if(log.isDebugEnabled())log.debug("directory="+directory+" resource="+resource);

                if (resource!=null && resource.exists() && !resource.isDirectory())
                    break;
                resource=null;
                directory=URI.parentPath(directory);
            }

            // Try default directory
            if (resource==null && _default!=null)
            {
                resource=Resource.newResource(_default);
                if (!resource.exists() || resource.isDirectory())
                    return;
            }
            if (resource==null)
                return;

            if(log.isDebugEnabled())log.debug("HTACCESS="+resource);

            ht=(HTAccess)_htCache.get(resource);
            if (ht==null || ht.getLastModified()!=resource.lastModified())
            {
                ht=new HTAccess(resource);
                _htCache.put(resource,ht);
                if(log.isDebugEnabled())log.debug("HTCache loaded "+ht);
            }

            // prevent access to htaccess files
            if (pathInContext.endsWith(_accessFile))
            {
                response.sendError(HttpResponse.__403_Forbidden);
                request.setHandled(true);
                return;
            }

            // See if there is a config problem
            if (ht.isForbidden())
            {
                log.warn("Mis-configured htaccess: "+ht);
                response.sendError(HttpResponse.__403_Forbidden);
                request.setHandled(true);
                return;
            }

            //first see if we need to handle based on method type
            Map methods=ht.getMethods();
            if (methods.size()>0 && !methods.containsKey(request.getMethod()))
                return; //Nothing to check

            // Check the accesss
            int satisfy=ht.getSatisfy();

            // second check IP address
            IPValid=ht.checkAccess("",request.getRemoteAddr());
            if(log.isDebugEnabled())log.debug("IPValid = "+IPValid);

            // If IP is correct and satify is ANY then access is allowed
            if (IPValid==true && satisfy==HTAccess.ANY)
                return;

            // If IP is NOT correct and satify is ALL then access is forbidden
            if (IPValid==false && satisfy==HTAccess.ALL)
            {
                response.sendError(HttpResponse.__403_Forbidden);
                request.setHandled(true);
                return;
            }

            // set required page
            if (!ht.checkAuth(user,password,getHttpContext(),request))
            {
                log.debug("Auth Failed");
                response.setField(HttpFields.__WwwAuthenticate,"basic realm="+ht.getName());
                response.sendError(HttpResponse.__401_Unauthorized);
                response.commit();
                request.setHandled(true);
                return;
            }

            // set user
            if (user!=null)
            {
                request.setAuthType(SecurityConstraint.__BASIC_AUTH);
                request.setAuthUser(user);
            }

        }
        catch (Exception ex)
        {
            log.warn(LogSupport.EXCEPTION,ex);
            if (ht!=null)
            {
                response.sendError(HttpResponse.__500_Internal_Server_Error);
                request.setHandled(true);
            }
        }
    }
245757
void handle(OngoingRequest ongoingRequest, RequestContext requestContext, Endpoint endpoint) {
    try {
      endpoint.invoke(requestContext)
          .whenComplete((message, throwable) -> {
            try {
              if (message != null) {
                ongoingRequest.reply(message);
              } else if (throwable != null) {
                // unwrap CompletionException
                if (throwable instanceof CompletionException) {
                  throwable = throwable.getCause();
                }
                handleException(throwable, ongoingRequest);
              } else {
                LOG.error(
                    "Both message and throwable null in EndpointInvocationHandler for request "
                    + ongoingRequest
                    + " - this shouldn't happen!");
                handleException(new IllegalStateException("Both message and throwable null"),
                                ongoingRequest);
              }
            } catch (Throwable t) {
              // don't try to respond here; just log the fact that responding failed.
              LOG.error("Exception caught when replying", t);
            }
          });
    } catch (Exception e) {
      handleException(e, ongoingRequest);
    }
  }
1176148
public void handleResponse(String response) {
        if (messageListener != null) {
            log.debug("Sending Http response");
            messageListener.onOutboundMessage(new RawMessage(response), null);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Sending Http response:" + NEWLINE + response);
            }
        }
    }
47298
private void handle(final Request request, final Response response, final List<Middleware> middlewares) throws Exception {
		if (middlewares.isEmpty()) {
			throw new NotFoundException();
		}
		
		Middleware current = middlewares.remove(0);
		current.handle(request, response, new MiddlewareChain() {
			@Override
			public void next() throws Exception {
				// recursive call
				handle(request, response, middlewares);
			}
		});
	}
653640
@Override
    public void handle(RequestContext context, AuthenticationException e) throws SecurityProviderException,
            IOException {
        String targetUrl = getTargetUrl();
        if (StringUtils.isNotEmpty(targetUrl)) {
            RedirectUtils.redirect(context.getRequest(), context.getResponse(), targetUrl);
        } else {
            sendError(e, context);
        }
    }
110925
@Override
    public T handleResponse(final HttpResponse response) throws IOException {

        InputStream content = null;
        final T addresses;

        try {
            final StatusLine status = response.getStatusLine();
            if (status.getStatusCode() >= HttpStatus.SC_BAD_REQUEST) {
                throw new IOException(String.format("HTTP error: %s %s", status.getStatusCode(), status.getReasonPhrase()));
            }
            content = response.getEntity().getContent();
            addresses = gsonInstance
                    .fromJson(new InputStreamReader(content, "utf-8"), responseType);
        } finally {
            if (null != content) {
                content.close();
            }
            response.getEntity().consumeContent();
        }

        return addresses;
    }