Create a support class to coordinate the web request.

@param httpServletRequest the request being processed
@param httpServletResponse the servlet response

@return the servlet helper
516557
protected WServletHelper createServletHelper(final HttpServletRequest httpServletRequest,
			final HttpServletResponse httpServletResponse) {
		LOG.debug("Creating a new WServletHelper instance");
		WServletHelper helper = new WServletHelper(this, httpServletRequest, httpServletResponse);
		return helper;
	}
589740
private HttpHandler validate(final HttpServletRequest request,
                               final HttpServletResponse response,
                               final ParsedHttpRequest parsedHttpRequest) throws IOException, ServletException {
    final String specification = parsedHttpRequest.getTargetSpecification();
    final String version = parsedHttpRequest.getVersion();

    if (specification == null) {
      writeMessage(response, "Specification is not provided in the request.", HttpServletResponse.SC_BAD_REQUEST);
      return null;
    }

    final HttpHandler handler = eventHandlers.get(specification.toLowerCase());
    if (handler == null) {
      writeMessage(response, String.format("No event handler registered for: [%s].", specification),
          HttpServletResponse.SC_NOT_FOUND);
      return null;
    }

    if (version == null) {
      writeMessage(response, "Version is not provided in the request.", HttpServletResponse.SC_BAD_REQUEST);
      return null;
    }
    return handler;
  }
1222227
@Nonnull
  public static UnifiedResponse createSimple (@Nonnull final HttpServletRequest aHttpRequest)
  {
    return new UnifiedResponse (RequestHelper.getHttpVersion (aHttpRequest),
                                RequestHelper.getHttpMethod (aHttpRequest),
                                aHttpRequest);
  }
236013
private static AnnotatedHttpServiceElement create(String pathPrefix, Object object, Method method,
                                                      List<ExceptionHandlerFunction> baseExceptionHandlers,
                                                      List<RequestConverterFunction> baseRequestConverters,
                                                      List<ResponseConverterFunction> baseResponseConverters) {

        final Set<Annotation> methodAnnotations = httpMethodAnnotations(method);
        if (methodAnnotations.isEmpty()) {
            throw new IllegalArgumentException("HTTP Method specification is missing: " + method.getName());
        }

        final Set<HttpMethod> methods = toHttpMethods(methodAnnotations);
        if (methods.isEmpty()) {
            throw new IllegalArgumentException(method.getDeclaringClass().getName() + '#' + method.getName() +
                                               " must have an HTTP method annotation.");
        }

        final Class<?> clazz = object.getClass();
        final PathMapping pathMapping = pathStringMapping(pathPrefix, method, methodAnnotations)
                .withHttpHeaderInfo(methods, consumableMediaTypes(method, clazz),
                                    producibleMediaTypes(method, clazz));

        final List<ExceptionHandlerFunction> eh =
                getAnnotatedInstances(method, clazz, ExceptionHandler.class, ExceptionHandlerFunction.class)
                        .addAll(baseExceptionHandlers).add(defaultExceptionHandler).build();
        final List<RequestConverterFunction> req =
                getAnnotatedInstances(method, clazz, RequestConverter.class, RequestConverterFunction.class)
                        .addAll(baseRequestConverters).build();
        final List<ResponseConverterFunction> res =
                getAnnotatedInstances(method, clazz, ResponseConverter.class, ResponseConverterFunction.class)
                        .addAll(baseResponseConverters).build();

        List<AnnotatedValueResolver> resolvers;
        try {
            resolvers = AnnotatedValueResolver.ofServiceMethod(method, pathMapping.paramNames(),
                                                               toRequestObjectResolvers(req));
        } catch (NoParameterException ignored) {
            // Allow no parameter like below:
            //
            // @Get("/")
            // public String method1() { ... }
            //
            resolvers = ImmutableList.of();
        }

        final Set<String> expectedParamNames = pathMapping.paramNames();
        final Set<String> requiredParamNames =
                resolvers.stream()
                         .filter(AnnotatedValueResolver::isPathVariable)
                         .map(AnnotatedValueResolver::httpElementName)
                         .collect(Collectors.toSet());

        if (!expectedParamNames.containsAll(requiredParamNames)) {
            final Set<String> missing = Sets.difference(requiredParamNames, expectedParamNames);
            throw new IllegalArgumentException("cannot find path variables: " + missing);
        }

        // Warn unused path variables only if there's no '@RequestObject' annotation.
        if (resolvers.stream().noneMatch(r -> r.annotationType() == RequestObject.class) &&
            !requiredParamNames.containsAll(expectedParamNames)) {
            final Set<String> missing = Sets.difference(expectedParamNames, requiredParamNames);
            logger.warn("Some path variables of the method '" + method.getName() +
                        "' of the class '" + clazz.getName() +
                        "' do not have their corresponding parameters annotated with @Param. " +
                        "They would not be automatically injected: " + missing);
        }

        final Optional<HttpStatus> defaultResponseStatus = findFirst(method, StatusCode.class)
                .map(code -> {
                    final int statusCode = code.value();
                    checkArgument(statusCode >= 0,
                                  "invalid HTTP status code: %s (expected: >= 0)", statusCode);
                    return HttpStatus.valueOf(statusCode);
                });
        final HttpHeaders defaultHeaders = HttpHeaders.of(defaultResponseStatus(defaultResponseStatus, method));

        final HttpHeaders defaultTrailingHeaders = HttpHeaders.of();
        final String classAlias = clazz.getName();
        final String methodAlias = String.format("%s.%s()", classAlias, method.getName());
        setAdditionalHeader(defaultHeaders, clazz, "header", classAlias, "class", AdditionalHeader.class,
                            AdditionalHeader::name, AdditionalHeader::value);
        setAdditionalHeader(defaultHeaders, method, "header", methodAlias, "method", AdditionalHeader.class,
                            AdditionalHeader::name, AdditionalHeader::value);
        setAdditionalHeader(defaultTrailingHeaders, clazz, "trailer", classAlias, "class",
                            AdditionalTrailer.class, AdditionalTrailer::name, AdditionalTrailer::value);
        setAdditionalHeader(defaultTrailingHeaders, method, "trailer", methodAlias, "method",
                            AdditionalTrailer.class, AdditionalTrailer::name, AdditionalTrailer::value);

        if (ArmeriaHttpUtil.isContentAlwaysEmpty(defaultHeaders.status()) &&
            !defaultTrailingHeaders.isEmpty()) {
            logger.warn("A response with HTTP status code '{}' cannot have a content. " +
                        "Trailing headers defined at '{}' might be ignored.",
                        defaultHeaders.status().code(), methodAlias);
        }

        // A CORS preflight request can be received because we handle it specially. The following
        // decorator will prevent the service from an unexpected request which has OPTIONS method.
        final Function<Service<HttpRequest, HttpResponse>,
                ? extends Service<HttpRequest, HttpResponse>> initialDecorator;
        if (methods.contains(HttpMethod.OPTIONS)) {
            initialDecorator = Function.identity();
        } else {
            initialDecorator = delegate -> new SimpleDecoratingService<HttpRequest, HttpResponse>(delegate) {
                @Override
                public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exception {
                    if (req.method() == HttpMethod.OPTIONS) {
                        // This must be a CORS preflight request.
                        throw HttpStatusException.of(HttpStatus.FORBIDDEN);
                    }
                    return delegate().serve(ctx, req);
                }
            };
        }
        return new AnnotatedHttpServiceElement(pathMapping,
                                               new AnnotatedHttpService(object, method, resolvers, eh,
                                                                        res, pathMapping, defaultHeaders,
                                                                        defaultTrailingHeaders),
                                               decorator(method, clazz, initialDecorator));
    }
1324363
public synchronized void create( HttpServletRequest request,
                                     HttpServletResponse response,
                                     ServletContext servletContext )
    {
        PerRequestState prevState = setPerRequestState( new PerRequestState( request, response, null ) );

        try
        {
            try
            {
                // we start the context on the bean so user control can run against Controls in the onCreate() method
                super.create( request, response, servletContext );
            }
            catch ( Throwable th )
            {
                try
                {
                    _log.info( "Handling exception in onCreate(), FlowController " + this, th );
                    reinitialize(request, response, servletContext);
                    ActionForward fwd = handleException( th, null, null, request, response );
                    if ( fwd == null ) fwd = NULL_ACTION_FORWARD;
                    request.setAttribute( ONCREATE_EXCEPTION_FORWARD, fwd );
                }
                catch ( Exception e )
                {
                    _log.error( "Exception thrown while handling exception in onCreate(): " + e.getMessage(), th );
                }
            }
        }
        finally
        {
            if(prevState != null)
                setPerRequestState( prevState );

            PageFlowControlContainer pfcc = PageFlowControlContainerFactory.getControlContainer(request,getServletContext());
            pfcc.endContextOnPageFlow(this);
        }

        PageFlowEventReporter er = AdapterManager.getServletContainerAdapter( servletContext ).getEventReporter();
        RequestContext requestContext = new RequestContext( request, response );
        er.flowControllerCreated( requestContext, this );
    }
177014
public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String requestedPath = (StringUtils.isEmpty(mapping)) ? helper
				.getPathWithinApplication(request) : helper
				.getPathWithinServletMapping(request);

		if (StringUtils.isNotEmpty(controllerMapping)) {
			requestedPath = requestedPath.substring(controllerMapping.length());
		}

		requestHandler.processRequest(requestedPath, request, response);
		return null;
	}
1136829
private final static HttpServletRequest createServletRequest(final HttpServletRequest req, final String translatedPath) {
        return new HttpServletRequestWrapper(req){
            @Override
            public String getServletPath() {
                return translatedPath;
            }
        };
    }
245182
protected Response doRequest(HttpRequestBase request, String authorizationToken, Class<?> successResponseClass) {

		assertValid(authorizationToken, "An authorizationToken is required for web resource call");

		CloseableHttpClient httpclient = HttpClients.createDefault();
		request.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
		request.setHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
		request.setHeader("Authorization", "Token " + authorizationToken);
		
		try {
			CloseableHttpResponse clientResponse = httpclient.execute(request);
		
		    HttpEntity entity = clientResponse.getEntity();

		    InputStream inputStream = entity.getContent();

		    StringWriter writer = new StringWriter();
		    IOUtils.copy(inputStream, writer, "UTF-8");
		    String json = writer.toString();
		    
		    LOG.debug("json: " + json);
		    
			Response response = (Response) OBJECT_MAPPER.readValue(json, successResponseClass);

			LOG.debug("response.statuscode: " + response.status_code);
			
			if (!StatusCode.SUCCESS.equals(response.status_code)) {

				throw new RuntimeException(response.toString());
			}

			Header totalCount = clientResponse.getFirstHeader("X-Total-Count");
			if (totalCount != null) {
				response.totalCount = Integer.valueOf(totalCount.getValue());
			}
		    EntityUtils.consume(entity);
			clientResponse.close();
		    
			LOG.debug("Response: " + response);
		    
			return response;

		} catch (ClientProtocolException e) {
			throw new RuntimeException(e);
		} catch (JsonParseException e) {
			throw new RuntimeException(e);
		} catch (JsonMappingException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
269731
protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		try {
			jawrController.handleRequest(request, response);
		} catch (Exception e) {
			if (logger.isDebugEnabled()) {
				logger.debug("Error in JawrSpringController", e);
			}
			throw new ServletException(e);
		}
	}
236749
public HttpServletResponse getResponse()
    {
    	// moved as part of 	LIDB-3598 to ServletUtil
    	/*
        ServletResponse r = _resp;

        while (!(r instanceof HttpServletResponse))
        {
            if (r instanceof ServletResponseWrapper)
            {
                r = ((ServletResponseWrapper) r).getResponse();
            }
        }
			    
        return (HttpServletResponse) r;
        */
    	//begin 311003, 61FVT:Simple SIP request generating exception
    	ServletResponse sRes = null;
		if (_resp==null)
    		return null;
    	try {
    		sRes = ServletUtil.unwrapResponse(_resp);
    	}
    	catch (RuntimeException re){
    		if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
    			logger.logp(Level.FINE, CLASS_NAME,"getResponse","Caught RuntimeException unwrapping the response",re);
    		return null;
    	}
    	//end 311003, 61FVT:Simple SIP request generating exception
    	if (sRes instanceof HttpServletResponse)
    		return (HttpServletResponse) sRes;
    	else
    		return null;
    }
1335538
public B annotatedService(String pathPrefix, Object service,
                              Function<Service<HttpRequest, HttpResponse>,
                                      ? extends Service<HttpRequest, HttpResponse>> decorator,
                              Iterable<?> exceptionHandlersAndConverters) {
        requireNonNull(pathPrefix, "pathPrefix");
        requireNonNull(service, "service");
        requireNonNull(decorator, "decorator");
        requireNonNull(exceptionHandlersAndConverters, "exceptionHandlersAndConverters");

        final List<AnnotatedHttpServiceElement> elements =
                AnnotatedHttpServiceFactory.find(pathPrefix, service, exceptionHandlersAndConverters);
        elements.forEach(e -> {
            Service<HttpRequest, HttpResponse> s = e.service();
            // Apply decorators which are specified in the service class.
            s = e.decorator().apply(s);
            // Apply decorators which are passed via annotatedService() methods.
            s = decorator.apply(s);

            // If there is a decorator, we should add one more decorator which handles an exception
            // raised from decorators.
            if (s != e.service()) {
                s = e.service().exceptionHandlingDecorator().apply(s);
            }
            service(e.pathMapping(), s);
        });
        return self();
    }
477008
public static ProcessRetrieveResponse checkRequestParameter(
			HttpServletRequest request, ServletContext context) {
		ProcessRetrieveResponse response = new ProcessRetrieveResponse(context);
		Integer numItems = checkNumItems(request, response);
		String term = checkTerm(request, response);
		if (term == null) {
			return response;
		}
		SuggestTree index = checkIndexName(request, response, context);
		if (index == null) {
			response.addError(RetrieveStatusCodes.NO_INDEX_AVAILABLE);
			return response;
		}
		retrieveSuggestions(request, response, index, term, numItems);
		return response;
	}
856250
@Override
    protected HTTPResponseHandler createHTTPResponseHandler()
    {
        //get property part
        String propertyPart=this.getPropertyPart();
        
        //get configuration
        Map<String,String> configuration=this.getConfiguration();

        //setup configuration
        configuration=new HashMap<String,String>(configuration);

        //modify configuration
        this.updateHTTPResponseHandlerConfiguration(configuration);

        //create handler
        HTTPResponseHandler handler=new JSONHTTPResponseHandler();
        handler.setPropertyPart(propertyPart);
        handler.initialize(configuration);
        
        return handler;
    }
359366
public static ActionResolver getCurrentActionResolver( HttpServletRequest request )
    {
        ServletContext servletContext = InternalUtils.getServletContext( request );
        return getCurrentActionResolver( request, servletContext );
    }
556701
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        String servletPath = (String) request.getAttribute(Dispatcher.__INCLUDE_SERVLET_PATH);
        String pathInfo = null;
        if (servletPath == null)
        {
            servletPath = request.getServletPath();
            pathInfo = request.getPathInfo();
        }
        else
            pathInfo = (String) request.getAttribute(Dispatcher.__INCLUDE_PATH_INFO);

        String pathInContext = URI.addPaths(servletPath, pathInfo);
                
        boolean endsWithSlash = pathInContext.endsWith("/");
        Resource resource = getResource(pathInContext);

        // Is the method allowed?
        String method = request.getMethod();
        if (_AllowString.indexOf(method) < 0)
        {
            if (resource != null && resource.exists())
            {
                response.setHeader(HttpFields.__Allow, _AllowString);
                response.sendError(HttpResponse.__405_Method_Not_Allowed);
            }
            else
                response.sendError(HttpResponse.__404_Not_Found);
            return;
        }

        // Handle the request
        try
        {
            // handle by method.
            if (method.equals(HttpRequest.__GET) || method.equals(HttpRequest.__POST) || method.equals(HttpRequest.__HEAD))
                handleGet(request, response, pathInContext, resource, endsWithSlash);
            else if (_putAllowed && method.equals(HttpRequest.__PUT))
                handlePut(request, response, pathInContext, resource);
            else if (_delAllowed && method.equals(HttpRequest.__DELETE))
                handleDelete(request, response, pathInContext, resource);
            else if (_putAllowed && _delAllowed && method.equals(HttpRequest.__MOVE))
                handleMove(request, response, pathInContext, resource);
            else if (method.equals(HttpRequest.__OPTIONS))
                handleOptions(request, response);
            else if (method.equals(HttpRequest.__TRACE))
                _servletHandler.handleTrace(request, response);
            else
            {
                // anything else...
                try
                {
                    if (resource.exists())
                        response.sendError(HttpResponse.__501_Not_Implemented);
                    else
                        _servletHandler.notFound(request, response);
                }
                catch (Exception e)
                {
                    LogSupport.ignore(log, e);
                }
            }
        }
        catch (IllegalArgumentException e)
        {
            LogSupport.ignore(log, e);
        }
        finally
        {
            if (resource != null && !(resource instanceof CachedResource))
                resource.release();
        }

    }
1091371
private HttpServletResponse getHttpServletResponseUrlEncoder(
			final Response response) {

		return new HttpServletResponse() {

			public void setLocale(Locale loc) {

			}

			public void setContentType(String type) {

			}

			public void setContentLength(int len) {

			}

			public void setBufferSize(int size) {

			}

			public void resetBuffer() {

			}

			public void reset() {

			}

			public boolean isCommitted() {
				return false;
			}

			public PrintWriter getWriter() throws IOException {
				return new PrintWriter(new RedirectWriter(getResponse()));
			}

			public ServletOutputStream getOutputStream() throws IOException {
				return null;
			}

			public Locale getLocale() {
				return null;
			}

			public int getBufferSize() {
				return 0;
			}

			public void flushBuffer() throws IOException {

			}

			public void setStatus(int sc, String sm) {

			}

			public void setStatus(int sc) {

			}

			public void setIntHeader(String name, int value) {

			}

			public void setHeader(String name, String value) {

			}

			public void setDateHeader(String name, long date) {

			}

			public void sendRedirect(String location) throws IOException {

			}

			public void sendError(int sc, String msg) throws IOException {

			}

			public void sendError(int sc) throws IOException {

			}

			public String encodeUrl(String url) {
				return response.encodeURL(url).toString();
			}

			public String encodeURL(String url) {
				return response.encodeURL(url).toString();
			}

			public String encodeRedirectUrl(String url) {
				return null;
			}

			public String encodeRedirectURL(String url) {
				return null;
			}

			public boolean containsHeader(String name) {
				return false;
			}

			public void addIntHeader(String name, int value) {

			}

			public void addHeader(String name, String value) {

			}

			public void addDateHeader(String name, long date) {

			}

			public void addCookie(Cookie cookie) {

			}

			public String getContentType() {
				return null;
			}

			public void setCharacterEncoding(String charset) {

			}

			@Override
			public String getCharacterEncoding() {
				return "UTF-8";
			}
		};
	}
1173298
public void service(HttpServletRequest req, HttpServletResponse res) 
        throws ServletException, IOException
    {
        String browser = this.getBrowser(req);
        String queryString = req.getQueryString();
        String path = req.getPathInfo();
        if (path == null)
        	path = "";
        String target = this.getProperty(browser);
        if (target == null)
            target = this.getProperty(TARGET);
        if (target == null)
            target = req.getParameter(TARGET);
        if (queryString != null)
        {
            char delimiter = '?';
            if (target.indexOf('?') != -1)
                delimiter = '&';
            target = target + delimiter + queryString;
        }

        if (logger != null)
        	logger.info("Redirect to " + target);
        String match = this.getProperty(MATCH);
        if ((target != null) && ((match == null) || path.matches(match)))
        	res.sendRedirect(target);
        else
        	super.service(req, res);
    }