Services a single request.
Supports HTTP and HTTPS.

@param pRequest
@param pResponse

@throws ServletException
@throws IOException

@see ProxyServlet Class descrition
517446
protected void service(HttpServletRequest pRequest, HttpServletResponse pResponse) throws ServletException, IOException {
        // Sanity check configuration
        if (remoteServer == null) {
            log(MESSAGE_REMOTE_SERVER_NOT_CONFIGURED);
            pResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    MESSAGE_REMOTE_SERVER_NOT_CONFIGURED);
            return;
        }

        HttpURLConnection remoteConnection = null;
        try {
            // Recreate request URI for remote request
            String requestURI = createRemoteRequestURI(pRequest);
            URL remoteURL = new URL(pRequest.getScheme(), remoteServer, remotePort, requestURI);

            // Get connection, with method from original request
            // NOTE: The actual connection is not done before we ask for streams...
            // NOTE: The HttpURLConnection is supposed to handle multiple
            // requests to the same server internally
            String method = pRequest.getMethod();
            remoteConnection = (HttpURLConnection) remoteURL.openConnection();
            remoteConnection.setRequestMethod(method);

            // Copy header fields
            copyHeadersFromClient(pRequest, remoteConnection);

            // Do proxy specifc stuff?
            // TODO: Read up the specs from RFC 2616 (HTTP) on proxy behaviour
            // TODO: RFC 2616 says "[a] proxy server MUST NOT establish an HTTP/1.1
            // persistent connection with an HTTP/1.0 client"

            // Copy message body from client to remote server
            copyBodyFromClient(pRequest, remoteConnection);

            // Set response status code from remote server to client
            int responseCode = remoteConnection.getResponseCode();
            pResponse.setStatus(responseCode);
            //System.out.println("Response is: " + responseCode + " " + remoteConnection.getResponseMessage());

            // Copy header fields back
            copyHeadersToClient(remoteConnection, pResponse);

            // More proxy specific stuff?

            // Copy message body from remote server to client
            copyBodyToClient(remoteConnection, pResponse);
        }
        catch (ConnectException e) {
            // In case we could not connecto to the remote server
            log("Could not connect to remote server.", e);
            pResponse.sendError(HttpServletResponse.SC_BAD_GATEWAY, e.getMessage());
        }
        finally {
            // Disconnect from server
            // TODO: Should we actually do this?
            if (remoteConnection != null) {
                remoteConnection.disconnect();
            }
        }
    }
93529
public void preInvoke( InterceptorContext context, InterceptorChain chain ) throws InterceptorException
    {
        preRequest( ( RequestInterceptorContext ) context, chain );
    }
561849
public void proxySubsequentRequest(MobicentsSipServletRequest sipServletRequest) {
		SipServletRequestImpl request = (SipServletRequestImpl) sipServletRequest;
		
		MobicentsSipServletResponse lastFinalResponse = (MobicentsSipServletResponse) request.getLastFinalResponse();
		if(lastFinalResponse != null && lastFinalResponse.isMessageSent()) {
		    // https://code.google.com/p/sipservlets/issues/detail?id=21
		    if(logger.isDebugEnabled()) {
		        logger.debug("Not proxying request as final response has already been sent for " + request);
		    }
		    return;
	    }
		
		addTransaction(request);
		// A re-INVITE needs special handling without going through the dialog-stateful methods
		if(request.getMethod().equalsIgnoreCase("INVITE")) {
			if(logger.isDebugEnabled()) {
				logger.debug("Proxying reinvite request " + request);
			}			
			proxyDialogStateless(request);
			return;
		}
		
		if(logger.isDebugEnabled()) {
			logger.debug("Proxying subsequent request " + request);
		}
		
		// Update the last proxied request
		request.setRoutingState(RoutingState.PROXIED);
		if(!request.getMethod().equalsIgnoreCase(Request.ACK) ) {
			proxy.setOriginalRequest(request);
			this.originalRequest = request;
		}
		
		// No proxy params, sine the target is already in the Route headers
//		final ProxyParams params = new ProxyParams(null, null, null, null);
		Request clonedRequest = null;
		if(request.getMethod().equalsIgnoreCase(Request.NOTIFY) || request.getMethod().equalsIgnoreCase(Request.SUBSCRIBE)) {
			// https://github.com/RestComm/sip-servlets/issues/121 http://tools.ietf.org/html/rfc6665#section-4.3
			clonedRequest = ProxyUtils.createProxiedRequest(request, this, null, outboundInterface, recordRouteURI, null);
		} else {
			clonedRequest = ProxyUtils.createProxiedRequest(request, this, null, null, null, null);
		}

//      There is no need for that, it makes application composition fail (The subsequent request is not dispatched to the next application since the route header is removed)
//		RouteHeader routeHeader = (RouteHeader) clonedRequest.getHeader(RouteHeader.NAME);
//		if(routeHeader != null) {
//			if(!((SipApplicationDispatcherImpl)proxy.getSipFactoryImpl().getSipApplicationDispatcher()).isRouteExternal(routeHeader)) {
//				clonedRequest.removeFirst(RouteHeader.NAME);	
//			}
//		}

		// https://telestax.atlassian.net/browse/MSS-153 perf optimization : we update the timer only on non ACK
		if(!clonedRequest.getMethod().equalsIgnoreCase(Request.ACK) ) {
			if(logger.isDebugEnabled()) {
				logger.debug("proxySubsequentRequest - calling updateTimer - request " + request);
			}
			updateTimer(false, request.getSipApplicationSession(false)); 
		}
 
		try {
			// Reset the proxy supervised state to default Chapter 6.2.1 - page down list bullet number 6
			proxy.setSupervised(true);
			if(clonedRequest.getMethod().equalsIgnoreCase(Request.ACK) ) { //|| clonedRequest.getMethod().equalsIgnoreCase(Request.PRACK)) {
				if(logger.isDebugEnabled()) {
					logger.debug("proxySubsequentRequest - clonedRequest is ACK - request " + request);
				}
				
				// we mark them as accessed so that HA replication can occur
				final MobicentsSipSession sipSession = request.getSipSession();
				final MobicentsSipApplicationSession sipApplicationSession = sipSession.getSipApplicationSession();
				sipSession.access();
				if(sipApplicationSession != null) {
					sipApplicationSession.access();
				}
				final String transport = JainSipUtils.findTransport(clonedRequest);
				SipFactoryImpl sipFactoryImpl = proxy.getSipFactoryImpl();
				SipNetworkInterfaceManager sipNetworkInterfaceManager = sipFactoryImpl.getSipNetworkInterfaceManager();
				final SipProvider sipProvider = sipNetworkInterfaceManager.findMatchingListeningPoint(
						transport, false).getSipProvider();
				SipConnector sipConnector = StaticServiceHolder.sipStandardService.findSipConnector(transport);
				
				// Optimizing the routing for AR (if any)
				if(sipConnector.isUseStaticAddress()) {
					JainSipUtils.optimizeRouteHeaderAddressForInternalRoutingrequest(
							sipConnector, clonedRequest, sipSession, sipFactoryImpl, transport);
					try {
						JainSipUtils.optimizeViaHeaderAddressForStaticAddress(sipConnector, clonedRequest, sipFactoryImpl, transport);
					} catch (Exception e) {
						throw new RuntimeException(e);
					}
				}
				try {
					RFC5626Helper.checkRequest(this, clonedRequest, originalRequest);
				} catch (IncorrectFlowIdentifierException e1) {
					logger.warn(e1.getMessage());		
					this.cancel();
					return;
				}
				sipProvider.sendRequest(clonedRequest);
				sipFactoryImpl.getSipApplicationDispatcher().updateRequestsStatistics(clonedRequest, false);
			}
			else {				
				if(logger.isDebugEnabled()) {
					logger.debug("proxySubsequentRequest - calling forwardRequest - request " + request);
				}
				forwardRequest(clonedRequest, true);
			}
			
		} catch (SipException e) {
			logger.error("A problem occured while proxying a subsequent request", e);
		}
	}
723273
private HttpUriRequest proxyRequest(HttpServletRequest request) throws ServletException,
            IOException {
        String newUri = serviceUriForRequest(request);

        BasicHttpEntityEnclosingRequest httpRequest
                = new BasicHttpEntityEnclosingRequest(request.getMethod(), newUri);
        HttpEntity entity = new InputStreamEntity(request.getInputStream(),
                request.getContentLength());
        httpRequest.setEntity(entity);

        try {
            // Sadly have to do this to set the URI; it is not derived from the original httpRequest
            HttpRequestWrapper wrappedRequest = HttpRequestWrapper.wrap(httpRequest);
            wrappedRequest.setURI(new URI(newUri));

            // Somehow, content type header does not come in the original request either
            wrappedRequest.setHeader("Content-Type", "application/json");

            return wrappedRequest;
        } catch (URISyntaxException e) {
            LOGGER.error("Syntax exception in service URI, " + newUri, e);
            throw new LightblueServletException("Syntax exception in service URI, " + newUri, e);
        }
    }
1202980
public void service(ServletRequest req, ServletResponse res, WebAppServletInvocationEvent evt) throws IOException, ServletException {
        // 569469
        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE)) {
            logger.entering(CLASS_NAME, "service " + this.toString());
        }
        // 569469

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        
        HttpServletRequest httpRequest = null;
        IExtendedRequest wasreq = null;
        
        if(useOriginalRequestState){
                
                WebContainerRequestState reqStateSaveFilteredRequest = WebContainerRequestState.getInstance(false);
                if(reqStateSaveFilteredRequest != null){                        
                        httpRequest = (HttpServletRequest)reqStateSaveFilteredRequest.getAttribute("unFilteredRequestObject");
                        //remove attribute
                        reqStateSaveFilteredRequest.removeAttribute("unFilteredRequestObject");
                        if(httpRequest != null) {
                                wasreq = (IExtendedRequest) ServletUtil.unwrapRequest(httpRequest);                     
                        }
                }               
        }
        //if httpRequest is null then get it from unwrapped
        if(httpRequest == null)
        {
                wasreq = (IExtendedRequest) ServletUtil.unwrapRequest(request);
        }
       // IExtendedRequest wasreq = (IExtendedRequest) ServletUtil.unwrapRequest(req);
        WebAppDispatcherContext dispatchContext = (WebAppDispatcherContext) wasreq.getWebAppDispatcherContext();

        boolean writeResponseBody = true;
        // PK55965 Start
        boolean notify = notifyInvocationListeners && (evt != null);
        long curLastAccessTime = 0;
        long endTime = 0;

        if (notify) {
            evtSource.onServletStartService(evt);
            curLastAccessTime = System.currentTimeMillis();
        }
        // PK55965 End

        try {
            synchronized (this) {
                nServicing++;
            }
            boolean isInclude = dispatchContext.isInclude();
            if (!isInclude) {
                writeResponseBody = setResponseHeaders(request, response);
            }
            if (writeResponseBody) {

                // begin pq65763
                // <!-- move response writing into separate method -->
                writeResponseToClient(request, response, wasreq);
                // end pq65763
            }

            // PK55965 Start
            if (notify) {
                endTime = System.currentTimeMillis();
                evt.setResponseTime(endTime - curLastAccessTime);
                evtSource.onServletFinishService(evt);
            }
        } catch (Throwable e) {

            if (notify) {
                if (endTime == 0) {
                    endTime = System.currentTimeMillis();
                    evt.setResponseTime(endTime - curLastAccessTime);
                    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE)) {
                        logger.logp(Level.FINE, CLASS_NAME, "service", "Notify onServletFinishService : response time "
                                    + (endTime - curLastAccessTime) + " milliseconds");
                    }
                    evtSource.onServletFinishService(evt);
                }
                ServletErrorEvent errorEvent = new ServletErrorEvent(this, getServletContext(), getServletName(), "FileServletWrapper", e);
                if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE)) {
                    logger.logp(Level.FINE, CLASS_NAME, "service", "Notify onServletServiceError : " + errorEvent.toString());
                }
                evtSource.onServletServiceError(errorEvent);
            }
            throw new ServletException(e);

        } finally {
            synchronized (this) {
                nServicing--;
            }
            // 569469
            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE)) {
                logger.exiting(CLASS_NAME, "service");
            }
            // 569469
        }
    }
445357
public void updateStreamPresets(UpdateStreamPresetsRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");

        checkStringNotEmpty(request.getDomain(), "Domain should NOT be empty.");
        checkStringNotEmpty(request.getApp(), "App should NOT be empty");
        checkStringNotEmpty(request.getStream(), "Stream should NOT be empty.");
        // presets can be null for letting stream to use domain's presets,
        // so no need to check if presets is null

        InternalRequest internalRequest = createRequest(HttpMethodName.POST, request, LIVE_DOMAIN,
                request.getDomain(), LIVE_APP, request.getApp(), LIVE_STREAM, request.getStream());
        internalRequest.addParameter("presets", null);
        invokeHttpClient(internalRequest, AbstractBceResponse.class);
    }
241816
protected boolean trigger(ServletRequest pRequest) {
        boolean trigger = false;

        if (pRequest instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) pRequest;
            String accept = getAcceptedFormats(request);
            String originalFormat = getServletContext().getMimeType(request.getRequestURI());

            //System.out.println("Accept: " + accept);
            //System.out.println("Original format: " + originalFormat);

            // Only override original format if it is not accpeted by the client
            // Note: Only explicit matches are okay, */* or image/* is not.
            if (!StringUtil.contains(accept, originalFormat)) {
                trigger = true;
            }
        }

        // Call super, to allow content negotiation even though format is supported
        return trigger || super.trigger(pRequest);
    }
86809
private void processInternal( HttpServletRequest request, HttpServletResponse response )
            throws IOException, ServletException
    {
        //
        // First wrap the request with an object that contains request-scoped values that our runtime uses.  This
        // is faster than sticking everything into attributes on the request (then basically reading from a HashMap).
        //
        request = PageFlowRequestWrapper.wrapRequest( request );

        String uri = InternalUtils.getDecodedServletPath( request );
        ServletContext servletContext = getServletContext();

        // The ServletContainerAdapter reference may have been lost during serialization/deserialization.
        if (_servletContainerAdapter == null) {
            _servletContainerAdapter = AdapterManager.getServletContainerAdapter( servletContext );
        }

        //
        // Allow the container to do a security check on forwarded requests, if that feature is enabled.
        //
        if ( LegacySettings.get( servletContext ).shouldDoSecureForwards()
             && PageFlowRequestWrapper.get( request ).isForwardedRequest() )
        {
            //
            // In some situations (namely, in scoped requests under portal), the initial
            // security check may not have been done for the request URI.  In this case, a redirect
            // to https may happen during checkSecurity().
            //
            if ( _servletContainerAdapter.doSecurityRedirect( uri, request, response ) )
            {
                if ( LOG.isDebugEnabled() )
                    LOG.debug( "checkSecurity() caused a redirect.  Ending processing for this request "
                               + '(' + uri + ')' );

                return;
            }
        }

        //
        // If we've come in on a forced redirect due to security constraints, look for request attrs
        // that we put into the session.
        //
        String hash = request.getParameter( REDIRECT_REQUEST_ATTRS_PARAM );
        if ( hash != null )
        {
            HttpSession session = request.getSession( false );

            if ( session != null )
            {
                String carryoverAttrName = makeRedirectedRequestAttrsKey( uri, hash );
                Map attrs = ( Map ) session.getAttribute( carryoverAttrName );
                session.removeAttribute( carryoverAttrName );

                if ( attrs != null )
                {
                    for ( Iterator i = attrs.entrySet().iterator(); i.hasNext(); )
                    {
                        Map.Entry entry = ( Map.Entry ) i.next();

                        String attrName = ( String ) entry.getKey();
                        if ( request.getAttribute( attrName ) == null )
                        {
                            request.setAttribute( attrName, entry.getValue() );
                        }
                    }
                }
            }
        }

        //
        // The requested action can be overridden by a request parameter.  In this case, we parse the action from
        // the request parameter and forward to a URI constructed from it.  If this happens, just return.
        //
        if ( processActionOverride( request, response ) ) return;

        //
        // Process any direct request for a page flow by forwarding to its "begin" action.
        //
        if ( processPageFlowRequest( request, response, uri ) ) return;

        //
        // Get the FlowController for this request (page flow or shared flow), and cache it in the request.
        //
        String flowControllerClassName = InternalUtils.getFlowControllerClassName( moduleConfig );

        if ( flowControllerClassName == null &&
             ! ( moduleConfig instanceof AutoRegisterActionServlet.MissingRootModuleControllerConfig ) )
        {
            //
            // If this isn't a blank module initialized in place of a missing root PageFlowController, emit a warning
            // about the missing controllerClass property.
            //
            if(LOG.isWarnEnabled())
                LOG.warn( "Struts module " + moduleConfig.getPrefix() + " is configured to use " + getClass().getName()
                    + " as the request processor, but the <controller> element does not contain a <set-property>"
                    + " for \"controllerClass\".  Page Flow actions in this module may not be handled correctly." );
        }

        //
        // Look up or create the appropriate SharedFlowControllers if they don't exist.
        //
        if ( LOG.isInfoEnabled() )
            LOG.info( "Attempting to instantiate SharedFlowControllers for request " + request.getRequestURI() );

        FlowController currentFlowController = null;

        try
        {
            RequestContext requestContext = new RequestContext( request, response );
            Map/*< String, SharedFlowController >*/ sharedFlows =
                    _flowControllerFactory.getSharedFlowsForRequest( requestContext );

            /* todo: why are the shared flow / global app objects loaded for data binding here? */
            ImplicitObjectUtil.loadSharedFlow( request, sharedFlows );
            ImplicitObjectUtil.loadGlobalApp( request, PageFlowUtils.getGlobalApp( request ) );

            if ( flowControllerClassName != null )
            {
                currentFlowController = getFlowController( requestContext, flowControllerClassName );
                PageFlowRequestWrapper.get( request ).setCurrentFlowController( currentFlowController );
            }
            else
            {
                PageFlowRequestWrapper.get( request ).setCurrentFlowController( null );
            }
        }
        catch ( ClassNotFoundException e )
        {
            LOG.error( "Could not find FlowController class " + flowControllerClassName, e );
            ServletUtils.throwServletException(e);
        }
        catch ( InstantiationException e )
        {
            LOG.error( "Could not instantiate FlowController of type " + flowControllerClassName, e );
            ServletUtils.throwServletException(e);
        }
        catch ( IllegalAccessException e )
        {
            LOG.error( "Could not instantiate FlowController of type " + flowControllerClassName, e );
            ServletUtils.throwServletException(e);
        }

        //
        // Get the page flow for this request.
        //
        PageFlowController jpf = PageFlowUtils.getCurrentPageFlow( request, getServletContext() );

        //
        // Remove any current JavaServer Faces backing bean.  We have "left" any JSF page and are now processing a
        // Page Flow action.
        //
        InternalUtils.removeCurrentFacesBackingBean( request, servletContext );

        //
        // Set up implicit objects used by the expression language in simple actions and in declarative validation.
        //
        ImplicitObjectUtil.loadImplicitObjects( request, response, servletContext, jpf );

        try
        {
            super.process( request, response );
        }
        catch ( UnhandledException unhandledException )
        {
            // If we get here, then we've already tried to find an exception handler.  Just throw.
            rethrowUnhandledException( unhandledException );
        }
        catch ( ServletException servletEx )
        {
            // If a ServletException escapes out of any of the processing methods, let the current FlowController handle it.
            if ( ! handleException( servletEx, currentFlowController, request, response ) )
                throw servletEx;
        }
        catch ( IOException ioe )
        {
            // If an IOException escapes out of any of the processing methods, let the current FlowController handle it.
            if ( ! handleException( ioe, currentFlowController, request, response ) )
                throw ioe;
        }
        catch ( Throwable th )
        {
            // If a Throwable escapes out of any of the processing methods, let the current FlowController handle it.
            if ( ! handleException( th, currentFlowController, request, response ) )
            {
                if ( th instanceof Error )
                    throw ( Error ) th;
                ServletUtils.throwServletException(th);
            }
        }
    }
709857
def preprocessRequest(self, service_request, *args, **kwargs):
        
        processor = self.getPreprocessor(service_request)

        if self.logger:
            self.logger.debug('Preprocessor expands to: %r' % processor)

        if processor is None:
            return

        args = (service_request,) + args

        if hasattr(processor, '_pyamf_expose_request'):
            http_request = kwargs.get('http_request', None)
            args = (http_request,) + args

        return defer.maybeDeferred(processor, *args)
847969
public void service(HttpServletRequest req, HttpServletResponse resp) 
        throws ServletException, IOException
    {
	    boolean fileFound = sendResourceFile(req, resp);
		if (!fileFound)
		    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
//    	super.service(req, resp);
    }
652241
public final void doReportPdf(final HttpServletRequest pReq,
    final HttpServletResponse pResp) throws ServletException, IOException {
    pReq.setCharacterEncoding("UTF-8");
    try {
      HashMap<String, Object> reqVars = new HashMap<String, Object>();
      String nameHandler = pReq.getParameter("nmHnd");
      IHndlFileReportReq srvHandleRequest = (IHndlFileReportReq) this
        .factoryAppBeans.lazyGet(nameHandler);
      HttpRequestData requestData = new HttpRequestData(pReq, pResp);
      requestData.setAttribute("reqVars", reqVars);
      IHandlerRequest hndlI18nRequest = (IHandlerRequest) this
        .factoryAppBeans.lazyGet("hndlI18nRequest");
      hndlI18nRequest.handle(reqVars, requestData);
      pResp.setContentType("application/pdf");
      String fileName = pReq.getParameter("fileName");
      if (fileName != null && !"".equals(fileName)) {
        pResp.setHeader("Content-Disposition", "attachment; filename="
          + fileName + ".pdf");
      }
      srvHandleRequest.handle(reqVars, requestData, pResp.getOutputStream());
    } catch (Exception e) {
      if (factoryAppBeans != null) {
        ILog logger = null;
        try {
          logger = (ILog) factoryAppBeans.lazyGet("ILog");
        } catch (Exception e1) {
          e1.printStackTrace();
        }
        if (logger != null) {
          logger.error(null, getClass(), "WORK", e);
        } else {
          e.printStackTrace();
        }
      } else {
        e.printStackTrace();
      }
      if (e instanceof ExceptionWithCode) {
        pReq.setAttribute("error_code",
          ((ExceptionWithCode) e).getCode());
        pReq.setAttribute("short_message",
          ((ExceptionWithCode) e).getShortMessage());
      } else {
        pReq.setAttribute("error_code",
          HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      }
      pReq.setAttribute("javax.servlet.error.status_code",
        HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      pReq.setAttribute("javax.servlet.error.exception", e);
      pReq.setAttribute("javax.servlet.error.request_uri",
        pReq.getRequestURI());
      pReq.setAttribute("javax.servlet.error.servlet_name", this.getClass()
        .getCanonicalName());
      pResp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  }
620105
@Override
	public void doFilter(final ServletRequest servletRequest,
			final ServletResponse servletResponse,
			final FilterChain filterChain) throws IOException,
			ServletException {
		if (!(servletRequest instanceof HttpServletRequest)
				|| !(servletResponse instanceof HttpServletResponse)) {
			String message
					= "CORS doesn't support non-HTTP request or response.";
			throw new ServletException(message);
		}

		// Safe to downcast at this point.
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;

		// Determines the CORS request type.
		CORSFilter.CORSRequestType requestType = checkRequestType(request);

		// Adds CORS specific attributes to request.
		if (decorateRequest) {
			CORSFilter.decorateCORSProperties(request, requestType);
		}
		switch (requestType) {
			case SIMPLE:
				// Handles a Simple CORS request.
				this.handleSimpleCORS(request, response, filterChain);
				break;
			case ACTUAL:
				// Handles an Actual CORS request.
				this.handleSimpleCORS(request, response, filterChain);
				break;
			case PRE_FLIGHT:
				// Handles a Pre-flight CORS request.
				this.handlePreflightCORS(request, response, filterChain);
				break;
			case NOT_CORS:
				// Handles a Normal request that is not a cross-origin request.
				this.handleNonCORS(request, response, filterChain);
				break;
			default:
				// Handles a CORS request that violates specification.
				this.handleInvalidCORS(request, response, filterChain);
				break;
		}
	}
1350189
private void executeProxyRequest(HttpMethod httpMethodProxyRequest,
                                     HttpServletRequest httpServletRequest,
                                     HttpServletResponse httpServletResponse, History history) {
        try {
            RequestInformation requestInfo = requestInformation.get();

            // Execute the request

            // set virtual host so the server knows how to direct the request
            // If the host header exists then this uses that value
            // Otherwise the hostname from the URL is used
            processVirtualHostName(httpMethodProxyRequest, httpServletRequest);
            cullDisabledPaths();

            // check for existence of ODO_PROXY_HEADER
            // finding it indicates a bad loop back through the proxy
            if (httpServletRequest.getHeader(Constants.ODO_PROXY_HEADER) != null) {
                logger.error("Request has looped back into the proxy.  This will not be executed: {}", httpServletRequest.getRequestURL());
                return;
            }

            // set ODO_PROXY_HEADER
            httpMethodProxyRequest.addRequestHeader(Constants.ODO_PROXY_HEADER, "proxied");

            requestInfo.blockRequest = hasRequestBlock();
            PluginResponse responseWrapper = new PluginResponse(httpServletResponse);
            requestInfo.jsonpCallback = stripJSONPToOutstr(httpServletRequest, responseWrapper);

            if (!requestInfo.blockRequest) {
                logger.info("Sending request to server");

                history.setModified(requestInfo.modified);
                history.setRequestSent(true);

                executeRequest(httpMethodProxyRequest,
                               httpServletRequest,
                               responseWrapper,
                               history);
            } else {
                history.setRequestSent(false);
            }

            logOriginalResponseHistory(responseWrapper, history);
            applyResponseOverrides(responseWrapper, httpServletRequest, httpMethodProxyRequest, history);
            // store history
            history.setModified(requestInfo.modified);
            logRequestHistory(httpMethodProxyRequest, responseWrapper, history);

            writeResponseOutput(responseWrapper, requestInfo.jsonpCallback);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
980807
@Override
    public void service(HttpServletRequest req, HttpServletResponse res) 
        throws ServletException, IOException
    {
        ServletTask servletTask = new ServletTask(this, BasicServlet.SERVLET_TYPE.COCOON);
        try {
            this.addBrowserProperties(req, servletTask);
    		ScreenModel screen = servletTask.doProcessInput(this, req, null);
    		
            Transformer transformer = getTransformer(req, servletTask, screen); // Screen can't be freed when I call this.
    
            PipedReader in = new PipedReader();
            PipedWriter out = new PipedWriter(in);
            
            new ProcessOutputThread(this, out, servletTask, req, screen, true).start();
            // Note: Print Thread frees the servlettask when it is done.
    
            StreamSource source = new StreamSource(in);
    
            ServletOutputStream outStream = res.getOutputStream();
            res.setContentType("text/html");	// Always for servlets/screens
            Result result = new StreamResult(outStream);

            synchronized (transformer)
            {
                transformer.transform(source, result);  // Get the data from the pipe (thread) and transform it to http
            }
        } catch (TransformerException ex) {
            ex.printStackTrace();
            servletTask.free();
        } catch (ServletException ex) {
            servletTask.free();
            throw ex;
        } catch (IOException ex) {
            servletTask.free();
            throw ex;
        } catch (Exception ex) {
            servletTask.free();
        }
	
    	//x Don't call super.service(req, res);
    }
902885
def pre_request(self, response, exc=None):
        
        if response.request.method == 'CONNECT':
            self.start_response(
                '200 Connection established',
                [('content-length', '0')]
            )
            # send empty byte so that headers are sent
            self.future.set_result([b''])
            # proxy - server connection
            upstream = response.connection
            # client - proxy connection
            dostream = self.connection
            # Upgrade downstream connection
            dostream.upgrade(partial(StreamTunnel.create, upstream))
            #
            # upstream upgrade
            upstream.upgrade(partial(StreamTunnel.create, dostream))
            response.fire_event('post_request')
            # abort the event
            raise AbortEvent
        else:
            response.event('data_processed').bind(self.data_processed)
            response.event('post_request').bind(self.post_request)
990954
@Override
    public void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
            throws ServletException, IOException {
        CallFuture<NaviRpcResponse> callFuture = new CallFuture<NaviRpcResponse>();
        try {
            NaviRpcExporter serviceExporter = getRpcExporter(httpRequest);
            String protocol = getProtocolByHttpContentType(httpRequest);
            LocalContext.getContext().setStartTime().setProtocol(protocol)
                    .setFromIp(IPUtils.getIpAddr(httpRequest))
                    .setServiceName(serviceExporter.getName());

            byte[] byteArray = ByteUtil.readStream(httpRequest.getInputStream(),
                    httpRequest.getContentLength());
            LocalContext.getContext().setReqByteSize(byteArray.length);

            NaviRpcRequest request = new NaviRpcRequest(serviceExporter, byteArray);
            processor.service(request, callFuture);
        } catch (InvalidRequestException e) {
            callFuture.cancel(true);
            LOG.warn(e.getMessage());
            httpResponse.setStatus(HttpStatus.SC_BAD_REQUEST);
        } catch (InvalidProtocolException e) {
            callFuture.cancel(true);
            LOG.warn(e.getMessage());
            httpResponse.setStatus(HttpStatus.SC_NOT_ACCEPTABLE);
        } catch (ServiceNotFoundException e) {
            callFuture.cancel(true);
            LOG.warn(e.getMessage());
            httpResponse.setStatus(HttpStatus.SC_NOT_FOUND);
        } catch (CodecException e) {
            callFuture.cancel(true);
            LOG.warn(e.getMessage());
            httpResponse.setStatus(HttpStatus.SC_BAD_REQUEST);
            callFuture.cancel(true);
        } catch (DeserilizeNullException e) {
            callFuture.cancel(true);
            LOG.warn(e.getMessage());
            httpResponse.setStatus(HttpStatus.SC_BAD_REQUEST);
        } catch (MethodNotFoundException e) {
            callFuture.cancel(true);
            LOG.warn(e.getMessage());
            httpResponse.setStatus(HttpStatus.SC_NOT_FOUND);
        } catch (ServerErrorException e) {
            callFuture.cancel(true);
            LOG.warn(e.getMessage());
            httpResponse.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        } catch (Exception e) {
            callFuture.cancel(true);
            LOG.error(e.getMessage(), e);
            httpResponse.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        } finally {
            try {
                buildHttpResponse(httpResponse, callFuture.get(), httpRequest.getContentType(),
                        httpRequest.getCharacterEncoding());
            } catch (InterruptedException e2) {
                LOG.error(e2.getMessage(), e2);
            }
            LocalContext.removeContext();
        }
    }
468894
@Override
	protected WebResponse newWebResponse(final WebRequest webRequest,
		final HttpServletResponse httpServletResponse)
	{
		return new ServletWebResponse((ServletWebRequest)webRequest, httpServletResponse)
		{

			@Override
			public String encodeRedirectURL(final CharSequence url)
			{
				return isRobot(webRequest) ? url.toString() : super.encodeRedirectURL(url);
			}

			@Override
			public String encodeURL(final CharSequence url)
			{
				return isRobot(webRequest) ? url.toString() : super.encodeURL(url);
			}

			private boolean isRobot(final WebRequest request)
			{
				final String agent = webRequest.getHeader("User-Agent");
				return BotAgentInspector.isAgent(agent);
			}
		};
	}