Java Code Examples for org.springframework.web.context.request.NativeWebRequest

The following examples show how to use org.springframework.web.context.request.NativeWebRequest. These examples are extracted from open source projects. 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
/**
 * 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 2
Source Project: goods-seckill   Source File: UserArgumentResolver.java    License: Apache License 2.0 6 votes vote down vote up
@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 3
Source Project: nakadi   Source File: PartitionsController.java    License: MIT License 6 votes vote down vote up
@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 4
@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 5
/**
 * 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 6
Source Project: java-technology-stack   Source File: CallableInterceptorChain.java    License: MIT License 6 votes vote down vote up
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 7
@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 8
@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 9
/**
 * 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 10
/**
 * Initialize a WebDataBinder with {@code @InitBinder} methods.
 * <p>If the {@code @InitBinder} annotation specifies attributes names,
 * it is invoked only if the names include the target object name.
 * @throws Exception if one of the invoked @{@link InitBinder} methods fails
 * @see #isBinderMethodApplicable
 */
@Override
public void initBinder(WebDataBinder dataBinder, NativeWebRequest request) throws Exception {
	for (InvocableHandlerMethod binderMethod : this.binderMethods) {
		if (isBinderMethodApplicable(binderMethod, dataBinder)) {
			Object returnValue = binderMethod.invokeForRequest(request, null, dataBinder);
			if (returnValue != null) {
				throw new IllegalStateException(
						"@InitBinder methods must not return a value (should be void): " + binderMethod);
			}
		}
	}
}
 
Example 11
@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
    MethodInterceptResult result) throws Throwable {
    Object handler = allArguments[1];
    if (handler instanceof EnhancedInstance) {
        ContextManager.getRuntimeContext()
                      .put(RESPONSE_KEY_IN_RUNTIME_CONTEXT, ((NativeWebRequest) allArguments[2]).getNativeResponse());
    }
}
 
Example 12
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
    if (returnValue == null) {
        mavContainer.setRequestHandled(true);
        return;
    }

    final Single<?> single = Single.class.cast(returnValue);
    WebAsyncUtils.getAsyncManager(webRequest)
                 .startDeferredResultProcessing(new SingleDeferredResult(single), mavContainer);
}
 
Example 13
@Override
public List<MediaType> resolveMediaTypes(NativeWebRequest request) throws HttpMediaTypeNotAcceptableException {
	for (ContentNegotiationStrategy strategy : this.strategies) {
		List<MediaType> mediaTypes = strategy.resolveMediaTypes(request);
		if (mediaTypes.isEmpty() || mediaTypes.equals(MEDIA_TYPE_ALL)) {
			continue;
		}
		return mediaTypes;
	}
	return Collections.emptyList();
}
 
Example 14
@ExceptionHandler
public ResponseEntity<Problem> handleConcurrencyFailure(ConcurrencyFailureException ex, NativeWebRequest request) {
    Problem problem = Problem.builder()
        .withStatus(Status.CONFLICT)
        .with("message", ErrorConstants.ERR_CONCURRENCY_FAILURE)
        .build();
    return create(ex, problem, request);
}
 
Example 15
Source Project: loc-framework   Source File: LocServiceAdviceTrait.java    License: MIT License 5 votes vote down vote up
@API(status = API.Status.INTERNAL)
@ExceptionHandler(value = MethodArgumentNotValidException.class)
default ResponseEntity<Problem> handleMethodArgumentNotValidException(
    final MethodArgumentNotValidException methodArgumentNotValidException,
    final NativeWebRequest request) {
  List<FieldError> fieldErrors = methodArgumentNotValidException.getBindingResult().getFieldErrors();
  return this.create(methodArgumentNotValidException, ProblemUtil.createProblem(
      fieldErrors.stream().map(e -> e.getField() + ":" + e.getDefaultMessage())
          .collect(Collectors.joining(",")), METHOD_ARGUMENT_NOT_VALID_ERROR_CODE), request);
}
 
Example 16
Source Project: openapi-generator   Source File: ApiUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void setExampleResponse(NativeWebRequest req, String contentType, String example) {
    try {
        HttpServletResponse res = req.getNativeResponse(HttpServletResponse.class);
        res.setCharacterEncoding("UTF-8");
        res.addHeader("Content-Type", contentType);
        res.getWriter().print(example);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 17
/**
 * Construct a new attribute instance with the given constructor.
 * @since 5.0
 * @deprecated as of 5.1, in favor of
 * {@link #constructAttribute(Constructor, String, MethodParameter, WebDataBinderFactory, NativeWebRequest)}
 */
@Deprecated
@Nullable
protected Object constructAttribute(Constructor<?> ctor, String attributeName,
		WebDataBinderFactory binderFactory, NativeWebRequest webRequest) throws Exception {

	return null;
}
 
Example 18
@Override
protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest request) throws Exception {
	String[] headerValues = request.getHeaderValues(name);
	if (headerValues != null) {
		return (headerValues.length == 1 ? headerValues[0] : headerValues);
	}
	else {
		return null;
	}
}
 
Example 19
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 20
/**
 * This implementation downcasts {@link WebDataBinder} to
 * {@link ServletRequestDataBinder} before binding.
 * @see ServletRequestDataBinderFactory
 */
@Override
protected void bindRequestParameters(WebDataBinder binder, NativeWebRequest request) {
	ServletRequest servletRequest = request.getNativeRequest(ServletRequest.class);
	Assert.state(servletRequest != null, "No ServletRequest");
	ServletRequestDataBinder servletBinder = (ServletRequestDataBinder) binder;
	servletBinder.bind(servletRequest);
}
 
Example 21
@Nullable
public static MultipartRequest resolveMultipartRequest(NativeWebRequest webRequest) {
	MultipartRequest multipartRequest = webRequest.getNativeRequest(MultipartRequest.class);
	if (multipartRequest != null) {
		return multipartRequest;
	}
	HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
	if (servletRequest != null && isMultipartContent(servletRequest)) {
		return new StandardMultipartHttpServletRequest(servletRequest);
	}
	return null;
}
 
Example 22
Source Project: spring-analysis-note   Source File: ReactiveTypeHandler.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Collection<MediaType> getMediaTypes(NativeWebRequest request)
		throws HttpMediaTypeNotAcceptableException {

	Collection<MediaType> mediaTypes = (Collection<MediaType>) request.getAttribute(
			HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);

	return CollectionUtils.isEmpty(mediaTypes) ?
			this.contentNegotiationManager.resolveMediaTypes(request) : mediaTypes;
}
 
Example 23
@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 24
@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 25
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 26
@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 27
@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 28
Source Project: utils   Source File: SessionUserArgumentResolver.java    License: Apache License 2.0 5 votes vote down vote up
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 29
Source Project: problem-spring-web   Source File: OpenApiValidationAdviceTrait.java    License: MIT License 5 votes vote down vote up
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 30
@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;
}