Apply any applicable header overrides to request

@param httpMethodProxyRequest
@throws Exception
514326
private void processRequestHeaderOverrides(HttpMethod httpMethodProxyRequest) throws Exception {
        RequestInformation requestInfo = requestInformation.get();
        for (EndpointOverride selectedPath : requestInfo.selectedRequestPaths) {
            List<EnabledEndpoint> points = selectedPath.getEnabledEndpoints();
            for (EnabledEndpoint endpoint : points) {
                if (endpoint.getOverrideId() == Constants.PLUGIN_REQUEST_HEADER_OVERRIDE_ADD) {
                    httpMethodProxyRequest.addRequestHeader(endpoint.getArguments()[0].toString(),
                                                            endpoint.getArguments()[1].toString());
                    requestInfo.modified = true;
                } else if (endpoint.getOverrideId() == Constants.PLUGIN_REQUEST_HEADER_OVERRIDE_REMOVE) {
                    httpMethodProxyRequest.removeRequestHeader(endpoint.getArguments()[0].toString());
                    requestInfo.modified = true;
                }
            }
        }
    }
1313993
private void checkHttpMethod(R pRequest) {
        if (!restrictor.isHttpMethodAllowed(pRequest.getHttpMethod())) {
            throw new SecurityException("HTTP method " + pRequest.getHttpMethod().getMethod() +
                    " is not allowed according to the installed security policy");
        }
    }
861761
public HttpMethod createRequestMethodNew(HttpRequestHeader header, HttpBody body) throws URIException {
		HttpMethod httpMethod = null;
		
		String method = header.getMethod();
		URI uri	= header.getURI();
		String version = header.getVersion();
		
		httpMethod = new GenericMethod(method);

		httpMethod.setURI(uri);
		HttpMethodParams httpParams = httpMethod.getParams();
		// default to use HTTP 1.0
		httpParams.setVersion(HttpVersion.HTTP_1_0);
		if (version.equalsIgnoreCase(HttpHeader.HTTP11)) {
			httpParams.setVersion(HttpVersion.HTTP_1_1);
		}
		
		// set various headers
		int pos = 0;
		// ZAP: FindBugs fix - always initialise pattern
		Pattern pattern = patternCRLF;
		
		String msg = header.getHeadersAsString();
		if ((pos = msg.indexOf(CRLF)) < 0) {
			if ((pos = msg.indexOf(LF)) < 0) {
				pattern = patternLF;
			}
		} else {
			pattern = patternCRLF;
		}
	        
		String[] split = pattern.split(msg);
		String token = null;
		String name = null;
		String value = null;
		
		for (int i=0; i<split.length; i++) {
			token = split[i];
			if (token.equals("")) {
				continue;
			}
			
			if ((pos = token.indexOf(":")) < 0) {
				return null;
			}
			name  = token.substring(0, pos).trim();
			value = token.substring(pos +1).trim();			
			httpMethod.addRequestHeader(name, value);

		}

		// set body if post method or put method
		if (body != null && body.length() > 0) {
			EntityEnclosingMethod generic = (EntityEnclosingMethod) httpMethod;
            generic.setRequestEntity(new ByteArrayRequestEntity(body.getBytes()));

        }

		httpMethod.setFollowRedirects(false);
		return httpMethod;

	}
140792
public void route(HttpMethods meth, String path, API api, GwCode code) throws Exception {
		String version = "1.0";
		// Get Correct API Class from Mapper
		Class<?> respCls = facade.mapper().getClass(api); 
		if(respCls==null) throw new Exception("Unknown class associated with " + api.getClass().getName() + ' ' + api.name());
		// setup Application API HTML ContentTypes for JSON and Route
		String application = applicationJSON(respCls, version);
		//route(env,meth,path,code,application,"application/json;version="+version,"*/*");

		// setup Application API HTML ContentTypes for XML and Route
		application = applicationXML(respCls, version);
		//route(env,meth,path,code.clone(facade_1_0_XML,false),application,"text/xml;version="+version);
		
		// Add other Supported APIs here as created
	}
1322383
private void processRedirect(String stringStatusCode,
                                 HttpMethod httpMethodProxyRequest,
                                 HttpServletRequest httpServletRequest,
                                 HttpServletResponse httpServletResponse) throws Exception {
        // Check if the proxy response is a redirect
        // The following code is adapted from
        // org.tigris.noodle.filters.CheckForRedirect
        // Hooray for open source software

        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: "
                                           + stringStatusCode + " but no "
                                           + STRING_LOCATION_HEADER
                                           + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather than the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        httpServletResponse.sendRedirect(stringLocation.replace(
            getProxyHostAndPort() + this.getProxyPath(),
            stringMyHostName));
    }
1080465
protected HttpRequest createHttpRequest(URI uri, HttpMethod method) {
        HttpRequest request = new HttpRequest();
        request.setUri(uri);
        request.setMethod(method);

        // Set authorization header
        request.setHeaders(createHeaders());

        return request;
    }
865069
private String checkRequestMethod(HttpServletRequest request, JCorsConfig config) {

		String requestMethod = request.getHeader(CorsHeaders.ACCESS_CONTROL_REQUEST_METHOD_HEADER);
		Constraint.ensureNotEmpty(requestMethod, "Request Method Header must be supplied");

		Constraint.ensureTrue(config.isMethodAllowed(requestMethod),
				String.format("The specified method is not allowed: '%s'", requestMethod));

		return requestMethod;
	}
472905
public HttpRequest method(Method method) {
		if (Method.PATCH == method) {
			this.method = Method.POST;
			this.header("X-HTTP-Method-Override", "PATCH");
		} else {
			this.method = method;
		}
		return this;
	}
756809
protected void setupHTTPRequestHeaderProperties(HTTPRequest httpRequest,HttpMethodBase httpMethodClient)
    {
        //setup header properties
        Properties headerProperties=httpRequest.getHeaderProperties();
        if(headerProperties!=null)
        {
            Iterator<Entry<Object,Object>> iterator=headerProperties.entrySet().iterator();
            Entry<Object,Object> entry=null;
            while(iterator.hasNext())
            {
                //get next entry
                entry=iterator.next();
                
                //set header values
                httpMethodClient.addRequestHeader((String)entry.getKey(),(String)entry.getValue());
            }
        }
    }
19049
protected final void setHttpProxyHost(String proxyHost) {
        httpConf = new MyHttpClientConfiguration(proxyHost
                , httpConf.getHttpProxyUser()
                , httpConf.getHttpProxyPassword()
                , httpConf.getHttpProxyPort()
                , httpConf.isHttpProxySocks()
                , httpConf.getHttpConnectionTimeout()
                , httpConf.getHttpReadTimeout()
                , httpConf.isPrettyDebugEnabled(), httpConf.isGZIPEnabled()
        );
    }
33887
private void applyResponseOverrides(PluginResponse httpServletResponse,
                                        HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest, History history) throws Exception {
        RequestInformation requestInfo = requestInformation.get();

        for (EndpointOverride selectedPath : requestInfo.selectedResponsePaths) {
            // check to see if there is custom override data
            // something like
            List<EnabledEndpoint> points = selectedPath.getEnabledEndpoints();
            for (EnabledEndpoint endpoint : points) {
                // skip if the repeat number is 0
                if (endpoint.getRepeatNumber() == 0) {
                    continue;
                }

                // skip if this is a custom override and one has already been applied
                if (endpoint.getOverrideId() == Constants.PLUGIN_RESPONSE_OVERRIDE_CUSTOM &&
                    requestInfo.usedCustomResponse) {
                    continue;
                }

                // decrease repeat number
                endpoint.decrementRepeatNumber();

                if (endpoint.getOverrideId() == Constants.PLUGIN_RESPONSE_OVERRIDE_CUSTOM) {
                    // return custom response
                    String response = endpoint.getArguments()[0].toString();
                    String responseCode = endpoint.getResponseCode();
                    if (responseCode != null && !responseCode.isEmpty()) {
                        httpServletResponse.setStatus(Integer.parseInt(responseCode));
                    }
                    httpServletResponse.setContentType(selectedPath.getContentType());
                    requestInfo.usedCustomResponse = true;
                    requestInfo.modified = true;
                    PluginHelper.writeResponseContent(httpServletResponse, response);
                } else if (endpoint.getOverrideId() == Constants.PLUGIN_RESPONSE_HEADER_OVERRIDE_ADD) {
                    httpServletResponse = (PluginResponse) HttpUtilities.addHeader(httpServletResponse, endpoint.getArguments());
                    requestInfo.modified = true;
                } else if (endpoint.getMethodInformation() != null &&
                    (endpoint.getMethodInformation().getMethodType().equals(Constants.PLUGIN_TYPE_RESPONSE_OVERRIDE) ||
                        endpoint.getMethodInformation().getMethodType().equals(Constants.PLUGIN_TYPE_RESPONSE_OVERRIDE_V2))) {
                    // run method
                    try {
                        com.groupon.odo.proxylib.models.Method methodInfo =
                            PathOverrideService.getInstance().getMethodForEnabledId(endpoint.getOverrideId());

                        logger.info("method = {}", methodInfo);
                        logger.info("Enabled endpoint: {}", methodInfo.getMethodName());
                        logger.info("Calling override for {}",
                                    httpServletRequest.getRequestURL() + "?" + httpServletRequest.getQueryString());

                        // For v1 plugins - verify HTTP code is set correctly
                        if (methodInfo.getOverrideVersion() == 1) {
                            logger.info("Running {}", methodInfo.getMethodName());
                            String responseOutput = (String) PluginManager.getInstance().callFunction(methodInfo.getClassName(), methodInfo.getMethodName(),
                                                                                                      httpServletResponse.getContentString(), endpoint.getArguments());
                            PluginHelper.writeResponseContent(httpServletResponse, responseOutput);

                            if (methodInfo.getHttpCode() != httpServletResponse.getStatus()) {
                                logger.info("Setting HTTP Code to {}", methodInfo.getHttpCode());
                                httpServletResponse.setStatus(methodInfo.getHttpCode());
                                // the server might have set a "Status" header.. so let's reset this too
                                httpServletResponse.setHeader(Constants.HEADER_STATUS,
                                                              Integer.toString(methodInfo.getHttpCode()));
                            }
                        } else if (methodInfo.getOverrideVersion() == 2) {
                            PluginArguments pluginArgs = new PluginArguments(httpServletResponse, requestInfo.originalRequestInfo, httpMethodProxyRequest);

                            PluginManager.getInstance().callFunction(
                                methodInfo.getClassName(), methodInfo.getMethodName(),
                                pluginArgs, endpoint.getArguments());
                        }

                        requestInfo.modified = true;
                        logger.info("Done calling override");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        httpServletResponse.flushBuffer();
    }
594600
protected void setRequestContent(HTTPRequest httpRequest,HttpMethodBase httpMethodClient)
    {
        //set content
        if(httpMethodClient instanceof EntityEnclosingMethod)
        {
            EntityEnclosingMethod pushMethod=(EntityEnclosingMethod)httpMethodClient;
            
            RequestEntity requestEntity=null;
            ContentType contentType=httpRequest.getContentType();
            switch(contentType)
            {
                case STRING:
                    requestEntity=this.createStringRequestContent(httpRequest);
                    break;
                case BINARY:
                    requestEntity=this.createBinaryRequestContent(httpRequest);
                    break;
                case MULTI_PART:
                    requestEntity=this.createMultiPartRequestContent(httpRequest,httpMethodClient);
                    break;
                default:
                    throw new FaxException("Unsupported content type: "+contentType);
            }

            //set request data
            if(requestEntity!=null)
            {
                pushMethod.setRequestEntity(requestEntity);
                pushMethod.setContentChunked(false);
            }
        }
    }
116570
public void setHttpProxy(String httpProxy) {
		this.httpProxy = httpProxy;
		
		if (httpProxy == null) {
//			throw new IllegalArgumentException("'httpProxy' cannot be null");
			return;
		}
		
		String[] tokens = httpProxy.split(":");
		int count = tokens.length; 
		if (count == 1) {
			System.setProperty("http.proxyHost", tokens[0]);
		} else if (count == 2) {
			System.setProperty("http.proxyHost", tokens[0]);
			System.setProperty("http.proxyPort", tokens[1]);
		}		
	}
152227
protected HTTPResponse submitHTTPRequestImpl(HTTPRequest httpRequest,HTTPMethod httpMethod)
    {
        return this.httpClient.submitHTTPRequest(httpRequest,this.httpClientConfiguration,httpMethod);
    }
962679
protected void handleHttpRequest(final ChannelHandlerContext channelContext, final HttpRequest request) throws Exception {
        if (isWebSocketsUpgradeRequest( request )) {

            final Handshake handshake = findHandshake( request );

            if (handshake != null) {

                HttpResponse response = handshake.generateResponse( request );

                response.addHeader( Names.UPGRADE, Values.WEBSOCKET );
                response.addHeader( Names.CONNECTION, Values.UPGRADE );

                final ChannelPipeline pipeline = channelContext.getChannel().getPipeline();
                reconfigureUpstream( pipeline, handshake );

                Channel channel = channelContext.getChannel();
                ChannelFuture future = channel.write( response );
                future.addListener( new ChannelFutureListener() {
                    public void operationComplete(ChannelFuture future) throws Exception {
                        reconfigureDownstream( pipeline, handshake );
                        pipeline.replace( ServerHandshakeHandler.this, "websocket-disconnection-negotiator", new WebSocketDisconnectionNegotiator() );
                        forwardConnectEventUpstream( channelContext );
                        decodeHost( channelContext, request );
                        decodeSession( channelContext, request );
                    }
                } );

                return;
            }
        }

        // Send an error page otherwise.
        sendHttpResponse( channelContext, request, new DefaultHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN ) );
    }
522052
void doMethod(HttpServletRequest request, HttpServletResponse response, HttpMethod httpMethod) {

        // Locate a request handler:
        String requestPath = mapRequestPath(request);
        Route route = api.get(requestPath);

        try {

            if (route != null && route.requestHandlers.containsKey(httpMethod)) {
                handleRequest(request, response, route, httpMethod);
            } else {
                handleNotFound(request, response);
            }

        } catch (Throwable t) {

            // Chances are the exception we've actually caught is the reflection
            // one from Method.invoke(...)
            Throwable caught = t;
            if (InvocationTargetException.class.isAssignableFrom(t.getClass())) {
                caught = t.getCause();
            }

            RequestHandler requestHandler = (route == null ? null : route.requestHandlers.get(httpMethod));
            handleError(request, response, requestHandler, caught);
        }

    }
215418
protected function _loadRequestMethod()
    {
        if($this->_requestMethod !== NULL) return;

        if(!key_exists('REQUEST_METHOD', $_SERVER)) {
            throw new Exception("Request method unknown");
        }

        $method = strtoupper($_SERVER['REQUEST_METHOD']);

        if (in_array($method, array('GET', 'POST', 'PUT', 'DELETE', 'PATCH'))) {
            $this->_requestMethod = $method;
        } else {
            throw new Exception("Request method ($method) invalid");
        }
    }