org.springframework.web.context.request.NativeWebRequest Java Examples
The following examples show how to use
org.springframework.web.context.request.NativeWebRequest.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InvocableHandlerMethod.java From spring4-understanding with Apache License 2.0 | 6 votes |
/** * Invoke the method after resolving its argument values in the context of the given request. * <p>Argument values are commonly resolved through {@link HandlerMethodArgumentResolver}s. * The {@code providedArgs} parameter however may supply argument values to be used directly, * i.e. without argument resolution. Examples of provided argument values include a * {@link WebDataBinder}, a {@link SessionStatus}, or a thrown exception instance. * Provided argument values are checked before argument resolvers. * @param request the current request * @param mavContainer the ModelAndViewContainer for this request * @param providedArgs "given" arguments matched by type, not resolved * @return the raw value returned by the invoked method * @exception Exception raised if no suitable argument resolver can be found, * or if the method raised an exception */ public Object invokeForRequest(NativeWebRequest request, ModelAndViewContainer mavContainer, Object... providedArgs) throws Exception { Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs); if (logger.isTraceEnabled()) { StringBuilder sb = new StringBuilder("Invoking ["); sb.append(getBeanType().getSimpleName()).append("."); sb.append(getMethod().getName()).append("] method with arguments "); sb.append(Arrays.asList(args)); logger.trace(sb.toString()); } Object returnValue = doInvoke(args); if (logger.isTraceEnabled()) { logger.trace("Method [" + getMethod().getName() + "] returned [" + returnValue + "]"); } return returnValue; }
Example #2
Source File: GlobalSearchHandlerMethodArgumentResolver.java From springlets with Apache License 2.0 | 6 votes |
@Override public GlobalSearch resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) { String searchValue = webRequest.getParameter(getSearchValueParameter()); if (StringUtils.isEmpty(searchValue)) { return null; } String regexp = webRequest.getParameter(getRegexpParameter()); if ("true".equalsIgnoreCase(regexp)) { return new GlobalSearch(searchValue, true); } else if ("false".equalsIgnoreCase(regexp)) { return new GlobalSearch(searchValue, false); } return new GlobalSearch(searchValue); }
Example #3
Source File: AuthenticationArgumentResolver.java From halo with GNU General Public License v3.0 | 6 votes |
@Override @Nullable public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer, NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) { log.debug("Handle AuthenticationArgument"); Class<?> parameterType = parameter.getParameterType(); Authentication authentication = Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication()) .orElseThrow(() -> new AuthenticationException("You haven't signed in yet")); if (Authentication.class.isAssignableFrom(parameterType)) { return authentication; } else if (UserDetail.class.isAssignableFrom(parameterType)) { return authentication.getDetail(); } else if (User.class.isAssignableFrom(parameterType)) { return authentication.getDetail().getUser(); } // Should never happen... throw new UnsupportedOperationException("Unknown parameter type: " + parameterType); }
Example #4
Source File: UserArgumentResolver.java From goods-seckill with Apache License 2.0 | 6 votes |
@Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class); String paramToken = request.getParameter(MiaoshaUserServiceImpl.COOKIE_NAME_TOKEN); String cookieToken = getCookieValue(request, MiaoshaUserServiceImpl.COOKIE_NAME_TOKEN); String token = null; if (StringUtils.isEmpty(paramToken)) { if (!StringUtils.isEmpty(cookieToken)) { token = cookieToken; } } else { token = paramToken; } if (StringUtils.isEmpty(token)) { return null; } return miaoshaUserService.getByToken(token, response); }
Example #5
Source File: ErrorsMethodArgumentResolver.java From lams with GNU General Public License v2.0 | 6 votes |
@Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { ModelMap model = mavContainer.getModel(); if (model.size() > 0) { int lastIndex = model.size()-1; String lastKey = new ArrayList<String>(model.keySet()).get(lastIndex); if (lastKey.startsWith(BindingResult.MODEL_KEY_PREFIX)) { return model.get(lastKey); } } throw new IllegalStateException( "An Errors/BindingResult argument is expected to be declared immediately after the model attribute, " + "the @RequestBody or the @RequestPart arguments to which they apply: " + parameter.getMethod()); }
Example #6
Source File: RequestResponseBodyMethodProcessor.java From java-technology-stack with MIT License | 6 votes |
/** * Throws MethodArgumentNotValidException if validation fails. * @throws HttpMessageNotReadableException if {@link RequestBody#required()} * is {@code true} and there is no body content or if there is no suitable * converter to read the content with. */ @Override public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer, NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception { parameter = parameter.nestedIfOptional(); Object arg = readWithMessageConverters(webRequest, parameter, parameter.getNestedGenericParameterType()); String name = Conventions.getVariableNameForParameter(parameter); if (binderFactory != null) { WebDataBinder binder = binderFactory.createBinder(webRequest, arg, name); if (arg != null) { validateIfApplicable(binder, parameter); if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) { throw new MethodArgumentNotValidException(parameter, binder.getBindingResult()); } } if (mavContainer != null) { mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult()); } } return adaptArgumentIfNecessary(arg, parameter); }
Example #7
Source File: PartitionsController.java From nakadi with MIT License | 6 votes |
@RequestMapping(value = "/event-types/{name}/partitions/{partition}", method = RequestMethod.GET) public ResponseEntity<?> getPartition( @PathVariable("name") final String eventTypeName, @PathVariable("partition") final String partition, @Nullable @RequestParam(value = "consumed_offset", required = false) final String consumedOffset, final NativeWebRequest request) throws NoSuchEventTypeException { LOG.trace("Get partition endpoint for event-type '{}', partition '{}' is called", eventTypeName, partition); final EventType eventType = eventTypeCache.getEventType(eventTypeName); authorizationValidator.authorizeEventTypeView(eventType); authorizationValidator.authorizeStreamRead(eventType); if (consumedOffset != null) { final CursorLag cursorLag = getCursorLag(eventTypeName, partition, consumedOffset); return ok().body(cursorLag); } else { final EventTypePartitionView result = getTopicPartition(eventTypeName, partition); return ok().body(result); } }
Example #8
Source File: Jackson2ServletRequestDataBinderFactory.java From gvnix with GNU General Public License v3.0 | 6 votes |
/** * Look current Thread for {@link ServletRequestDataBinder} created by * {@link DataBinderMappingJackson2HttpMessageConverter}, if found return * it, otherwise it delegates on parent method. * * @param target * @param objectName * @param request * @return ServletRequestDataBinder */ @Override protected ServletRequestDataBinder createBinderInstance(Object target, String objectName, NativeWebRequest request) { try { ServletRequestDataBinder binder = (ServletRequestDataBinder) ThreadLocalUtil .getThreadVariable(BindingResult.MODEL_KEY_PREFIX .concat("JSON_DataBinder")); if (binder != null) { return binder; } return super.createBinderInstance(target, objectName, request); } finally { ThreadLocalUtil.destroy(); } }
Example #9
Source File: CallableInterceptorChain.java From java-technology-stack with MIT License | 6 votes |
public Object applyPostProcess(NativeWebRequest request, Callable<?> task, Object concurrentResult) { Throwable exceptionResult = null; for (int i = this.preProcessIndex; i >= 0; i--) { try { this.interceptors.get(i).postProcess(request, task, concurrentResult); } catch (Throwable ex) { // Save the first exception but invoke all interceptors if (exceptionResult != null) { if (logger.isTraceEnabled()) { logger.trace("Ignoring failure in postProcess method", ex); } } else { exceptionResult = ex; } } } return (exceptionResult != null) ? exceptionResult : concurrentResult; }
Example #10
Source File: OpenApiValidationAdviceTrait.java From problem-spring-web with MIT License | 5 votes |
default ResponseEntity<Problem> newConstraintViolationProblem(final Exception exception, final NativeWebRequest request, final ValidationReport report) { final List<Violation> violations = report.getMessages().stream() .map(this::createViolation) .collect(toList()); return newConstraintViolationProblem(exception, violations, request); }
Example #11
Source File: RequestResponseBodyMethodProcessorTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public WebDataBinder createBinder(NativeWebRequest webRequest, Object target, String objectName) throws Exception { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.afterPropertiesSet(); WebDataBinder dataBinder = new WebDataBinder(target, objectName); dataBinder.setValidator(validator); return dataBinder; }
Example #12
Source File: SessionUserArgumentResolver.java From utils with Apache License 2.0 | 5 votes |
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { Object user = null; Subject subject = SecurityUtils.getSubject(); if (supportsParameter(parameter) && subject.isAuthenticated()) { user = subject.getPrincipal(); } return user; }
Example #13
Source File: StreamingResponseBodyReturnValueHandler.java From spring-analysis-note with MIT License | 5 votes |
@Override @SuppressWarnings("resource") public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { if (returnValue == null) { mavContainer.setRequestHandled(true); return; } HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class); Assert.state(response != null, "No HttpServletResponse"); ServerHttpResponse outputMessage = new ServletServerHttpResponse(response); if (returnValue instanceof ResponseEntity) { ResponseEntity<?> responseEntity = (ResponseEntity<?>) returnValue; response.setStatus(responseEntity.getStatusCodeValue()); outputMessage.getHeaders().putAll(responseEntity.getHeaders()); returnValue = responseEntity.getBody(); if (returnValue == null) { mavContainer.setRequestHandled(true); outputMessage.flush(); return; } } ServletRequest request = webRequest.getNativeRequest(ServletRequest.class); Assert.state(request != null, "No ServletRequest"); ShallowEtagHeaderFilter.disableContentCaching(request); Assert.isInstanceOf(StreamingResponseBody.class, returnValue, "StreamingResponseBody expected"); StreamingResponseBody streamingBody = (StreamingResponseBody) returnValue; Callable<Void> callable = new StreamingResponseBodyTask(outputMessage.getBody(), streamingBody); WebAsyncUtils.getAsyncManager(webRequest).startCallableProcessing(callable, mavContainer); }
Example #14
Source File: DeferredResultInterceptorChain.java From java-technology-stack with MIT License | 5 votes |
public Object applyPostProcess(NativeWebRequest request, DeferredResult<?> deferredResult, Object concurrentResult) { try { for (int i = this.preProcessingIndex; i >= 0; i--) { this.interceptors.get(i).postProcess(request, deferredResult, concurrentResult); } } catch (Throwable ex) { return ex; } return concurrentResult; }
Example #15
Source File: TimeoutCallableProcessingInterceptor.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public <T> Object handleTimeout(NativeWebRequest request, Callable<T> task) throws Exception { HttpServletResponse servletResponse = request.getNativeResponse(HttpServletResponse.class); if (!servletResponse.isCommitted()) { servletResponse.sendError(HttpStatus.SERVICE_UNAVAILABLE.value()); } return CallableProcessingInterceptor.RESPONSE_HANDLED; }
Example #16
Source File: SpringParameterProvider.java From katharsis-framework with Apache License 2.0 | 5 votes |
@Override @SuppressWarnings("unchecked") public <T> T provide(Method method, int parameterIndex) { MethodParameter methodParameter = new MethodParameter(method, parameterIndex); ModelAndViewContainer modelAndViewContainer = new ModelAndViewContainer(); NativeWebRequest webRequest = new ServletWebRequest(request); DefaultDataBinderFactory binderFactory = new DefaultDataBinderFactory(new ConfigurableWebBindingInitializer()); try { return (T) argumentResolvers.resolveArgument(methodParameter, modelAndViewContainer, webRequest, binderFactory); } catch (Exception e) { throw new RuntimeException(e); } }
Example #17
Source File: JsonArgumentResolver.java From springboot_security_restful_api with Apache License 2.0 | 5 votes |
private String getRequestBody(NativeWebRequest webRequest) { HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class); String jsonBody = (String) webRequest.getAttribute(JSON_BODY_ATTRIBUTE, NativeWebRequest.SCOPE_REQUEST); if (jsonBody == null) { try { jsonBody = IOUtils.toString(servletRequest.getInputStream(), "UTF-8"); webRequest.setAttribute(JSON_BODY_ATTRIBUTE, jsonBody, NativeWebRequest.SCOPE_REQUEST); } catch (IOException e) { throw new RuntimeException(e); } } return jsonBody; }
Example #18
Source File: RequestResponseBodyMethodProcessorMockTests.java From java-technology-stack with MIT License | 5 votes |
@Override public WebDataBinder createBinder(NativeWebRequest webRequest, @Nullable Object target, String objectName) throws Exception { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.afterPropertiesSet(); WebDataBinder dataBinder = new WebDataBinder(target, objectName); dataBinder.setValidator(validator); return dataBinder; }
Example #19
Source File: UriComponentsBuilderMethodArgumentResolver.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); return ServletUriComponentsBuilder.fromServletMapping(request); }
Example #20
Source File: UserDetailsArgumentResolver.java From slackspace-angular-spring-keycloak with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") private Object createUserDetails(NativeWebRequest webRequest) { KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = (KeycloakPrincipal<RefreshableKeycloakSecurityContext>) webRequest.getUserPrincipal(); AccessToken token = principal.getKeycloakSecurityContext().getToken(); return new UserDetails(token.getId(), token.getGivenName(), token.getFamilyName(), token.getEmail(), token.getRealmAccess().getRoles()); }
Example #21
Source File: ExceptionTranslator.java From cubeai with Apache License 2.0 | 5 votes |
/** * Post-process Problem payload to add the message key for front-end if needed */ @Override public ResponseEntity<Problem> process(@Nullable ResponseEntity<Problem> entity, NativeWebRequest request) { if (entity == null || entity.getBody() == null) { return entity; } Problem problem = entity.getBody(); if (!(problem instanceof ConstraintViolationProblem || problem instanceof DefaultProblem)) { return entity; } ProblemBuilder builder = Problem.builder() .withType(Problem.DEFAULT_TYPE.equals(problem.getType()) ? ErrorConstants.DEFAULT_TYPE : problem.getType()) .withStatus(problem.getStatus()) .withTitle(problem.getTitle()) .with("path", request.getNativeRequest(HttpServletRequest.class).getRequestURI()); if (problem instanceof ConstraintViolationProblem) { builder .with("violations", ((ConstraintViolationProblem) problem).getViolations()) .with("message", ErrorConstants.ERR_VALIDATION); return new ResponseEntity<>(builder.build(), entity.getHeaders(), entity.getStatusCode()); } else { builder .withCause(((DefaultProblem) problem).getCause()) .withDetail(problem.getDetail()) .withInstance(problem.getInstance()); problem.getParameters().forEach(builder::with); if (!problem.getParameters().containsKey("message") && problem.getStatus() != null) { builder.with("message", "error.http." + problem.getStatus().getStatusCode()); } return new ResponseEntity<>(builder.build(), entity.getHeaders(), entity.getStatusCode()); } }
Example #22
Source File: RestConfig.java From kbear with Apache License 2.0 | 5 votes |
@Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.defaultContentType(MediaType.APPLICATION_JSON) .strategies(Arrays.asList(new ContentNegotiationStrategy() { @Override public List<MediaType> resolveMediaTypes(NativeWebRequest webRequest) throws HttpMediaTypeNotAcceptableException { MediaType mediaType = MediaType.APPLICATION_JSON; String accept = webRequest.getHeader(HttpHeaders.ACCEPT); if (accept == null) return Arrays.asList(mediaType); switch (accept) { case APPLICATION_PROTOBUF_VALUE: mediaType = ProtobufHttpMessageConverter.PROTOBUF; break; case MediaType.APPLICATION_JSON_VALUE: mediaType = MediaType.APPLICATION_JSON; break; default: mediaType = MediaType.APPLICATION_JSON; break; } return Arrays.asList(mediaType); } })); }
Example #23
Source File: DefaultExceptionHandler.java From bookshop with MIT License | 5 votes |
@ExceptionHandler({UnauthorizedException.class}) @ResponseStatus(HttpStatus.UNAUTHORIZED) public ModelAndView processUnauthenticatedException(NativeWebRequest request, UnauthorizedException e) { ModelAndView mv = new ModelAndView(); mv.addObject("ex", e); mv.setViewName("unauthorized"); return mv; }
Example #24
Source File: ExceptionTranslator.java From java-microservices-examples with Apache License 2.0 | 5 votes |
@ExceptionHandler public ResponseEntity<Problem> handleNoSuchElementException(NoSuchElementException ex, NativeWebRequest request) { Problem problem = Problem.builder() .withStatus(Status.NOT_FOUND) .with(MESSAGE_KEY, ErrorConstants.ENTITY_NOT_FOUND_TYPE) .build(); return create(ex, problem, request); }
Example #25
Source File: SimpleSpecificationResolverTest.java From specification-arg-resolver with Apache License 2.0 | 5 votes |
@Test public void buildsTheSpecUsingCustomMultiValueWebParametersNames() throws Exception { MethodParameter param = MethodParameter.forExecutable(testMethod("testMethod4"), 0); NativeWebRequest req = mock(NativeWebRequest.class); QueryContext queryCtx = new WebRequestQueryContext(req); when(req.getParameterValues("theParameter")).thenReturn(new String[] { "theValue", "theValue2" }); when(req.getParameterValues("theParameter2")).thenReturn(new String[] { "theValue3", "theValue4" }); WebRequestProcessingContext ctx = new WebRequestProcessingContext(param, req); Specification<?> resolved = resolver.buildSpecification(ctx, param.getParameterAnnotation(Spec.class)); assertThat(resolved).isEqualTo(new EqualEnum<>(queryCtx, "thePath", new String[] { "theValue", "theValue2", "theValue3", "theValue4" })); }
Example #26
Source File: MethodNotAllowedAdviceTraitTest.java From problem-spring-web with MIT License | 5 votes |
@Test void noAllowIfNoneAllowed() { final MethodNotAllowedAdviceTrait unit = new MethodNotAllowedAdviceTrait() { }; final ResponseEntity<Problem> entity = unit.handleRequestMethodNotSupportedException( new HttpRequestMethodNotSupportedException("non allowed", new String[]{}), mock(NativeWebRequest.class)); assertThat(entity.getHeaders(), not(hasKey("Allow"))); }
Example #27
Source File: ModelAndViewResolverMethodReturnValueHandler.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { if (this.mavResolvers != null) { for (ModelAndViewResolver mavResolver : this.mavResolvers) { Class<?> handlerType = returnType.getContainingClass(); Method method = returnType.getMethod(); ExtendedModelMap model = (ExtendedModelMap) mavContainer.getModel(); ModelAndView mav = mavResolver.resolveModelAndView(method, handlerType, returnValue, model, webRequest); if (mav != ModelAndViewResolver.UNRESOLVED) { mavContainer.addAllAttributes(mav.getModel()); mavContainer.setViewName(mav.getViewName()); if (!mav.isReference()) { mavContainer.setView(mav.getView()); } return; } } } // No suitable ModelAndViewResolver... if (this.modelAttributeProcessor.supportsReturnType(returnType)) { this.modelAttributeProcessor.handleReturnValue(returnValue, returnType, mavContainer, webRequest); } else { throw new UnsupportedOperationException("Unexpected return type: " + returnType.getParameterType().getName() + " in method: " + returnType.getMethod()); } }
Example #28
Source File: LoggedInUserAccountArgumentResolver.java From salespoint with Apache License 2.0 | 5 votes |
@Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { Optional<UserAccount> user = authenticationManager.getCurrentUser(); ResolvableType parameterType = ResolvableType.forMethodParameter(parameter); return OPTIONAL_OF_USER_ACCOUNT.isAssignableFrom(parameterType) ? user : user.orElseThrow(() -> new ServletRequestBindingException(USER_ACCOUNT_EXPECTED)); }
Example #29
Source File: NakadiProblemExceptionHandler.java From nakadi with MIT License | 5 votes |
@Override @ExceptionHandler public ResponseEntity<Problem> handleThrowable(final Throwable throwable, final NativeWebRequest request) { final String errorTraceId = generateErrorTraceId(); LOG.error("InternalServerError (" + errorTraceId + "):", throwable); return create(Problem.valueOf(INTERNAL_SERVER_ERROR, "An internal error happened. Please report it. (" + errorTraceId + ")"), request); }
Example #30
Source File: DeferredResultInterceptorChain.java From spring-analysis-note with MIT License | 5 votes |
/** * Determine if further error handling should be bypassed. * @return {@code true} to continue error handling, or false to bypass any further * error handling */ public boolean triggerAfterError(NativeWebRequest request, DeferredResult<?> deferredResult, Throwable ex) throws Exception { for (DeferredResultProcessingInterceptor interceptor : this.interceptors) { if (deferredResult.isSetOrExpired()) { return false; } if (!interceptor.handleError(request, deferredResult, ex)){ return false; } } return true; }