@Override protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { UrlPathHelper helper = new UrlPathHelper(); String suffix = helper.getPathWithinApplication(request); StopWatch stopWatch = new StopWatch(); stopWatch.start(); try { chain.doFilter(request, response); } finally { stopWatch.stop(); int status = getStatus(response); Object bestMatchingPattern = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); HttpStatus httpStatus = HttpStatus.OK; try { httpStatus = HttpStatus.valueOf(status); } catch (Exception ex) { // not convertible } if (bestMatchingPattern != null) { suffix = bestMatchingPattern.toString().replaceAll("[{}]", "-"); } else if (httpStatus.is4xxClientError()) { suffix = UNKNOWN_PATH_SUFFIX; } String gaugeKey = getKey("response" + suffix); MetricFilterAutoConfiguration.this.gaugeService.submit( gaugeKey, stopWatch.getTotalTimeMillis()); String counterKey = getKey("status." + status + suffix); MetricFilterAutoConfiguration.this.counterService.increment(counterKey); } }
/** * Handles requests with message handler implementation. Previously sets Http request method as * header parameter. * * @param method * @param requestEntity * @return */ private ResponseEntity<String> handleRequestInternal( HttpMethod method, HttpEntity<String> requestEntity) { Map<String, ?> httpRequestHeaders = headerMapper.toHeaders(requestEntity.getHeaders()); Map<String, String> customHeaders = new HashMap<String, String>(); for (Entry<String, List<String>> header : requestEntity.getHeaders().entrySet()) { if (!httpRequestHeaders.containsKey(header.getKey())) { customHeaders.put( header.getKey(), StringUtils.collectionToCommaDelimitedString(header.getValue())); } } HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); UrlPathHelper pathHelper = new UrlPathHelper(); customHeaders.put(CitrusHttpMessageHeaders.HTTP_REQUEST_URI, pathHelper.getRequestUri(request)); customHeaders.put( CitrusHttpMessageHeaders.HTTP_CONTEXT_PATH, pathHelper.getContextPath(request)); String queryParams = pathHelper.getOriginatingQueryString(request); customHeaders.put( CitrusHttpMessageHeaders.HTTP_QUERY_PARAMS, queryParams != null ? queryParams : ""); customHeaders.put(CitrusHttpMessageHeaders.HTTP_REQUEST_METHOD, method.toString()); Message<?> response = messageHandler.handleMessage( MessageBuilder.withPayload(requestEntity.getBody()) .copyHeaders(convertHeaderTypes(httpRequestHeaders)) .copyHeaders(customHeaders) .build()); return generateResponse(response); }
private void setDefaultConfiguredEncoding( HttpServletRequest request, GrailsContentBufferingResponse contentBufferingResponse) { UrlPathHelper urlHelper = new UrlPathHelper(); String requestURI = urlHelper.getOriginatingRequestUri(request); // static content? if (requestURI.endsWith(HTML_EXT)) { contentBufferingResponse.setContentType("text/html;charset=" + defaultEncoding); } }
/** * 获得当的访问路径 * * <p>HttpServletRequest.getRequestURL+"?"+HttpServletRequest.getQueryString * * @param request * @return */ public static String getLocation(HttpServletRequest request) { UrlPathHelper helper = new UrlPathHelper(); StringBuffer buff = request.getRequestURL(); String uri = request.getRequestURI(); String origUri = helper.getOriginatingRequestUri(request); buff.replace(buff.length() - uri.length(), buff.length(), origUri); String queryString = helper.getOriginatingQueryString(request); if (queryString != null) { buff.append("?").append(queryString); } return buff.toString(); }
/* * (non-Javadoc) * * @see * org.springframework.web.servlet.mvc.Controller#handleRequest(javax.servlet * .http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ 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; }
/** * @deprecated Use {@link * org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest#getContextPath() instead} * @param request The Servlet Reqest * @return The Application URI */ @Deprecated public String getApplicationUri(ServletRequest request) { String appUri = (String) request.getAttribute(GrailsApplicationAttributes.APP_URI_ATTRIBUTE); if (appUri == null) { appUri = urlHelper.getContextPath((HttpServletRequest) request); } return appUri; }
/** * Returns the context path of the request. * * @return the path */ @Override public String getContextPath() { final HttpServletRequest request = getCurrentRequest(); String appUri = (String) request.getAttribute(GrailsApplicationAttributes.APP_URI_ATTRIBUTE); if (appUri == null) { appUri = urlHelper.getContextPath(request); } return appUri; }
private void prepareLinkPrefix(HttpServletRequest request) { StringBuffer url = new StringBuffer(urlPathHelper.getOriginatingRequestUri(request)); url.append('?'); if (copyParameters) { String query = urlPathHelper.getOriginatingQueryString(request); if (query != null) { int i = query.indexOf(pageParam); if (i != -1) { url.append(query.substring(0, i)); } else { url.append(query).append('&'); } } } url.append(pageParam); url.append('='); linkPrefix = url.toString(); }
@Override protected String getMediaTypeKey(NativeWebRequest webRequest) { HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); if (request == null) { logger.warn("An HttpServletRequest is required to determine the media type key"); return null; } String path = PATH_HELPER.getLookupPathForRequest(request); String filename = WebUtils.extractFullFilenameFromUrlPath(path); String extension = StringUtils.getFilenameExtension(filename); return (StringUtils.hasText(extension)) ? extension.toLowerCase(Locale.ENGLISH) : null; }
protected void setUp() throws Exception { super.setUp(); urlPathHelper = new UrlPathHelper(); urlPathHelper.setUrlDecode(true); urlPathHelper.setDefaultEncoding("UTF-8"); sitePropertiesService = new MockSitePropertiesService(); sitePropertiesService.setProperty( siteKey_1, SitePropertyNames.URL_DEFAULT_CHARACTER_ENCODING, "UTF-8"); urlPathHelperManager = new UrlPathHelperManager(); urlPathHelperManager.setSitePropertiesService(sitePropertiesService); sitePathResolver = new SitePathResolver(); sitePathResolver.setSitePathPrefix("/site"); sitePathResolver.setUrlPathHelperManager(urlPathHelperManager); httpServletRequest = new MockHttpServletRequest(); // httpServletRequest.setCharacterEncoding("ISO-8859-1"); }
/** * Lookup the CMS Content Page for this request. * * @param request The request * @return the CMS content page */ protected ContentPageModel getContentPageForRequest(final HttpServletRequest request) { // Get the path for this request. // Note that the path begins with a '/' final String lookupPathForRequest = urlPathHelper.getLookupPathForRequest(request); try { // Lookup the CMS Content Page by label. Note that the label value must begin with a '/'. return getCmsPageService().getPageForLabel(lookupPathForRequest); } catch (final CMSItemNotFoundException ignore) { // Ignore exception } return null; }
protected void addCategoryToModel(HttpServletRequest request, ModelMap model) { Category rootCategory = null; if (getRootCategoryId() != null) { rootCategory = catalogService.findCategoryById(getRootCategoryId()); } else if (getRootCategoryName() != null) { rootCategory = catalogService.findCategoryByName(getRootCategoryName()); } if (rootCategory == null) { throw new IllegalStateException( "Catalog Controller configured incorrectly - rootId category not found: " + rootCategoryId); } String url = pathHelper.getRequestUri(request).substring(pathHelper.getContextPath(request).length()); String categoryId = request.getParameter("categoryId"); if (categoryId != null) { Category category = catalogService.findCategoryById(new Long(categoryId)); if (category != null) { url = category.getUrl(); } } List<Long> categoryIdList = catalogService.getChildCategoryURLMapByCategoryId(rootCategory.getId()).get(url); List<Category> categoryList = null; if (categoryIdList != null) { categoryList = new ArrayList<Category>(categoryIdList.size()); for (Long id : categoryIdList) { categoryList.add(catalogService.findCategoryById(id)); } } addCategoryListToModel(categoryList, rootCategory, url, model); model.addAttribute("rootCategory", rootCategory); }
public static boolean matchAll( HttpServletRequest request, UrlPathHelper urlPathHelper, PathMatcher pathMatcher, String[] patterns) { if (ArrayUtils.isNotEmpty(patterns)) { String lookupPath = urlPathHelper.getLookupPathForRequest(request); for (String pattern : patterns) { if (!pathMatcher.match(pattern, lookupPath)) { return false; } } } return true; }
@Override protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception { String lookupPath = urlPathHelper.getLookupPathForRequest(request); if (logger.isDebugEnabled()) { logger.debug("Looking up handler method for path " + lookupPath); } HandlerMethod handlerMethod = lookupHandlerMethod(lookupPath, request); if (logger.isDebugEnabled()) { if (handlerMethod != null) { logger.debug("Returning handler method [" + handlerMethod + "]"); } else { logger.debug("Did not find handler method for [" + lookupPath + "]"); } } return (handlerMethod != null) ? handlerMethod.createWithResolvedBean() : null; }
@Override protected Object getHandlerInternal(HttpServletRequest request) throws Exception { String url = URL_PATH_HELPER.getPathWithinApplication(request); UrlMatch match = routeSet.getBestMatch(request, url); if (match != null) { routeSet.setCurrentMatch(request, match); Object controller = specialRoutes.get(match.getRoute()); if (controller == null) { String controllerName = match.getParameters().get(controllerParameterName); if (controllerName != null) { return controllerName + controllerNameSuffix; } } return controller; } return null; }
/** * Overrides the default behaviour to establish the handler from the GrailsApplication instance * * @param request The request * @param cache Whether to cache the Handler in the request * @return The HandlerExecutionChain * @throws Exception */ protected HandlerExecutionChain getHandler(HttpServletRequest request, boolean cache) throws Exception { String uri = urlHelper.getPathWithinApplication(request); if (logger.isDebugEnabled()) { logger.debug("Looking up Grails controller for URI [" + uri + "]"); } GrailsControllerClass controllerClass = (GrailsControllerClass) application.getArtefactForFeature(ControllerArtefactHandler.TYPE, uri); final String actionName = (String) request.getAttribute(GrailsApplicationAttributes.ACTION_NAME_ATTRIBUTE); if (controllerClass != null) { HandlerInterceptor[] interceptors; // if we're in a development environment we want to re-establish interceptors just in case // they // have changed at runtime if (GrailsUtil.isDevelopmentEnv()) { interceptors = establishInterceptors(getWebApplicationContext()); } else { interceptors = this.interceptors; } if (controllerClass.isFlowAction(actionName)) { FlowHandler flowHandler = new AbstractFlowHandler() { public String getFlowId() { return actionName; } }; return new HandlerExecutionChain(flowHandler, interceptors); } else { return new HandlerExecutionChain(mainController, interceptors); } } return null; }
/** * Determines the list of {@link MediaType} for the given {@link HttpServletRequest}. * * <p>The default implementation invokes {@link #getMediaTypeFromFilename(String)} if {@linkplain * #setFavorPathExtension favorPathExtension} property is <code>true</code>. If the property is * <code>false</code>, or when a media type cannot be determined from the request path, this * method will inspect the {@code Accept} header of the request. * * <p>This method can be overridden to provide a different algorithm. * * @param request the current servlet request * @return the list of media types requested, if any */ protected List<MediaType> getMediaTypes(HttpServletRequest request) { if (this.favorPathExtension) { String requestUri = urlPathHelper.getLookupPathForRequest(request); String filename = WebUtils.extractFullFilenameFromUrlPath(requestUri); MediaType mediaType = getMediaTypeFromFilename(filename); if (mediaType != null) { if (logger.isDebugEnabled()) { logger.debug( "Requested media type is '" + mediaType + "' (based on filename '" + filename + "')"); } return Collections.singletonList(mediaType); } } if (this.favorParameter) { if (request.getParameter(this.parameterName) != null) { String parameterValue = request.getParameter(this.parameterName); MediaType mediaType = getMediaTypeFromParameter(parameterValue); if (mediaType != null) { if (logger.isDebugEnabled()) { logger.debug( "Requested media type is '" + mediaType + "' (based on parameter '" + this.parameterName + "'='" + parameterValue + "')"); } return Collections.singletonList(mediaType); } } } if (!this.ignoreAcceptHeader) { String acceptHeader = request.getHeader(ACCEPT_HEADER); if (StringUtils.hasText(acceptHeader)) { try { List<MediaType> acceptableMediaTypes = MediaType.parseMediaTypes(acceptHeader); List<MediaType> producibleMediaTypes = getProducibleMediaTypes(request); Set<MediaType> compatibleMediaTypes = new LinkedHashSet<MediaType>(); for (MediaType acceptable : acceptableMediaTypes) { for (MediaType producible : producibleMediaTypes) { if (acceptable.isCompatibleWith(producible)) { compatibleMediaTypes.add(getMostSpecificMediaType(acceptable, producible)); } } } List<MediaType> mediaTypes = new ArrayList<MediaType>(compatibleMediaTypes); MediaType.sortByQualityValue(mediaTypes); if (logger.isDebugEnabled()) { logger.debug( "Requested media types are " + mediaTypes + " based on Accept header types " + "and producible media types " + producibleMediaTypes + ")"); } return mediaTypes; } catch (IllegalArgumentException ex) { if (logger.isDebugEnabled()) { logger.debug( "Could not parse accept header [" + acceptHeader + "]: " + ex.getMessage()); } return null; } } } if (this.defaultContentType != null) { if (logger.isDebugEnabled()) { logger.debug( "Requested media types is " + this.defaultContentType + " (based on defaultContentType property)"); } return Collections.singletonList(this.defaultContentType); } else { return Collections.emptyList(); } }
static { urlPathHelper.setUrlDecode(false); }
static { PATH_HELPER.setUrlDecode(false); }