Handles the incoming request

@param pathInContext
@param pathParams
@param request The incoming HTTP-request
@param response The outgoing HTTP-response
188882
public void handle(String pathInContext, String pathParams, HttpRequest request,
            HttpResponse response) throws HttpException, IOException
    {

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

        try
        {

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

            if (!authorized)
            {
                // The IP is NOT allowed
                response.sendError(HttpResponse.__403_Forbidden);
                request.setHandled(true);
                return;
            }
            else
            {
                // The IP is allowed
                return;
            }
        }
        catch (Exception ex)
        {
            System.out.println(ex);
            response.sendError(HttpResponse.__500_Internal_Server_Error);
            request.setHandled(true);
        }
    }
1333195
protected void handleUpload(HttpServletRequest request, HttpServletResponse response) {

        String sessionIdStr = request.getParameter(CmsUgcConstants.PARAM_SESSION_ID);
        CmsUUID sessionId = new CmsUUID(sessionIdStr);
        CmsUgcSession session = CmsUgcSessionFactory.getInstance().getSession(request, sessionId);
        session.getFormUploadHelper().processFormSubmitRequest(request);
    }
948453
private static String getHandler(HttpServletRequest request) {
    String pathInfo = request.getPathInfo();
    return pathInfo == null ? "" : pathInfo.substring(1);
  }
670254
@Override
	public void handleRequest(final Request request) {
		super.handleRequest(request);

		WComponent visibleDialog = getVisible();

		if (visibleDialog != null) {
			visibleDialog.serviceRequest(request);
		}
	}
903506
protected void customizeConnection(String pathInContext, String pathParams, HttpRequest request, Socket socket) throws IOException
    {
    }
1265209
private void addPostParams(final Request request) {
        if (body != null) {
            request.addPostParam("Body", body);
        }

        if (mediaUrl != null) {
            for (URI prop : mediaUrl) {
                request.addPostParam("MediaUrl", prop.toString());
            }
        }
    }
770635
@Override
	public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext) {
		if (backend.getConfiguration().shouldProcessContext(OutgoingResponse)) {
			final Map<String, String> filtered = backend.getConfiguration().filterDeniedParams(backend.copyToMap(), OutgoingResponse);
			responseContext.getHeaders().putSingle(TraceeConstants.TPIC_HEADER, transportSerialization.render(filtered));
		}

		backend.clear();
	}
931646
@Override
    @SuppressWarnings("deprecation")
    public RequestCtx handleRequest(HttpServletRequest request,
                                    HttpServletResponse response)
            throws IOException, ServletException {
        if (request.getPathInfo() == null) {
            logger.error("Bad request: " + request.getRequestURI());
            throw new ServletException("Bad request: "
                    + request.getRequestURI());
        }

        String[] parts = request.getPathInfo().split("/");
        if (parts.length < 2) {
            logger.warn("Not enough path components on the URI.");
            return null;
            // throw new ServletException("Not enough path components on the
            // URI.");
        }

        RequestCtx req = null;

        String pid = null;
        String dsID = null;
        String dissID = null;
        String methodName = null;
        String dateTime = null;

        if (logger.isDebugEnabled()) {
            for (String p : parts) {
                logger.debug("Parts: {}", p);
            }
        }

        Map<URI, AttributeValue> actions = new HashMap<URI, AttributeValue>();
        Map<URI, AttributeValue> resAttr;

        String logAction = null;

        // Starting assumption is that we are doing a GetObjectProfile
        pid = parts[1];
        actions.put(Constants.ACTION.ID.getURI(),
                    Constants.ACTION.GET_OBJECT_PROFILE
                            .getStringAttribute());
        logAction =
                Constants.ACTION.GET_OBJECT_PROFILE.uri;

        if (parts.length > 2) {
            if (isDate(parts[2])) {
                dateTime = parts[2];
            } else if (isDatastream(parts[2])) {
                dsID = parts[2];
                actions.clear();
                actions
                        .put(Constants.ACTION.ID.getURI(),
                             Constants.ACTION.GET_DATASTREAM_DISSEMINATION
                                     .getStringAttribute());
                actions.put(Constants.ACTION.ID.getURI(),
                            Constants.ACTION.GET_DATASTREAM
                                    .getStringAttribute());
                logAction =
                        Constants.ACTION.GET_DATASTREAM_DISSEMINATION.getURI()
                                .toASCIIString();
            } else {
                dissID = parts[2];
                actions.clear();
                actions
                        .put(Constants.ACTION.ID.getURI(),
                             Constants.ACTION.GET_DISSEMINATION
                                     .getStringAttribute());
                logAction =
                        Constants.ACTION.GET_DISSEMINATION.uri;
            }
        }

        if (parts.length > 3) {
            if (isDate(parts[3])) {
                dateTime = parts[3];
            } else {
                methodName = parts[3];
            }
        }

        if (parts.length > 4) {
            if (isDate(parts[4])) {
                dateTime = parts[4];
            }
        }

        try {
            resAttr = ResourceAttributes.getResources(pid);
            
            if (dsID != null && !dsID.isEmpty()) {
                resAttr.put(Constants.DATASTREAM.ID.getURI(),
                            new StringAttribute(dsID));
            }
            if (dissID != null && !dissID.isEmpty()) {
                resAttr.put(Constants.DISSEMINATOR.ID.getURI(),
                            new StringAttribute(dissID));
            }
            if (methodName != null && !methodName.isEmpty()) {
                resAttr.put(Constants.DISSEMINATOR.METHOD.getURI(),
                            new StringAttribute(methodName));
            }
            if (dateTime != null && !dateTime.isEmpty()) {
                resAttr.put(Constants.DATASTREAM.AS_OF_DATETIME.getURI(),
                            DateTimeAttribute.getInstance(dateTime));
            }

            actions.put(Constants.ACTION.API.getURI(),
                        Constants.ACTION.APIA.getStringAttribute());

            req =
                    getContextHandler().buildRequest(getSubjects(request),
                                                     actions,
                                                     resAttr,
                                                     getEnvironment(request));

            LogUtil.statLog(request.getRemoteUser(), logAction, pid, dsID);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServletException(e);
        }

        return req;
    }
1192485
public void doBrowse(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException
    {
        if (!common.checkGet(request, response)) return;
        User user = common.getLoggedInUser(request);
        if (user == null) {
            common.pageSoftError(response, "Can't do /browse.  Nobody is logged in.");
            return;
        }

        DbxClientV2 dbxClient = requireDbxClient(request, response, user);
        if (dbxClient == null) return;

        String path = request.getParameter("path");
        if (path == null || path.length() == 0) {
            renderFolder(response, user, dbxClient, "");
        } else {
            String pathError = DbxPathV2.findError(path);
            if (pathError != null) {
                response.sendError(400, "Invalid path: " + jq(path) + ": " + pathError);
                return;
            }
            Metadata metadata;
            try {
                metadata = dbxClient.files()
                    .getMetadata(path);
            }
            catch (GetMetadataErrorException ex) {
                if (ex.errorValue.isPath()) {
                    LookupError le = ex.errorValue.getPathValue();
                    if (le.isNotFound()) {
                        response.sendError(400, "Path doesn't exist on Dropbox: " + jq(path));
                        return;
                    }
                }
                common.handleException(response, ex, "getMetadata(" + jq(path) + ")");
                return;
            }
            catch (DbxException ex) {
                common.handleDbxException(response, user, ex, "getMetadata(" + jq(path) + ")");
                return;
            }

            path = DbxPathV2.getParent(path) + "/" + metadata.getName();
            if (metadata instanceof FolderMetadata) {
                renderFolder(response, user, dbxClient, path);
            }
            else {
                renderFile(response, path, (FileMetadata) metadata);
            }
        }
    }
349274
@Override
	public void process(Request request)
	{
		String name = getRouteName(request);

		if (name == null || name.isEmpty()) return;

		if (!ROUTE_TIMERS.containsKey(name))
		{
			ROUTE_TIMERS.putIfAbsent(name, metrics.timer(getTimerName(name)));
		}

		if (!EXCEPTION_COUNTERS_BY_ROUTE.containsKey(name))
		{
			EXCEPTION_COUNTERS_BY_ROUTE.putIfAbsent(name, metrics.counter(getExceptionCounterName(name)));
		}
	}
614943
public void handle(String pathInContext,
                       String pathParams,
                       HttpRequest httpRequest,
                       HttpResponse httpResponse)
         throws IOException
    {
        if (!isStarted())
            return;
        
        // Handle TRACE
        if (HttpRequest.__TRACE.equals(httpRequest.getMethod()))
        {
            handleTrace(httpRequest,httpResponse);
            return;
        }

        // Look for existing request/response objects (from enterScope call)
        ServletHttpRequest request = (ServletHttpRequest) httpRequest.getWrapper();
        ServletHttpResponse response = (ServletHttpResponse) httpResponse.getWrapper();
        if (request==null)
        {
            // Not in ServletHttpContext, but bumble on anyway
            request = new ServletHttpRequest(this,pathInContext,httpRequest);
            response = new ServletHttpResponse(request,httpResponse);
            httpRequest.setWrapper(request);
            httpResponse.setWrapper(response);
        }
        else
        {
            request.recycle(this,pathInContext);
            response.recycle();
        }
        
        // Look for the servlet
        Map.Entry servlet=getHolderEntry(pathInContext);
        ServletHolder servletHolder=servlet==null?null:(ServletHolder)servlet.getValue();
        if(log.isDebugEnabled())log.debug("servlet="+servlet);
            
        try
        {
            // Adjust request paths
            if (servlet!=null)
            {
                String servletPathSpec=(String)servlet.getKey(); 
                request.setServletPaths(PathMap.pathMatch(servletPathSpec,pathInContext),
                                        PathMap.pathInfo(servletPathSpec,pathInContext),
                                        servletHolder);
            }
            
            // Handle the session ID
            request.setRequestedSessionId(pathParams);
            HttpSession session=request.getSession(false);
            if (session!=null)
                ((SessionManager.Session)session).access();
            if(log.isDebugEnabled())log.debug("session="+session);
            
            // Do that funky filter and servlet thang!
            if (servletHolder!=null)
                dispatch(pathInContext,request,response,servletHolder, Dispatcher.__REQUEST);
        }
        catch(Exception e)
        {
            log.debug(LogSupport.EXCEPTION,e);
            
            Throwable th=e;
            while (th instanceof ServletException)
            {
                log.warn(LogSupport.EXCEPTION, th);
                Throwable cause=((ServletException)th).getRootCause();
                if (cause==th || cause==null)
                    break;
                th=cause;
            }
            
            if (th instanceof HttpException)
                throw (HttpException)th;
            if (th instanceof EOFException)
                throw (IOException)th;
            else if (log.isDebugEnabled() || !( th instanceof java.io.IOException))
            {
                if (_contextLog!=null)
                {
                    if (th instanceof RuntimeException) 
                        _contextLog.error(httpRequest.getURI()+": ",th);
                    else
                        _contextLog.warn(httpRequest.getURI()+": ",th);
                }
                
                if(log.isDebugEnabled())
                {
                    if (th instanceof RuntimeException) 
                        log.error(httpRequest.getURI()+": ",th);
                    else
                        log.warn(httpRequest.getURI()+": ",th);
                    log.debug(httpRequest);
                }
            }
            
            httpResponse.getHttpConnection().forceClose();
            if (!httpResponse.isCommitted())
            {
                request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION_TYPE,th.getClass());
                request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION,th);
                if (th instanceof UnavailableException)
                {
                    UnavailableException ue = (UnavailableException)th;
                    if (ue.isPermanent())
                        response.sendError(HttpResponse.__404_Not_Found,e.getMessage());
                    else
                        response.sendError(HttpResponse.__503_Service_Unavailable,e.getMessage());
                }
                else
                    response.sendError(HttpResponse.__500_Internal_Server_Error,e.getMessage());
            }
            else
                if(log.isDebugEnabled())log.debug("Response already committed for handling "+th);
        }
        catch(Error e)
        {   
            log.warn("Error for "+httpRequest.getURI(),e);
            if(log.isDebugEnabled())log.debug(httpRequest);
            
            httpResponse.getHttpConnection().forceClose();
            if (!httpResponse.isCommitted())
            {
                request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION_TYPE,e.getClass());
                request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION,e);
                response.sendError(HttpResponse.__500_Internal_Server_Error,
                                   e.getMessage());
            }
            else
                if(log.isDebugEnabled())log.debug("Response already committed for handling ",e);
        }
        finally
        {
            if (servletHolder!=null && response!=null)
            {
                response.complete();
            }
        }
    }
1265038
protected void sendData(HttpServletRequest request, HttpServletResponse response, String pathInContext, Resource resource) throws IOException
    {
        long resLength = resource.length();

        boolean include = request.getAttribute(Dispatcher.__INCLUDE_REQUEST_URI) != null;

        // Get the output stream (or writer)
        OutputStream out = null;
        try
        {
            out = response.getOutputStream();
        }
        catch (IllegalStateException e)
        {
            out = new WriterOutputStream(response.getWriter());
        }

        // see if there are any range headers
        Enumeration reqRanges = include ? null : request.getHeaders(HttpFields.__Range);

        if (reqRanges == null || !reqRanges.hasMoreElements())
        {
            // if there were no ranges, send entire entity
            Resource data = resource;
            if (!include)
            {
                // look for a gziped content.
                if (_minGzipLength > 0)
                {
                    String accept = request.getHeader(HttpFields.__AcceptEncoding);
                    if (accept != null && resLength > _minGzipLength && !pathInContext.endsWith(".gz"))
                    {
                        Resource gz = getResource(pathInContext + ".gz");
                        if (gz.exists() && accept.indexOf("gzip") >= 0 && request.getAttribute(Dispatcher.__INCLUDE_REQUEST_URI) == null)
                        {
                            response.setHeader(HttpFields.__ContentEncoding, "gzip");
                            data = gz;
                            resLength = data.length();
                        }
                    }
                }
                writeHeaders(response, resource, resLength);
            }

            data.writeTo(out, 0, resLength);
            return;
        }

        // Parse the satisfiable ranges
        List ranges = InclusiveByteRange.satisfiableRanges(reqRanges, resLength);

        // if there are no satisfiable ranges, send 416 response
        if (ranges == null || ranges.size() == 0)
        {
            writeHeaders(response, resource, resLength);
            response.setStatus(HttpResponse.__416_Requested_Range_Not_Satisfiable);
            response.setHeader(HttpFields.__ContentRange, InclusiveByteRange.to416HeaderRangeString(resLength));
            resource.writeTo(out, 0, resLength);
            return;
        }

        // if there is only a single valid range (must be satisfiable
        // since were here now), send that range with a 216 response
        if (ranges.size() == 1)
        {
            InclusiveByteRange singleSatisfiableRange = (InclusiveByteRange) ranges.get(0);
            long singleLength = singleSatisfiableRange.getSize(resLength);
            writeHeaders(response, resource, singleLength);
            response.setStatus(HttpResponse.__206_Partial_Content);
            response.setHeader(HttpFields.__ContentRange, singleSatisfiableRange.toHeaderRangeString(resLength));
            resource.writeTo(out, singleSatisfiableRange.getFirst(resLength), singleLength);
            return;
        }

        // multiple non-overlapping valid ranges cause a multipart
        // 216 response which does not require an overall
        // content-length header
        //
        writeHeaders(response, resource, -1);
        ResourceCache.ResourceMetaData metaData = _httpContext.getResourceMetaData(resource);
        String encoding = metaData.getMimeType();
        MultiPartResponse multi = new MultiPartResponse(response.getOutputStream());
        response.setStatus(HttpResponse.__206_Partial_Content);

        // If the request has a "Request-Range" header then we need to
        // send an old style multipart/x-byteranges Content-Type. This
        // keeps Netscape and acrobat happy. This is what Apache does.
        String ctp;
        if (request.getHeader(HttpFields.__RequestRange) != null)
            ctp = "multipart/x-byteranges; boundary=";
        else
            ctp = "multipart/byteranges; boundary=";
        response.setContentType(ctp + multi.getBoundary());

        InputStream in = (resource instanceof CachedResource) ? null : resource.getInputStream();
        long pos = 0;

        for (int i = 0; i < ranges.size(); i++)
        {
            InclusiveByteRange ibr = (InclusiveByteRange) ranges.get(i);
            String header = HttpFields.__ContentRange + ": " + ibr.toHeaderRangeString(resLength);
            multi.startPart(encoding, new String[]
            { header});

            long start = ibr.getFirst(resLength);
            long size = ibr.getSize(resLength);
            if (in != null)
            {
                // Handle non cached resource
                if (start < pos)
                {
                    in.close();
                    in = resource.getInputStream();
                    pos = 0;
                }
                if (pos < start)
                {
                    in.skip(start - pos);
                    pos = start;
                }
                IO.copy(in, out, size);
                pos += size;
            }
            else
                // Handle cached resource
                (resource).writeTo(out, start, size);

        }
        if (in != null)
            in.close();
        multi.close();

        return;
    }
913608
void handlePut(HttpRequest request,
                   HttpResponse response,
                   String pathInContext,
                   Resource resource)
        throws IOException
    {
        if(log.isDebugEnabled())log.debug("PUT "+pathInContext+" in "+resource);

        boolean exists=resource!=null && resource.exists();
        if (exists &&
            !passConditionalHeaders(request,response,resource))
            return;
        
        if (pathInContext.endsWith("/"))
        {
            if (!exists)
            {
                if (!resource.getFile().mkdirs())
                    response.sendError(HttpResponse.__403_Forbidden, "Directories could not be created");
                else
                {
                    request.setHandled(true);
                    response.setStatus(HttpResponse.__201_Created);
                    response.commit();
                }
            }
            else
            {
                request.setHandled(true);
                response.setStatus(HttpResponse.__200_OK);
                response.commit();
            }
        }
        else
        {
            try
            {
                int toRead = request.getContentLength();
                InputStream in = request.getInputStream();
                OutputStream out = resource.getOutputStream();
                if (toRead>=0)
                    IO.copy(in,out,toRead);
                else
                    IO.copy(in,out);
                out.close();
                request.setHandled(true);
                response.setStatus(exists
                                   ?HttpResponse.__200_OK
                                   :HttpResponse.__201_Created);
                response.commit();
            }
            catch (Exception ex)
            {
                log.warn(LogSupport.EXCEPTION,ex);
                response.sendError(HttpResponse.__403_Forbidden,
                                   ex.getMessage());
            }
        }
    }
484069
public void handle(String pathInContext, String pathParams, HttpRequest httpRequest, HttpResponse httpResponse)
        throws HttpException, IOException
    {
        if (!isStarted())
            return;
        try
        {
            super.handle(pathInContext, pathParams, httpRequest, httpResponse);
        }
        finally
        {
            if (!httpRequest.isHandled())
                httpResponse.sendError(HttpResponse.__404_Not_Found);
            httpRequest.setHandled(true);
            if (!httpResponse.isCommitted())
            {
                httpResponse.completing();
                httpResponse.commit();
            }
        }
    }
1268677
void handleOptions(HttpResponse response, String pathInContext)
        throws IOException
    {
        if ("*".equals(pathInContext))
            return;
        setAllowHeader(response);
        response.commit();
    }
1164190
public void handleMove(HttpServletRequest request, HttpServletResponse response, String pathInContext, Resource resource) throws ServletException, IOException
    {
        if (!resource.exists() || !passConditionalHeaders(request, response, resource))
            return;

        String newPath = URI.canonicalPath(request.getHeader("new-uri"));
        if (newPath == null)
        {
            response.sendError(HttpResponse.__400_Bad_Request, "No new-uri");
            return;
        }

        String contextPath = _httpContext.getContextPath();
        if (contextPath != null && !newPath.startsWith(contextPath))
        {
            response.sendError(HttpResponse.__405_Method_Not_Allowed, "Not in context");
            return;
        }

        try
        {
            String newInfo = newPath;
            if (contextPath != null)
                newInfo = newInfo.substring(contextPath.length());
            Resource newFile = _httpContext.getBaseResource().addPath(newInfo);

            resource.renameTo(newFile);
            response.setStatus(HttpResponse.__204_No_Content);
            response.flushBuffer();
        }
        catch (Exception ex)
        {
            log.warn(LogSupport.EXCEPTION, ex);
            response.sendError(HttpResponse.__500_Internal_Server_Error, "Error:" + ex);
            return;
        }

    }
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;
	}