@Override public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) { BindingResult result = ex.getBindingResult(); List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream() .map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode())) .collect(Collectors.toList()); Problem problem = Problem.builder() .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE) .withTitle("Method argument not valid") .withStatus(defaultConstraintViolationStatus()) .with("message", ErrorConstants.ERR_VALIDATION) .with("fieldErrors", fieldErrors) .build(); return create(ex, problem, request); }
private RedirectView handleSignIn(Connection<?> connection, ConnectionFactory<?> connectionFactory, NativeWebRequest request) { List<String> userIds = usersConnectionRepository.findUserIdsWithConnection(connection); if (userIds.isEmpty()) { ProviderSignInAttempt signInAttempt = new ProviderSignInAttempt(connection); sessionStrategy.setAttribute(request, ProviderSignInAttempt.SESSION_ATTRIBUTE, signInAttempt); return redirect(getSignUpUrl()); } else if (userIds.size() == 1) { usersConnectionRepository.createConnectionRepository(userIds.get(0)).updateConnection(connection); String originalUrl = signInAdapter.signIn(userIds.get(0), connection, request); return originalUrl != null ? redirect(originalUrl) : redirect(POST_SIGN_IN_URL); } else { log.error("Find more than one user with connection key: {}", connection.getKey()); return redirectOnError(connection.getKey().getProviderId()); } }
/** * 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()); } }
private Object resolveCookieValue(String cookieName, boolean required, String defaultValue, MethodParameter methodParam, NativeWebRequest webRequest, Object handlerForInitBinderCall) throws Exception { Class<?> paramType = methodParam.getParameterType(); if (cookieName.length() == 0) { cookieName = getRequiredParameterName(methodParam); } Object cookieValue = resolveCookieValue(cookieName, paramType, webRequest); if (cookieValue == null) { if (defaultValue != null) { cookieValue = resolveDefaultValue(defaultValue); } else if (required) { raiseMissingCookieException(cookieName, paramType); } cookieValue = checkValue(cookieName, cookieValue, paramType); } WebDataBinder binder = createBinder(webRequest, null, cookieName); initBinder(handlerForInitBinderCall, cookieName, binder, webRequest); return binder.convertIfNecessary(cookieValue, paramType, methodParam); }
@Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { String nonceBase64 = getNonceOrThrow(webRequest); String nonceSignatureBase64 = getNonceSignatureOrThrow(webRequest); if (!isBase64(nonceBase64)) { throw new BadRequestException("Nonce must be base64"); } if (!isBase64(nonceSignatureBase64)) { throw new BadRequestException("Nonce signature must be base64"); } return NonceAuthenticationImpl.builder() .nonceBase64(nonceBase64) .nonceSignatureBase64(nonceSignatureBase64) .build(); }
@Override public void handleReturnValue( Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { if (returnValue == null) { return; } else if (returnValue instanceof Model) { mavContainer.addAllAttributes(((Model) returnValue).asMap()); } else { // should not happen throw new UnsupportedOperationException("Unexpected return type: " + returnType.getParameterType().getName() + " in method: " + returnType.getMethod()); } }
@Override public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { if (returnValue == null) { mavContainer.setRequestHandled(true); return; } final AsyncResponseEntity<?> asyncResponseEntity = AsyncResponseEntity.class.cast(returnValue); Observable<?> observable = asyncResponseEntity.getObservable(); Single<?> single = asyncResponseEntity.getSingle(); MultiValueMap<String, String> headers = asyncResponseEntity.getHeaders(); HttpStatus status = asyncResponseEntity.getStatus(); if(observable != null) WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(new ObservableDeferredResult<>(observable, headers, status), mavContainer); else if(single != null) WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(new SingleDeferredResult<>(single, headers, status), mavContainer); }
/** * 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 provideArgs} * 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 the method raised an exception */ public final 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 = invoke(args); if (logger.isTraceEnabled()) { logger.trace("Method [" + getMethod().getName() + "] returned [" + returnValue + "]"); } return returnValue; }
/** * Populate the model in the following order: * <ol> * <li>Retrieve "known" session attributes -- i.e. attributes listed via * {@link SessionAttributes @SessionAttributes} and previously stored in * the in the model at least once * <li>Invoke {@link ModelAttribute @ModelAttribute} methods * <li>Find method arguments eligible as session attributes and retrieve * them if they're not already present in the model * </ol> * @param request the current request * @param mavContainer contains the model to be initialized * @param handlerMethod the method for which the model is initialized * @throws Exception may arise from {@code @ModelAttribute} methods */ public void initModel(NativeWebRequest request, ModelAndViewContainer mavContainer, HandlerMethod handlerMethod) throws Exception { Map<String, ?> attributesInSession = this.sessionAttributesHandler.retrieveAttributes(request); mavContainer.mergeAttributes(attributesInSession); invokeModelAttributeMethods(request, mavContainer); for (String name : findSessionAttributeArguments(handlerMethod)) { if (!mavContainer.containsAttribute(name)) { Object value = this.sessionAttributesHandler.retrieveAttribute(request, name); if (value == null) { throw new HttpSessionRequiredException("Expected session attribute '" + name + "'"); } mavContainer.addAttribute(name, value); } } }
@Override public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { if (returnValue == null) { mavContainer.setRequestHandled(true); return; } final DeferredResult<Object> deferredResult = new DeferredResult<>(); @SuppressWarnings("unchecked") ListenableFuture<Object> futureValue = (ListenableFuture<Object>) returnValue; Futures.addCallback(futureValue, new FutureCallback<Object>() { @Override public void onSuccess(@Nullable Object result) { deferredResult.setResult(result); } @Override public void onFailure(Throwable ex) { deferredResult.setErrorResult(ex); } }); startDeferredResultProcessing(mavContainer, webRequest, deferredResult); }
/** * Add {@link BindingResult} attributes to the model for attributes that require it. */ private void updateBindingResult(NativeWebRequest request, ModelMap model) throws Exception { List<String> keyNames = new ArrayList<String>(model.keySet()); for (String name : keyNames) { Object value = model.get(name); if (isBindingCandidate(name, value)) { String bindingResultKey = BindingResult.MODEL_KEY_PREFIX + name; if (!model.containsAttribute(bindingResultKey)) { WebDataBinder dataBinder = binderFactory.createBinder(request, value, name); model.put(bindingResultKey, dataBinder.getBindingResult()); } } } }
@Test public void handlesFailure() throws Exception { final AtomicReference<Object> value = new AtomicReference<>(); Exception ex = new Exception("This is bad"); ListenableFuture<String> future = Futures.immediateFailedFuture(ex); GuavaLFReturnValueHandler handler = new GuavaLFReturnValueHandler() { @Override protected void startDeferredResultProcessing(ModelAndViewContainer mavContainer, NativeWebRequest webRequest, DeferredResult<Object> deferredResult) throws Exception { value.set(deferredResult.getResult()); } }; handler.handleReturnValue(future, null, null, null); assertThat(value.get()).isEqualTo(ex); }
@Override @SuppressWarnings({ "unchecked", "rawtypes" }) public void handleReturnValue( Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { if (returnValue == null) { return; } else if (returnValue instanceof Map){ mavContainer.addAllAttributes((Map) returnValue); } else { // should not happen throw new UnsupportedOperationException("Unexpected return type: " + returnType.getParameterType().getName() + " in method: " + returnType.getMethod()); } }
public Object triggerAfterTimeout(NativeWebRequest request, Callable<?> task) { for (CallableProcessingInterceptor interceptor : this.interceptors) { try { Object result = interceptor.handleTimeout(request, task); if (result == CallableProcessingInterceptor.RESPONSE_HANDLED) { break; } else if (result != CallableProcessingInterceptor.RESULT_NONE) { return result; } } catch (Throwable t) { return t; } } return CallableProcessingInterceptor.RESULT_NONE; }
@Test public void handlesSuccess() throws Exception { final AtomicReference<Object> value = new AtomicReference<>(); ListenableFuture<String> future = Futures.immediateFuture("42"); GuavaLFReturnValueHandler handler = new GuavaLFReturnValueHandler() { @Override protected void startDeferredResultProcessing(ModelAndViewContainer mavContainer, NativeWebRequest webRequest, DeferredResult<Object> deferredResult) throws Exception { value.set(deferredResult.getResult()); } }; handler.handleReturnValue(future, null, null, null); assertThat(value.get()).isEqualTo("42"); }
@Override public List<MediaType> resolveMediaTypes(NativeWebRequest webRequest) { String key = getMediaTypeKey(webRequest); if (StringUtils.hasText(key)) { MediaType mediaType = lookupMediaType(key); if (mediaType != null) { handleMatch(key, mediaType); return Collections.singletonList(mediaType); } mediaType = handleNoMatch(webRequest, key); if (mediaType != null) { addMapping(key, mediaType); return Collections.singletonList(mediaType); } } return Collections.emptyList(); }
/** * Look up the given extension via {@link ServletContext#getMimeType(String)} * and if that doesn't help, delegate to the parent implementation. */ @Override protected MediaType handleNoMatch(NativeWebRequest webRequest, String extension) { MediaType mediaType = null; if (this.servletContext != null) { String mimeType = this.servletContext.getMimeType("file." + extension); if (StringUtils.hasText(mimeType)) { mediaType = MediaType.parseMediaType(mimeType); } } if (mediaType == null || MediaType.APPLICATION_OCTET_STREAM.equals(mediaType)) { MediaType superMediaType = super.handleNoMatch(webRequest, extension); if (superMediaType != null) { mediaType = superMediaType; } } return mediaType; }
@Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { final String token = webRequest.getHeader("X-Auth-Token"); final Authentication authentication = SecurityContextHolder.getContext() .getAuthentication(); return new AuthContext(token, authentication); }
@SuppressWarnings("unchecked") private Object resolveRequestHeader(String headerName, boolean required, String defaultValue, MethodParameter methodParam, NativeWebRequest webRequest, Object handlerForInitBinderCall) throws Exception { Class<?> paramType = methodParam.getParameterType(); if (Map.class.isAssignableFrom(paramType)) { return resolveRequestHeaderMap((Class<? extends Map<?, ?>>) paramType, webRequest); } if (headerName.length() == 0) { headerName = getRequiredParameterName(methodParam); } Object headerValue = null; String[] headerValues = webRequest.getHeaderValues(headerName); if (headerValues != null) { headerValue = (headerValues.length == 1 ? headerValues[0] : headerValues); } if (headerValue == null) { if (defaultValue != null) { headerValue = resolveDefaultValue(defaultValue); } else if (required) { raiseMissingHeaderException(headerName, paramType); } headerValue = checkValue(headerName, headerValue, paramType); } WebDataBinder binder = createBinder(webRequest, null, headerName); initBinder(handlerForInitBinderCall, headerName, binder, webRequest); return binder.convertIfNecessary(headerValue, paramType, methodParam); }
@GetMapping(value = "/signin/{providerId}", params = "oauth_token") public RedirectView oauth1Callback(@PathVariable String providerId, NativeWebRequest request) { try { OAuth1ConnectionFactory<?> connectionFactory = (OAuth1ConnectionFactory<?>) connectionFactoryLocator .getConnectionFactory(providerId); Connection<?> connection = connectSupport.completeConnection(connectionFactory, request); return handleSignIn(connection, connectionFactory, request); } catch (Exception e) { log.error("Exception while completing OAuth 1.0(a) connection: ", e); return redirectOnError(providerId); } }
@GetMapping(value = "/signin/{providerId}", params = "code") public RedirectView oauth2Callback(@PathVariable String providerId, @RequestParam("code") String code, NativeWebRequest request) { try { OAuth2ConnectionFactory<?> connectionFactory = (OAuth2ConnectionFactory<?>) connectionFactoryLocator .getConnectionFactory(providerId); Connection<?> connection = connectSupport.completeConnection(connectionFactory, request); return handleSignIn(connection, connectionFactory, request); } catch (Exception e) { log.error("Exception while completing OAuth 2 connection: ", e); return redirectOnError(providerId); } }
/** * Builds the provider URL to redirect the user to for connection authorization. * * @param connectionFactory the service provider's connection factory e.g. FacebookConnectionFactory * @param request the current web request * @param additionalParameters parameters to add to the authorization URL. * @return the URL to redirect the user to for authorization * @throws IllegalArgumentException if the connection factory is not OAuth1 based. */ public String buildOAuthUrl(ConnectionFactory<?> connectionFactory, NativeWebRequest request, MultiValueMap<String, String> additionalParameters) { if (connectionFactory instanceof OAuth1ConnectionFactory) { return buildOAuth1Url((OAuth1ConnectionFactory<?>) connectionFactory, request, additionalParameters); } else if (connectionFactory instanceof OAuth2ConnectionFactory) { return buildOAuth2Url((OAuth2ConnectionFactory<?>) connectionFactory, request, additionalParameters); } else { throw new IllegalArgumentException("ConnectionFactory not supported"); } }
/** * Get the method argument values for the current request. */ private Object[] getMethodArgumentValues(NativeWebRequest request, ModelAndViewContainer mavContainer, Object... providedArgs) throws Exception { MethodParameter[] parameters = getMethodParameters(); Object[] args = new Object[parameters.length]; for (int i = 0; i < parameters.length; i++) { MethodParameter parameter = parameters[i]; parameter.initParameterNameDiscovery(this.parameterNameDiscoverer); GenericTypeResolver.resolveParameterType(parameter, getBean().getClass()); args[i] = resolveProvidedArgument(parameter, providedArgs); if (args[i] != null) { continue; } if (this.argumentResolvers.supportsParameter(parameter)) { try { args[i] = this.argumentResolvers.resolveArgument( parameter, mavContainer, request, this.dataBinderFactory); continue; } catch (Exception ex) { if (logger.isTraceEnabled()) { logger.trace(getArgumentResolutionErrorMessage("Error resolving argument", i), ex); } throw ex; } } if (args[i] == null) { String msg = getArgumentResolutionErrorMessage("No suitable resolver for argument", i); throw new IllegalStateException(msg); } } return args; }
/** * Iterate over registered {@link HandlerMethodReturnValueHandler}s and invoke the one that supports it. * @exception IllegalStateException if no suitable {@link HandlerMethodReturnValueHandler} is found. */ @Override public void handleReturnValue( Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { HandlerMethodReturnValueHandler handler = getReturnValueHandler(returnType); Assert.notNull(handler, "Unknown return value type [" + returnType.getParameterType().getName() + "]"); handler.handleReturnValue(returnValue, returnType, mavContainer, webRequest); }
private OAuthToken fetchRequestToken(NativeWebRequest request, MultiValueMap<String, String> requestParameters, OAuth1Operations oauthOperations) { if (oauthOperations.getVersion() == OAuth1Version.CORE_10_REVISION_A) { return oauthOperations.fetchRequestToken(callbackUrl(request), requestParameters); } return oauthOperations.fetchRequestToken(null, requestParameters); }
/** * Add non-null return values to the {@link ModelAndViewContainer}. */ @Override public void handleReturnValue( Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { if (returnValue != null) { String name = ModelFactory.getNameForReturnValue(returnValue, returnType); mavContainer.addAttribute(name, returnValue); } }
private static MultiValueMap<String, String> getRequestParameters(NativeWebRequest request, String... ignoredParameters) { List<String> ignoredParameterList = asList(ignoredParameters); MultiValueMap<String, String> convertedMap = new LinkedMultiValueMap<>(); for (Entry<String, String[]> entry : request.getParameterMap().entrySet()) { if (!ignoredParameterList.contains(entry.getKey())) { convertedMap.put(entry.getKey(), asList(entry.getValue())); } } return convertedMap; }
@Override public String signIn(String userId, Connection<?> connection, NativeWebRequest request) { UserDetails user = userDetailsService.loadUserByUsername(userId); Authentication newAuth = new UsernamePasswordAuthenticationToken( user, null, user.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(newAuth); return jHipsterProperties.getSocial().getRedirectAfterSignIn(); }
@Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { Optional<String> authorizationHeaderValueOrEmpty = Optional.ofNullable(webRequest) .map(s -> s.getHeaderValues(HEADER_NAME)) .map(Arrays::stream).orElseGet(Stream::empty) .findFirst(); if (!authorizationHeaderValueOrEmpty.isPresent()) { throw new BadRequestException(HEADER_NAME + " header is invalid or missing"); } String authorizationHeaderValue = authorizationHeaderValueOrEmpty.get(); String[] authorizationHeaderValueParts = authorizationHeaderValue.split(":", 2); if (authorizationHeaderValueParts.length != 2) { throw new BadRequestException(HEADER_NAME + " header is invalid or missing"); } String appId = Optional.ofNullable(authorizationHeaderValueParts[0]) .filter(this::isValidAppId) .orElseThrow(() -> new BadRequestException(HEADER_NAME + " header is invalid or missing")); String apiKey = Optional.ofNullable(authorizationHeaderValueParts[1]) .filter(this::isValidApiKey) .orElseThrow(() -> new BadRequestException(HEADER_NAME + " header is invalid or missing")); Application application = Optional.of(applicationResolver.find(appId, apiKey)) .map(app -> app.onErrorMap(e -> new UnauthorizedException(e.getMessage(), e))) .map(Mono::block) .orElseThrow(() -> new UnauthorizedException("ApplicationEntity not found")); return ApplicationAuthenticationImpl.builder() .application(application) .build(); }
protected void initBinder(Object handler, String attrName, WebDataBinder binder, NativeWebRequest webRequest) throws Exception { if (this.bindingInitializer != null) { this.bindingInitializer.initBinder(binder, webRequest); } if (handler != null) { Set<Method> initBinderMethods = this.methodResolver.getInitBinderMethods(); if (!initBinderMethods.isEmpty()) { boolean debug = logger.isDebugEnabled(); for (Method initBinderMethod : initBinderMethods) { Method methodToInvoke = BridgeMethodResolver.findBridgedMethod(initBinderMethod); String[] targetNames = AnnotationUtils.findAnnotation(initBinderMethod, InitBinder.class).value(); if (targetNames.length == 0 || Arrays.asList(targetNames).contains(attrName)) { Object[] initBinderArgs = resolveInitBinderArguments(handler, methodToInvoke, binder, webRequest); if (debug) { logger.debug("Invoking init-binder method: " + methodToInvoke); } ReflectionUtils.makeAccessible(methodToInvoke); Object returnValue = methodToInvoke.invoke(handler, initBinderArgs); if (returnValue != null) { throw new IllegalStateException( "InitBinder methods must not have a return value: " + methodToInvoke); } } } } } }
@Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { if(Oauth2Token.class.equals(parameter.getParameterType())){ return webRequest.getAttribute("Oauth2Token", RequestAttributes.SCOPE_REQUEST); } if(SNSUserInfo.class.equals(parameter.getParameterType())){ return webRequest.getAttribute("SNSUserInfo", RequestAttributes.SCOPE_REQUEST); } return null; }
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { if(Oauth2Token.class.equals(parameter.getParameterType())){ return webRequest.getAttribute("Oauth2Token", RequestAttributes.SCOPE_REQUEST); } if(SNSUserInfo.class.equals(parameter.getParameterType())){ return webRequest.getAttribute("SNSUserInfo", RequestAttributes.SCOPE_REQUEST); } return null; }
@ExceptionHandler({UnauthorizedException.class}) public ModelAndView processUnauthenticatedException(NativeWebRequest request, UnauthorizedException e) { ModelAndView mv = new ModelAndView(); mv.addObject("exception", e.getMessage()); mv.setViewName("/common/error.ftl"); return mv; }
@Override public Object resolveArgument( MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { return mavContainer.getModel(); }
/** * Synchronize model attributes with the session. Add {@link BindingResult} * attributes where necessary. * @param request the current request * @param mavContainer contains the model to update * @throws Exception if creating BindingResult attributes fails */ public void updateModel(NativeWebRequest request, ModelAndViewContainer mavContainer) throws Exception { if (mavContainer.getSessionStatus().isComplete()){ this.sessionAttributesHandler.cleanupAttributes(request); } else { this.sessionAttributesHandler.storeAttributes(request, mavContainer.getModel()); } if (!mavContainer.isRequestHandled()) { updateBindingResult(request, mavContainer.getModel()); } }
@Override public String signIn(String localUserId, Connection<?> connection, NativeWebRequest request) { User user = userRepository.findByUsername(localUserId); ConnectionData connectionData = connection.createData(); SignInUtils.authorizeUser(user); SignInUtils.setUserConnection(request, connectionData); return null; }
/** * Create a new {@link WebDataBinder} for the given target object and * initialize it through a {@link WebBindingInitializer}. * @throws Exception in case of invalid state or arguments */ @Override public final WebDataBinder createBinder(NativeWebRequest webRequest, Object target, String objectName) throws Exception { WebDataBinder dataBinder = createBinderInstance(target, objectName, webRequest); if (this.initializer != null) { this.initializer.initBinder(dataBinder, webRequest); } initBinder(dataBinder, webRequest); return dataBinder; }
@Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { final HttpServletRequest httpServletRequest = webRequest.getNativeRequest(HttpServletRequest.class); RequestInfo requestInfo = new RequestInfo(); httpServletRequest.setAttribute(Constants.REQUEST_INFO_TAG, requestInfo); try { inspectorManager.check(httpServletRequest, requestInfo); } catch (OpenSecurityException e) { throw e; } return requestInfo; }
@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; } }