/*
(non-Javadoc)

@see
org.springframework.web.servlet.mvc.Controller#handleRequest(javax.servlet
.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
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;
	}
871999
@Override
  public void handle(
      final String target,
      final HttpServletRequest request,
      final HttpServletResponse response,
      final int i)
      throws IOException, ServletException {
    LOG.log(Level.INFO, "JettyHandler handle is entered with target: {0} ", target);

    final Request baseRequest = (request instanceof Request) ? (Request) request :
        HttpConnection.getCurrentConnection().getRequest();

    response.setContentType("text/html;charset=utf-8");

    final ParsedHttpRequest parsedHttpRequest = new ParsedHttpRequest(request);
    final HttpHandler handler = validate(request, response, parsedHttpRequest);
    if (handler != null) {
      LOG.log(Level.INFO, "calling HttpHandler.onHttpRequest from JettyHandler.handle() for {0}.",
          handler.getUriSpecification());
      handler.onHttpRequest(parsedHttpRequest, response);
      response.setStatus(HttpServletResponse.SC_OK);
    }

    baseRequest.setHandled(true);
    LOG.log(Level.INFO, "JettyHandler handle exists");
  }
1299500
public void handle(String pathInContext,
                       String pathParams,
                       HttpRequest request,
                       HttpResponse response)
        throws HttpException, IOException
    {
        Resource resource = getResource(pathInContext);
        if (resource==null)
            return;

        // Is the method allowed?
        if (!isMethodAllowed(request.getMethod()))
        {
            if(log.isDebugEnabled())log.debug("Method not allowed: "+request.getMethod());
            if (resource.exists())
            {
                setAllowHeader(response);
                response.sendError(HttpResponse.__405_Method_Not_Allowed);
            }
            return;
        }

        // Handle the request
        try
        {
            if(log.isDebugEnabled())log.debug("PATH="+pathInContext+" RESOURCE="+resource);
            
            // check filename
            String method=request.getMethod();
            if (method.equals(HttpRequest.__GET) ||
                method.equals(HttpRequest.__POST) ||
                method.equals(HttpRequest.__HEAD))
                handleGet(request, response, pathInContext, pathParams, resource);  
            else if (method.equals(HttpRequest.__PUT))
                handlePut(request, response, pathInContext, resource);
            else if (method.equals(HttpRequest.__DELETE))
                handleDelete(request, response, pathInContext, resource);
            else if (method.equals(HttpRequest.__OPTIONS))
                handleOptions(response, pathInContext);
            else if (method.equals(HttpRequest.__MOVE))
                handleMove(request, response, pathInContext, resource);
            else if (method.equals(HttpRequest.__TRACE))
                handleTrace(request, response);
            else
            {
                if(log.isDebugEnabled())log.debug("Unknown action:"+method);
                // anything else...
                try{
                    if (resource.exists())
                        response.sendError(HttpResponse.__501_Not_Implemented);
                }
                catch(Exception e) {LogSupport.ignore(log,e);}
            }
        }
        catch(IllegalArgumentException e)
        {
            LogSupport.ignore(log,e);
        }
        finally
        {
            if (resource!=null && !(resource instanceof CachedResource))
                resource.release();
        }
    }
417368
private void handleSortRequest(final Request request) {
		String sortColStr = request.getParameter(getId() + ".sort");
		String sortDescStr = request.getParameter(getId() + ".sortDesc");

		if (sortColStr != null) {
			if ("".equals(sortColStr)) {
				// Reset sort
				setSort(-1, false);
				getOrCreateComponentModel().rowIndexMapping = null;
			} else {
				try {
					int sortCol = Integer.parseInt(sortColStr);
					// Allow for column order
					int[] cols = getColumnOrder();
					if (cols != null) {
						sortCol = cols[sortCol];
					}
					boolean sortAsc = !"true".equalsIgnoreCase(sortDescStr);

					// Only process the sort request if it differs from the current sort order
					if (sortCol != getSortColumnIndex() || sortAsc != isSortAscending()) {
						sort(sortCol, sortAsc);
						setFocussed();
					}
				} catch (NumberFormatException e) {
					LOG.warn("Invalid sort column: " + sortColStr);
				}
			}
		}
	}
948453
private static String getHandler(HttpServletRequest request) {
    String pathInfo = request.getPathInfo();
    return pathInfo == null ? "" : pathInfo.substring(1);
  }
210159
protected <T, A> void handleRequest(final Channel channel, final DataInput message, final ManagementProtocolHeader header, ActiveRequest<T, A> activeRequest) {
        handleMessage(channel, message, header, activeRequest.context, activeRequest.handler);
    }
732708
@Override
	public void handleRequest(final Request request) {
		// Clear pressed
		clearPressed();

		String requestValue = request.getParameter(getId());
		boolean pressed = "x".equals(requestValue);

		// Only process on a POST
		if (pressed && !"POST".equals(request.getMethod())) {
			LOG.warn("Button pressed on a request that is not a POST. Will be ignored.");
			return;
		}

		setPressed(pressed, request);
	}
653062
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
		// Stop controller stopwatch
		stopStopwatch();

		HandlerLocation location = threadLocation.get();
		location.setStep(HandlerStep.VIEW);

		// Start view stopwatch
		startStopwatch(location);
	}
585012
private void handleRequestAndRespond(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        RDFUnitConfiguration configuration = null;
        try {
            configuration = getConfiguration(httpServletRequest);
        } catch (ParameterException e) {
            String message = e.getMessage();
            if (message != null) {
                printMessage(httpServletResponse, message);
            }
            printHelpMessage(httpServletResponse);
            httpServletResponse.getWriter().close();
            return;
        }
        assert configuration != null;

        final TestSource dataset = configuration.getTestSource();

        final TestSuite testSuite = getTestSuite(configuration, dataset);
        assert testSuite != null;

        TestExecution results = null;
        try {
            results = validate(configuration, dataset, testSuite);
        } catch (TestCaseExecutionException e) {
            // TODO catch error
        }
        assert results != null;

        try {
            writeResults(configuration, results, httpServletResponse);
        } catch (RdfWriterException e) {
            printMessage(httpServletResponse, e.getMessage());
        }
    }
930766
@Override
    public RequestCtx handleRequest(HttpServletRequest request,
                                    HttpServletResponse response)
            throws IOException, ServletException {
        if (logger.isDebugEnabled()) {
            logger.debug("{}/handleRequest!", this.getClass().getName());
        }

        String asOfDateTime = request.getParameter("asOfDateTime");
        if (!isDate(asOfDateTime)) {
            asOfDateTime = null;
        }

        RequestCtx req = null;
        Map<URI, AttributeValue> actions = new HashMap<URI, AttributeValue>();
        Map<URI, AttributeValue> resAttr;
        try {
            String[] parts = getPathParts(request);
            resAttr = ResourceAttributes.getResources(parts);
            if (asOfDateTime != null && !asOfDateTime.isEmpty()) {
                resAttr.put(Constants.DATASTREAM.AS_OF_DATETIME.getURI(),
                            DateTimeAttribute.getInstance(asOfDateTime));
            }

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

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

            String pid = resAttr.get(Constants.OBJECT.PID.getURI()).toString();
            LogUtil.statLog(request.getRemoteUser(),
                            Constants.ACTION.LIST_DATASTREAMS.uri,
                            pid,
                            null);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServletException(e.getMessage(), e);
        }

        return req;
    }
1213450
@Override
	public void handleRequest(final Request request) {
		if (!isDisabled()) {
			final SelectToggleModel model = getComponentModel();
			String requestParam = request.getParameter(getId());

			final State newValue;
			if ("all".equals(requestParam)) {
				newValue = State.ALL;
			} else if ("none".equals(requestParam)) {
				newValue = State.NONE;
			} else if ("some".equals(requestParam)) {
				newValue = State.SOME;
			} else {
				newValue = model.state;
			}

			if (!newValue.equals(model.state)) {
				setState(newValue);
			}
			if (!model.clientSide && model.target != null && !State.SOME.equals(newValue)) {
				// We need to change the selections *after* all components
				// Have updated themselves from the request, as they may change
				// their values when their handleRequest methods are called.
				invokeLater(new Runnable() {
					@Override
					public void run() {
						setSelections(model.target, State.ALL.equals(newValue));
					}
				});
			}
		}
	}
256800
@Override
	public void handleRequest(final Request request) {
		if (isDisabled()) {
			// Protect against client-side tampering of disabled/read-only fields.
			return;
		}

		if (isMenuPresent(request)) {
			String requestValue = request.getParameter(getId());

			if (requestValue != null) {
				// Only process on a POST
				if (!"POST".equals(request.getMethod())) {
					LOG.warn("Menu item on a request that is not a POST. Will be ignored.");
					return;
				}

				// Execute associated action, if set
				final Action action = getAction();

				if (action != null) {
					final ActionEvent event = new ActionEvent(this, this.getActionCommand(), this.
							getActionObject());

					Runnable later = new Runnable() {
						@Override
						public void run() {
							action.execute(event);
						}
					};

					invokeLater(later);
				}
			}
		}
	}
801459
private ServletRequestHandler newPostHttpRequestHandler() {
        return new ServletRequestHandler() {
            /** {@inheritDoc} */
             public JSONAware handleRequest(HttpServletRequest pReq, HttpServletResponse pResp)
                    throws IOException {
                 String encoding = pReq.getCharacterEncoding();
                 InputStream is = pReq.getInputStream();
                 return requestHandler.handlePostRequest(pReq.getRequestURI(),is, encoding, getParameterMap(pReq));
             }
        };
    }
1318430
@RequestMapping(
            headers = {"org.apereo.portal.url.UrlType=ACTION"},
            method = RequestMethod.POST)
    public void actionRequest(HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        final IPortalRequestInfo portalRequestInfo =
                this.urlSyntaxProvider.getPortalRequestInfo(request);
        final IPortletRequestInfo portletRequestInfo =
                portalRequestInfo.getTargetedPortletRequestInfo();

        final IPortalUrlBuilder actionRedirectUrl;
        if (portletRequestInfo != null) {
            final IPortletWindowId targetWindowId = portletRequestInfo.getPortletWindowId();
            actionRedirectUrl =
                    this.portalUrlProvider.getPortalUrlBuilderByPortletWindow(
                            request, targetWindowId, UrlType.RENDER);
        } else {
            final String targetedLayoutNodeId = portalRequestInfo.getTargetedLayoutNodeId();

            if (targetedLayoutNodeId != null) {
                actionRedirectUrl =
                        this.portalUrlProvider.getPortalUrlBuilderByLayoutNode(
                                request, targetedLayoutNodeId, UrlType.RENDER);
            } else {
                actionRedirectUrl = this.portalUrlProvider.getDefaultUrl(request);
            }
        }

        // Stuff the action-redirect URL builder into the request so other code can use it during
        // request processing
        this.portalUrlProvider.convertToPortalActionUrlBuilder(request, actionRedirectUrl);

        if (portletRequestInfo != null) {
            final IPortletWindowId targetWindowId = portletRequestInfo.getPortletWindowId();

            try {
                this.portletExecutionManager.doPortletAction(targetWindowId, request, response);
            } catch (RuntimeException e) {
                this.logger.error(
                        "Exception thrown while executing portlet action for: "
                                + portletRequestInfo,
                        e);

                // TODO this should be a constant right?
                actionRedirectUrl.setParameter("portletActionError", targetWindowId.toString());
            }
        }

        sendRedirect(actionRedirectUrl, response);
    }
760174
protected static boolean handle(ServletRequest req, ServletResponse res) {
		return handler.handle((HttpServletRequest)req, (HttpServletResponse)res);
	}
1060783
private void handleRequest(
		ChainWriter out,
		WebSiteRequest req,
		HttpServletResponse resp,
		List<? extends TreePageData> tree,
		int scrollToX,
		int scrollToY,
		boolean[] opened
	) throws IOException, SQLException {
		WebPageLayout layout=getWebPageLayout(req);
		layout.startContent(out, req, resp, 1, getPreferredContentWidth(req));
		layout.printContentTitle(out, req, resp, this, 1);
		layout.printContentHorizontalDivider(out, req, resp, 1, false);
		layout.startContentLine(out, req, resp, 1, null, null);
		try {
			// Get the tree data
			int treeLen = tree.size();

			// Break apart each line
			String[][] paths = getLines(tree);

			if (opened == null) {
				// Default to opened for first item
				opened = new boolean[treeLen];
				if (treeLen > 0) opened[0] = true;
			}

			// Write the javascript that controls the form
			out.print("<script type='text/javascript'>\n"
					+ "  // <![CDATA[\n"
					+ "  function openNode(index) {\n"
					+ "    eval('document.forms[\"tree_form\"].opened_'+index+'.value=\"true\";');\n"
					+ "    document.forms[\"tree_form\"].scroll_to_x.value=getPageXOffset(window);\n"
					+ "    document.forms[\"tree_form\"].scroll_to_y.value=getPageYOffset(window);\n"
					+ "    document.forms[\"tree_form\"].submit();\n"
					+ "  }\n"
					+ "\n"
					+ "  function closeNode(index) {\n"
					+ "    eval('document.forms[\"tree_form\"].opened_'+index+'.value=\"false\";');\n"
					+ "    document.forms[\"tree_form\"].scroll_to_x.value=getPageXOffset(window);\n"
					+ "    document.forms[\"tree_form\"].scroll_to_y.value=getPageYOffset(window);\n"
					+ "    document.forms[\"tree_form\"].submit();\n"
					+ "  }\n"
					+ "  // ]]>\n"
					+ "</script>\n");

			// Write the form containing the current settings
			out.print("<form action='' id='tree_form' method='post'><div>\n");
			req.printFormFields(out, 1);
			out.print("  <input type='hidden' name='scroll_to_x' value='").print(scrollToX).print("' />\n"
					+ "  <input type='hidden' name='scroll_to_y' value='").print(scrollToY).print("' />\n");
			for(int c=0; c<treeLen; c++) {
				out.print("  <input type='hidden' name='opened_").print(c).print("' value='").print(opened[c]).print("' />\n");
			}

			// Display the tree in a table with links for opening/closing the different parts
			out.print("  <table cellspacing='0' cellpadding='0'>\n");

			String[] last = AoArrays.EMPTY_STRING_ARRAY;
			for (int c = 0; c < treeLen; c++) {
				String[] path = paths[c];
				int pathLen = path.length;

				// Every parent must be open for this to be visible
				boolean visible = true;
				Loop2 :
					for (int d = 0; d < (pathLen - 1); d++) {
						// Find the first row that has all the path up to current step
						for (int e = 0; e < c; e++) {
							String[] parentpath = paths[e];
							if (parentpath.length > d) {
								boolean isParent = true;
								for (int f = 0; f <= d; f++) {
									if (!parentpath[f].equals(path[f])) {
										isParent = false;
										break;
									}
								}
								if (isParent) {
									if (!opened[e]) {
										visible = false;
										break Loop2;
									}
									break;
								}
							}
						}
					}
					if (visible) {
						out.print("    <tr>\n"
								+ "      <td style='white-space:nowrap; border:0px;'><table cellspacing='0' cellpadding='0'><tr><td style='white-space:nowrap; border:0px;'>");

						int max = Math.min(pathLen - 1, last.length);
						int pos = 0;

						// Skip the part of the path that is already displayed by the parent
						for (; pos < max; pos++) {
							if (last[pos].equals(path[pos])) {
								boolean hasMore = false;
								for (int d = c + 1; d < treeLen; d++) {
									int end = pos;
									for (int e = 0; e < end; e++) {
										if (paths[d][e].equals(path[e])) {
											if (e == (end - 1) && !paths[d][end].equals(path[end])) {
												hasMore = true;
												break;
											}
										} else break;
									}
								}
								out.print("<img src='").encodeXmlAttribute(resp.encodeURL(req.getContextPath()+req.getURL(this, "image_num="+(hasMore?1:0)))).print("' style='border:0px; display:inline; vertical-align:bottom;' width='"+IMAGE_WIDTH+"' height='"+IMAGE_HEIGHT+"' alt='' />");
							} else break;
						}

						// Display the remaining part of the path
						for(; pos < pathLen; pos++) {
							if(path[pos].length()>0) {
								// Determine has sub items
								boolean hasSub = false;
								if (c < (treeLen - 1)) {
									String[] next_path = paths[c + 1];
									if (next_path.length >= pathLen) {
										hasSub = true;
										for (int e = 0; e < pathLen; e++) {
											String tempPath=path[e];
											if(tempPath.length()>0 && !tempPath.equals(next_path[e])) {
												hasSub = false;
												break;
											}
										}
									}
								}

								// Determine if the line continues farther down
								boolean hasMore = false;
								for (int d = c; d < treeLen; d++) {
									int end = pos;
									for (int e = 0; e < end; e++) {
										if (paths[d][e].equals(path[e])) {
											if (e == (end - 1) && !paths[d][end].equals(path[end])) {
												hasMore = true;
												break;
											}
										} else break;
									}
								}

								if(hasSub) {
									out
										.print("<a href='javascript:")
										.print(opened[c] ? "closeNode(" : "openNode(")
										.print(c)
										.print(");'><img alt='").print(opened[c] ? "Close" : "Open")
										.print("' src='")
										.encodeXmlAttribute(
											resp.encodeURL(
												req.getContextPath()+req.getURL(
													this,
													"image_num="+(
														opened[c]
														? (hasMore ? 4 : (c > 0 ? 5 : 9))
														: (hasMore ? 6 : (c > 0 ? 7 : 8))
													)
												)
											)
										).print("' style='vertical-align:bottom; border:0px; display:inline;' width='"+IMAGE_WIDTH+"' height='"+IMAGE_HEIGHT+"' /></a>");
								} else {
									out
										.print("<img src='")
										.encodeXmlAttribute(
											resp.encodeURL(
												req.getContextPath()+req.getURL(
													this,
													"image_num="+(hasMore ? 2 : 3)
												)
											)
										).print("' style='vertical-align:bottom; border:0px; display:inline;' width='"+IMAGE_WIDTH+"' height='"+IMAGE_HEIGHT+"' alt='' />");
								}
								out.print("<img src='").encodeXmlAttribute(resp.encodeURL(req.getContextPath()+req.getURL(this, "image_num=0"))).print("' style='vertical-align:bottom; border:0px; display:inline;' width='4' height='"+IMAGE_HEIGHT+"' alt='' /></td><td style='white-space:nowrap'>");
							}

							boolean useCodeFont=useCodeFont(req);
							if (useCodeFont) out.print("<code>");
							String href;
							if(
								(
									(pathLen>=2 && pos==(pathLen-2) && path[pathLen-1].length()==0)
									|| (pos==(pathLen-1) && path[pathLen-1].length()>0)
								) && (href = tree.get(c).getUrl()) != null
							) {
								out.print("<a class='aoLightLink' href='").encodeXmlAttribute(resp.encodeURL(href)).print("'>").print(path[pos]).print("</a>");
							} else if(path[pos].length()>0) out.print(path[pos]);
							if(useCodeFont) out.print("</code>");
						}

						out.print("</td></tr></table></td>\n"
								+ "      <td style='white-space:nowrap; width:20px'><img src='").encodeXmlAttribute(resp.encodeURL(req.getContextPath()+req.getURL(this, "image_num=0"))).print("' style='vertical-align:bottom; border:0px; display:inline;' width='20' height='1' alt='' /></td>\n"
								+ "      <td style='white-space:nowrap'>");
						String description=tree.get(c).getDescription();
						if(description!=null) out.print(description);
						out.print("</td>\n"
								+ "    </tr>\n");
						last = path;
					}
			}

			out.print("  </table>\n"
					+ "</div></form>\n");
		} finally {
			layout.endContentLine(out, req, resp, 1, false);
			layout.endContent(this, out, req, resp, 1);
		}
	}
1060949
private ResponseEntity<?> handleRequestInternal(HttpMethod method, HttpEntity<?> requestEntity) {
        HttpMessage request = endpointConfiguration.getMessageConverter().convertInbound(requestEntity, endpointConfiguration, null);

        HttpServletRequest servletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        UrlPathHelper pathHelper = new UrlPathHelper();

        Enumeration allHeaders = servletRequest.getHeaderNames();
        for (String headerName : CollectionUtils.toArray(allHeaders, new String[] {})) {
            if (request.getHeader(headerName) == null) {
                String headerValue = servletRequest.getHeader(headerName);
                request.header(headerName, headerValue != null ? headerValue : "");
            }
        }

        if (endpointConfiguration.isHandleCookies()) {
            request.setCookies(servletRequest.getCookies());
        }

        if (endpointConfiguration.isHandleAttributeHeaders()) {
            Enumeration<String> attributeNames = servletRequest.getAttributeNames();
            while (attributeNames.hasMoreElements()) {
                String attributeName = attributeNames.nextElement();
                Object attribute = servletRequest.getAttribute(attributeName);
                request.setHeader(attributeName, attribute);
            }
        }

        request.path(pathHelper.getRequestUri(servletRequest))
                .uri(pathHelper.getRequestUri(servletRequest))
                .contextPath(pathHelper.getContextPath(servletRequest))
                .queryParams(Optional.ofNullable(pathHelper.getOriginatingQueryString(servletRequest))
                                    .map(queryString -> queryString.replaceAll("&", ","))
                                    .orElse(""))
                .version(servletRequest.getProtocol())
                .method(method);

        Message response = endpointAdapter.handleMessage(request);

        ResponseEntity<?> responseEntity;
        if (response == null) {
            responseEntity = new ResponseEntity<>(HttpStatus.valueOf(endpointConfiguration.getDefaultStatusCode()));
        } else {
            HttpMessage httpResponse;
            if (response instanceof HttpMessage) {
                httpResponse = (HttpMessage) response;
            } else {
                httpResponse = new HttpMessage(response);
            }

            if (httpResponse.getStatusCode() == null) {
                httpResponse.status(HttpStatus.valueOf(endpointConfiguration.getDefaultStatusCode()));
            }

            responseEntity = (ResponseEntity<?>) endpointConfiguration.getMessageConverter().convertOutbound(httpResponse, endpointConfiguration, null);

            if (endpointConfiguration.isHandleCookies() && httpResponse.getCookies() != null) {
                HttpServletResponse servletResponse = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
                for (Cookie cookie : httpResponse.getCookies()) {
                    servletResponse.addCookie(cookie);
                }
            }
        }
        responseCache.add(responseEntity);
        
        return responseEntity;
    }