Java 类org.springframework.web.context.request.RequestAttributes 实例源码

项目:spring-cloud-skipper    文件:SkipperErrorAttributes.java   
@Override
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
    Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
    Throwable error = getError(requestAttributes);
    if (error != null) {
        // pass in name and version if ReleaseNotFoundException
        if (error instanceof ReleaseNotFoundException) {
            ReleaseNotFoundException e = ((ReleaseNotFoundException) error);
            if (e.getReleaseName() != null) {
                errorAttributes.put("releaseName", e.getReleaseName());
            }
            if (e.getReleaseVersion() != null) {
                errorAttributes.put("version", e.getReleaseVersion());
            }
        }
    }
    return errorAttributes;
}
项目:nitrite-database    文件:DataGateErrorController.java   
@RequestMapping
@ResponseBody
public ResponseEntity<DataGateError> error(HttpServletRequest request) {
    HttpStatus status = getStatus(request);
    RequestAttributes requestAttributes = new ServletRequestAttributes(request);
    Map<String, Object> attributeMap = this.errorAttributes.getErrorAttributes(requestAttributes, false);
    DataGateError dataGateError = new DataGateError();
    if (attributeMap != null) {
        String message = (String) attributeMap.get("message");
        dataGateError.setMessage(message);
    } else {
        dataGateError.setMessage("Unknown error");
    }

    return new ResponseEntity<>(dataGateError, status);
}
项目:nitrite-database    文件:DataGateErrorController.java   
@RequestMapping(produces = "text/html")
public String errorPage(HttpServletRequest request, Model model) {
    String message, error;
    HttpStatus status = getStatus(request);
    RequestAttributes requestAttributes = new ServletRequestAttributes(request);
    Map<String, Object> attributeMap = this.errorAttributes.getErrorAttributes(requestAttributes, false);

    if (attributeMap != null) {
        message = (String) attributeMap.get("message");
        error = (String) attributeMap.get("error");
        model.addAttribute("header", error);
        model.addAttribute("message", message);
    }

    if (status.is4xxClientError()){
        if(status.value() == 404) {
            model.addAttribute("header", "Sorry but we couldn't find this page");
            model.addAttribute("message", "This page you are looking for does not exist.");
        } else if (status.value() == 403) {
            model.addAttribute("header", "Access denied");
            model.addAttribute("message", "Full authentication is required to access this resource.");
        }
    } else if (status.value() == 500){
        model.addAttribute("header", "Internal Server Error");
        model.addAttribute("message",
                "If the problem persists feel free to create an issue in Github.");
    }
    model.addAttribute("number", status.value());
    return "errorPage";
}
项目:nixmash-blog    文件:UserController.java   
@RequestMapping(value = "/signup", method = RequestMethod.GET)
public String signupForm(@ModelAttribute SocialUserDTO socialUserDTO, WebRequest request, Model model) {
    if (request.getUserPrincipal() != null)
        return "redirect:/";
    else {
        Connection<?> connection = providerSignInUtils.getConnectionFromSession(request);
        request.setAttribute("connectionSubheader",
                webUI.parameterizedMessage(MESSAGE_KEY_SOCIAL_SIGNUP,
                        StringUtils.capitalize(connection.getKey().getProviderId())),
                RequestAttributes.SCOPE_REQUEST);

        socialUserDTO = createSocialUserDTO(request, connection);

        ConnectionData connectionData = connection.createData();
        SignInUtils.setUserConnection(request, connectionData);

        model.addAttribute(MODEL_ATTRIBUTE_SOCIALUSER, socialUserDTO);
        return SIGNUP_VIEW;
    }
}
项目:Your-Microservice    文件:YourServletUriComponentsBuilder.java   
/**
 * Obtain the request through {@link RequestContextHolder}.
 * @return the active servlet request
 */
protected static HttpServletRequest getCurrentRequest() {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    Assert.state(requestAttributes != null, "Could not find current request via RequestContextHolder");
    Assert.isInstanceOf(ServletRequestAttributes.class, requestAttributes);
    HttpServletRequest servletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
    Assert.state(servletRequest != null, "Could not find current HttpServletRequest");
    return servletRequest;
}
项目:happylifeplat-tcc    文件:SpringCloudTxTransactionInterceptor.java   
@Override
public Object interceptor(ProceedingJoinPoint pjp) throws Throwable {
    TccTransactionContext tccTransactionContext;
    //如果不是本地反射调用补偿
    RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
    HttpServletRequest request = requestAttributes == null ? null : ((ServletRequestAttributes) requestAttributes).getRequest();
    String context = request == null ? null : request.getHeader(CommonConstant.TCC_TRANSACTION_CONTEXT);
    tccTransactionContext =
            GsonUtils.getInstance().fromJson(context, TccTransactionContext.class);

    return tccTransactionAspectService.invoke(tccTransactionContext, pjp);
}
项目:TARA-Server    文件:TaraProperties.java   
public String getLocaleUrl(String locale) throws Exception {
    UriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentRequest().replaceQueryParam("locale", locale);
    RequestAttributes attributes = org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes();
    if (attributes instanceof ServletRequestAttributes) {
        int statusCode = ((ServletRequestAttributes) attributes).getResponse().getStatus();
        switch (statusCode) {
            case 200:
                break;
            case 404:
                builder.replacePath("" + statusCode);
                break;
            default:
                builder.replacePath("error");
        }
    }
    URI serverUri = new URI(this.casConfigurationProperties.getServer().getName());
    if ("https".equalsIgnoreCase(serverUri.getScheme())) {
        builder.port((serverUri.getPort() == -1) ? 443 : serverUri.getPort());
    }
    return builder.scheme(serverUri.getScheme()).host(serverUri.getHost()).build(true).toUriString();
}
项目:myth    文件:SpringCloudMythTransactionInterceptor.java   
@Override
public Object interceptor(ProceedingJoinPoint pjp) throws Throwable {
    MythTransactionContext mythTransactionContext = TransactionContextLocal.getInstance().get();
    if (Objects.nonNull(mythTransactionContext) &&
            mythTransactionContext.getRole() == MythRoleEnum.LOCAL.getCode()) {
        mythTransactionContext = TransactionContextLocal.getInstance().get();
    } else {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = requestAttributes == null ? null : ((ServletRequestAttributes) requestAttributes).getRequest();
        String context = request == null ? null : request.getHeader(CommonConstant.MYTH_TRANSACTION_CONTEXT);
        if (StringUtils.isNoneBlank(context)) {
            mythTransactionContext =
                    GsonUtils.getInstance().fromJson(context, MythTransactionContext.class);
        }
    }
    return mythTransactionAspectService.invoke(mythTransactionContext, pjp);
}
项目:juiser    文件:RequestContextUser.java   
protected User findUser() {
    try {
        RequestAttributes reqAttr = RequestContextHolder.currentRequestAttributes();

        if (reqAttr instanceof ServletRequestAttributes) {

            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) reqAttr;

            HttpServletRequest request = servletRequestAttributes.getRequest();

            if (request != null) {
                Object obj = request.getAttribute(User.class.getName());
                if (obj instanceof User) {
                    return (User) obj;
                }
            }
        }
    } catch (IllegalStateException e) {
        log.debug("Unable to obtain request context user via RequestContextHolder.", e);
    }

    return null;
}
项目:engerek    文件:SecurityUtil.java   
/**
 * Returns current connection information, as derived from HTTP request stored in current thread.
 * May be null if the thread is not associated with any HTTP request (e.g. task threads, operations invoked from GUI but executing in background).
 */
public static HttpConnectionInformation getCurrentConnectionInformation() {
    RequestAttributes attr = RequestContextHolder.getRequestAttributes();
    if (!(attr instanceof ServletRequestAttributes)) {
        return null;
    }
    ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) attr;
    HttpServletRequest request = servletRequestAttributes.getRequest();
    if (request == null) {
        return null;
    }
    HttpConnectionInformation rv = new HttpConnectionInformation();
    HttpSession session = request.getSession(false);
    if (session != null) {
        rv.setSessionId(session.getId());
    }
    rv.setLocalHostName(request.getLocalName());
    rv.setRemoteHostAddress(getRemoteHostAddress(request));
    return rv;
}
项目:spring-boot-concourse    文件:DefaultErrorAttributes.java   
private void addErrorDetails(Map<String, Object> errorAttributes,
        RequestAttributes requestAttributes, boolean includeStackTrace) {
    Throwable error = getError(requestAttributes);
    if (error != null) {
        while (error instanceof ServletException && error.getCause() != null) {
            error = ((ServletException) error).getCause();
        }
        errorAttributes.put("exception", error.getClass().getName());
        addErrorMessage(errorAttributes, error);
        if (includeStackTrace) {
            addStackTrace(errorAttributes, error);
        }
    }
    Object message = getAttribute(requestAttributes, "javax.servlet.error.message");
    if ((!StringUtils.isEmpty(message) || errorAttributes.get("message") == null)
            && !(error instanceof BindingResult)) {
        errorAttributes.put("message",
                StringUtils.isEmpty(message) ? "No message available" : message);
    }
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:DefaultErrorAttributes.java   
private void addErrorDetails(Map<String, Object> errorAttributes,
        RequestAttributes requestAttributes, boolean includeStackTrace) {
    Throwable error = getError(requestAttributes);
    if (error != null) {
        while (error instanceof ServletException && error.getCause() != null) {
            error = ((ServletException) error).getCause();
        }
        errorAttributes.put("exception", error.getClass().getName());
        addErrorMessage(errorAttributes, error);
        if (includeStackTrace) {
            addStackTrace(errorAttributes, error);
        }
    }
    Object message = getAttribute(requestAttributes, "javax.servlet.error.message");
    if ((!StringUtils.isEmpty(message) || errorAttributes.get("message") == null)
            && !(error instanceof BindingResult)) {
        errorAttributes.put("message",
                StringUtils.isEmpty(message) ? "No message available" : message);
    }
}
项目:metasfresh-webui-api    文件:WebuiExceptionHandler.java   
@Override
public Throwable getError(final RequestAttributes requestAttributes)
{
    Throwable exception = getAttribute(requestAttributes, REQUEST_ATTR_EXCEPTION);
    if (exception == null)
    {
        exception = getAttribute(requestAttributes, RequestDispatcher.ERROR_EXCEPTION);
    }

    if (exception != null)
    {
        exception = AdempiereException.extractCause(exception);
    }

    return exception;
}
项目:aramcomp    文件:PhotoController.java   
/**
    * 사진 목록 조회 Service interface 호출 및 결과를 반환한다.
    * 
    * @param photoVO
    */
@IncludedInfo(name = "사진 정보", order = 10050, gid = 100)
   @RequestMapping(value = "/mbl/com/mpa/listPhoto.do")
@Secured("ROLE_ADMIN")
   public String listPhoto(
        @ModelAttribute PhotoVO photoVO,
           ModelMap model) {

       PaginationInfo paginationInfo = new PaginationInfo();
       photoVO.getSearchVO().fillPageInfo(paginationInfo);

       model.addAttribute("resultList", photoService.selectPhotoList(photoVO));
       int totCnt = photoService.selectPhotoListCnt(photoVO);

       photoVO.getSearchVO().setTotalRecordCount(totCnt);
       paginationInfo.setTotalRecordCount(totCnt);

       model.addAttribute(paginationInfo);

    RequestContextHolder.getRequestAttributes().setAttribute("jspPrefix", "aramframework/mbl", RequestAttributes.SCOPE_REQUEST);
    return WebUtil.adjustViewName("/com/mpa/PhotoList");
   }
项目:aramcomp    文件:BBSBoardController.java   
private void setDirectUrlToModel(BoardVO boardVO, ModelMap model) {

    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

    String trgetId = (String) requestAttributes.getAttribute("curTrgetId", RequestAttributes.SCOPE_REQUEST);
    String contextUrl = (String) requestAttributes.getAttribute("contextUrl", RequestAttributes.SCOPE_REQUEST);
    String directUrl = "";
    if( trgetId != null 
            && trgetId != "" 
            && trgetId.indexOf("CMMNTY_") != -1) {
        String cmmntyId = WebUtil.getPathId(trgetId);
        directUrl = contextUrl + "/content/apps/"+cmmntyId+"/board/"+boardVO.getPathId()+"/article/"+boardVO.getNttId();
    } else {
        directUrl = contextUrl + "/content/board/"+boardVO.getPathId()+"/article/"+ boardVO.getNttId();
    }
    model.addAttribute("directUrl", directUrl);
}
项目:easycode    文件:SpringMvcConfig.java   
/**
 * 自定义ErrorAttributes,存储{@link com.easycodebox.common.error.CodeMsg} 属性
 */
@Bean
public ErrorAttributes errorAttributes() {
    return new DefaultErrorAttributes() {
        @Override
        public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
            Map<String, Object> attributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
            Throwable error = getError(requestAttributes);
            if (error instanceof ErrorContext) {
                ErrorContext ec = (ErrorContext) error;
                if (ec.getError() != null) {
                    attributes.put("code", ec.getError().getCode());
                    attributes.put("msg", ec.getError().getMsg());
                    attributes.put("data", ec.getError().getData());
                }
            }
            return attributes;
        }
    };
}
项目:aramcomp    文件:WebUtil.java   
public static String adjustViewName(String viewName) {

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        String jspPrefix = (String) requestAttributes.getAttribute("jspPrefix", RequestAttributes.SCOPE_REQUEST);
        if (jspPrefix == null || "".equals(jspPrefix)) jspPrefix = comDefaultPath;

        String jspPage = jspPrefix + viewName;  

//      LOG.debug("jspPage = " + jspPage);

        // if tiles exist, forward tiles layout
        String aTrgetId   = (String) requestAttributes.getAttribute("curTrgetId", RequestAttributes.SCOPE_REQUEST);
        String aCurMenuNo = (String) requestAttributes.getAttribute("curMenuNo", RequestAttributes.SCOPE_REQUEST);
        if( aTrgetId != null
                && aTrgetId.startsWith("CMMNTY_") 
                && aCurMenuNo != null
                && !"".equals(aCurMenuNo) )  {

            requestAttributes.setAttribute("jspPage", jspPage, RequestAttributes.SCOPE_REQUEST);

            return "forward:/cop/cmy/CmmntyTilesPage.do";
        }

        return jspPage;
    }
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:DefaultErrorAttributes.java   
private void addStatus(Map<String, Object> errorAttributes,
        RequestAttributes requestAttributes) {
    Integer status = getAttribute(requestAttributes,
            "javax.servlet.error.status_code");
    if (status == null) {
        errorAttributes.put("status", 999);
        errorAttributes.put("error", "None");
        return;
    }
    errorAttributes.put("status", status);
    try {
        errorAttributes.put("error", HttpStatus.valueOf(status).getReasonPhrase());
    }
    catch (Exception ex) {
        // Unable to obtain a reason
        errorAttributes.put("error", "Http Status " + status);
    }
}
项目:aramcomp    文件:GeoLocationController.java   
/**
   * 건물 위치정보 등록 Service interface 호출 및 결과를 반환한다.
   * 
   * @param geoLocationVO
   */
  @RequestMapping("/mbl/com/geo/insertBuildingLocationInfo.do")
  public String insertBuildingLocationInfo(
        @ModelAttribute GeoLocationVO geoLocationVO, 
          BindingResult bindingResult, 
        ModelMap model) {

      // Validation
      beanValidator.validate(geoLocationVO, bindingResult);
      if (bindingResult.hasErrors()) {
        RequestContextHolder.getRequestAttributes().setAttribute("jspPrefix", "aramframework/mbl", RequestAttributes.SCOPE_REQUEST);
        return WebUtil.adjustViewName("/com/geo/BuildingLocationInfoRegist");
      }

      LoginVO loginVO = (LoginVO)UserDetailsHelper.getAuthenticatedUser();
      geoLocationVO.setMberId(loginVO.getId());

      geoLocationService.insertBuildingLocationInfo(geoLocationVO);

model.addAttribute("message", MessageHelper.getMessage("success.common.insert"));
   return WebUtil.redirectJsp(model, "/mbl/com/geo/listBuildingLocationInfo.do");
   }
项目:aramcomp    文件:GeoLocationController.java   
/**
   * 건물 위치정보 수정 Service interface 호출 및 결과를 반환한다.
   * 
   * @param geoLocationVO
   */
  @RequestMapping(value="/mbl/com/geo/updateBuildingLocationInfo.do")
  public String updateBuildingLocationInfo(
        @ModelAttribute GeoLocationVO geoLocationVO, 
          BindingResult bindingResult, 
          ModelMap model) {

      // Validation
      beanValidator.validate(geoLocationVO, bindingResult);
      if (bindingResult.hasErrors()) {
        RequestContextHolder.getRequestAttributes().setAttribute("jspPrefix", "aramframework/mbl", RequestAttributes.SCOPE_REQUEST);
        return WebUtil.adjustViewName("/com/geo/BuildingLocationInfoEdit");
      }

      LoginVO loginVO = (LoginVO)UserDetailsHelper.getAuthenticatedUser();
      geoLocationVO.setMberId(loginVO.getId());

      geoLocationService.updateBuildingLocationInfo(geoLocationVO);

model.addAttribute("message", MessageHelper.getMessage("success.common.update"));
   return WebUtil.redirectJsp(model, "/mbl/com/geo/listBuildingLocationInfo.do");
  }
项目:aramcomp    文件:ChartGraphController.java   
/**
    * 차트/그래프 데이터 등록 Service interface 호출 및 결과를 반환한다.
    * 
    * @param chartGraphVO
    */
   @RequestMapping(value = "/mbl/com/mcg/insertChartGraph.do")
@Secured("ROLE_USER")
   public String insertChartGraph(
           @ModelAttribute ChartGraphVO chartGraphVO, 
           BindingResult bindingResult, 
           ModelMap model) {

       beanValidator.validate(chartGraphVO, bindingResult);
       if (bindingResult.hasErrors()) {
        RequestContextHolder.getRequestAttributes().setAttribute("jspPrefix", "aramframework/mbl", RequestAttributes.SCOPE_REQUEST);
        return WebUtil.adjustViewName("/com/mcg/ChartGraphRegist");
       }

       // 로그인VO에서 사용자 정보 가져오기
       LoginVO loginVO = (LoginVO) UserDetailsHelper.getAuthenticatedUser();
       chartGraphVO.setMberId(loginVO.getId());

       chartGraphService.insertChartGraph(chartGraphVO);

    model.addAttribute("message", MessageHelper.getMessage("success.common.insert"));
    return WebUtil.redirectJsp(model, "/mbl/com/mcg/listChartGraph.do");
   }
项目:aramcomp    文件:ChartGraphController.java   
/**
    * 차트/그래프 데이터 수정 Service interface 호출 및 결과를 반환한다.
    * 
    * @param chartGraphVO
    */
   @RequestMapping(value = "/mbl/com/mcg/updateChartGraph.do")
@Secured("ROLE_USER")
   public String updateChartGraph(
           @ModelAttribute ChartGraphVO chartGraphVO, 
           BindingResult bindingResult, 
           ModelMap model) {

       // Validation
       beanValidator.validate(chartGraphVO, bindingResult);
       if (bindingResult.hasErrors()) {
        RequestContextHolder.getRequestAttributes().setAttribute("jspPrefix", "aramframework/mbl", RequestAttributes.SCOPE_REQUEST);
        return WebUtil.adjustViewName("/com/mcg/ChartGraphEdit");
       }

       // 로그인VO에서 사용자 정보 가져오기
       LoginVO loginVO = (LoginVO) UserDetailsHelper.getAuthenticatedUser();
       chartGraphVO.setMberId(loginVO.getId());

       chartGraphService.updateChartGraph(chartGraphVO);

    model.addAttribute("message", MessageHelper.getMessage("success.common.update"));
    return WebUtil.redirectJsp(model, "/mbl/com/mcg/listChartGraph.do");
   }
项目:aramcomp    文件:SyncController.java   
/**
 * 동기화 목록 조회 Service interface 호출 및 결과를 반환한다.
 * 
 * @param syncVO
    */
@IncludedInfo(name = "동기화목록 정보", order = 10060, gid = 100)
@RequestMapping(value="/mbl/com/syn/listSync.do")
@Secured("ROLE_USER")
public String listSync (            
        @ModelAttribute SyncVO syncVO,          
        ModelMap model) {

    PaginationInfo paginationInfo = new PaginationInfo();
    syncVO.getSearchVO().fillPageInfo(paginationInfo);

    model.addAttribute("resultList", syncService.selectSyncList(syncVO));
       int totCnt = syncService.selectSyncListCnt(syncVO);

       syncVO.getSearchVO().setTotalRecordCount(totCnt);
    paginationInfo.setTotalRecordCount(totCnt);

    model.addAttribute(paginationInfo);

    RequestContextHolder.getRequestAttributes().setAttribute("jspPrefix", "aramframework/mbl", RequestAttributes.SCOPE_REQUEST);
    return WebUtil.adjustViewName("/com/syn/SyncList");
    }
项目:aramcomp    文件:SyncController.java   
/**
 * 동기화 서비스 등록 Service interface 호출 및 결과를 반환한다.
 * 
 * @param syncVO
 */
@RequestMapping(value="/mbl/com/syn/insertSync.do")
@Secured("ROLE_USER")
public String insertSync(
        @ModelAttribute SyncVO syncVO,          
        BindingResult bindingResult,
        ModelMap model) {

    beanValidator.validate(syncVO, bindingResult);
    if(bindingResult.hasErrors()){          
        RequestContextHolder.getRequestAttributes().setAttribute("jspPrefix", "aramframework/mbl", RequestAttributes.SCOPE_REQUEST);
        return WebUtil.adjustViewName("/com/syn/SyncRegist");
    }

    // 로그인VO에서  사용자 정보 가져오기
    LoginVO loginVO = (LoginVO)UserDetailsHelper.getAuthenticatedUser();
    syncVO.setMberId(loginVO.getId());  

    syncService.insertSync(syncVO);

    model.addAttribute("message", MessageHelper.getMessage("success.common.insert"));
    return WebUtil.redirectJsp(model, "/mbl/com/syn/listSync.do");
}
项目:happylifeplat-transaction    文件:SpringCloudTxTransactionInterceptor.java   
@Override
public Object interceptor(ProceedingJoinPoint pjp) throws Throwable {
    final String compensationId = CompensationLocal.getInstance().getCompensationId();
    String groupId = null;
    if (StringUtils.isBlank(compensationId)) {
        //如果不是本地反射调用补偿
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = requestAttributes == null ? null : ((ServletRequestAttributes) requestAttributes).getRequest();
        groupId = request == null ? null : request.getHeader(CommonConstant.TX_TRANSACTION_GROUP);
    }

    return aspectTransactionService.invoke(groupId, pjp);
}
项目:xm-uaa    文件:SocialControllerIntTest.java   
@Before
@SneakyThrows
public void setup() {
    TenantProperties properties = new TenantProperties();
    properties.setSocial(asList(
        new TenantProperties.Social("twitter", "xxx", "yyy", DEFAULT_DOMAIN),
        new TenantProperties.Social("facebook", "xxx", "yyy", DEFAULT_DOMAIN)
    ));
    tenantPropertiesService.onRefresh("/config/tenants/"+ DEFAULT_TENANT + "/uaa/uaa.yml",
        new ObjectMapper(new YAMLFactory()).writeValueAsString(properties));

    MockitoAnnotations.initMocks(this);
    SocialController socialController = new SocialController(socialService, providerSignInUtils,
        connectionFactoryLocator, usersConnectionRepository, signInAdapter, connectSupport, sessionStrategy, socialConfigRepository);
    this.restUserMockMvc = MockMvcBuilders.standaloneSetup(socialController)
        .setControllerAdvice(exceptionTranslator)
        .setMessageConverters(jacksonMessageConverter)
        .build();
    when(sessionStrategy.getAttribute(any(RequestAttributes.class), eq(ProviderSignInAttempt.SESSION_ATTRIBUTE)))
        .thenReturn(providerSignInAttempt);
    when(connection.fetchUserProfile())
        .thenReturn(new UserProfile("id", "name", "fname", "lname", "email", "username"));
    when(connection.createData()).thenReturn(
        new ConnectionData("twitter", "providerUserId", "displayName", "profileUrl", "imageUrl", "", "secret",
            "refreshToken", 1000L));
    Mockito.<Connection<?>>when(connectSupport.completeConnection(any(OAuth1ConnectionFactory.class), any()))
        .thenReturn(connection);
    Mockito.<Connection<?>>when(connectSupport.completeConnection(any(OAuth2ConnectionFactory.class), any()))
        .thenReturn(connection);
    when(connectSupport.buildOAuthUrl(any(), any(), any())).thenReturn("SomeCallbackUrl");
    Mockito.<Connection<?>>when(providerSignInAttempt.getConnection(any())).thenReturn(connection);
}
项目:private-WeChat    文件:SNSUserInfoArgumentResolver.java   
@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;
}
项目:private-WeChat    文件:SNSUserInfoArgumentResolver.java   
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;
}
项目:document-management-store-app    文件:ApiErrorAttributes.java   
@Override
public Map<String, Object> getErrorAttributes(
        RequestAttributes requestAttributes,
        boolean includeStackTrace) {

    Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, true);

    Throwable throwable = getError(requestAttributes);

    ErrorStatusCodeAndMessage errorStatusCodeAndMessage = exceptionStatusCodeAndMessageResolver
        .resolveStatusCodeAndMessage(
            throwable,
            (String) errorAttributes.get("message"),
            (Integer) requestAttributes.getAttribute("javax.servlet.error.status_code", 0));

    errorAttributes.put("error", errorStatusCodeAndMessage.getMessage());
    requestAttributes.setAttribute("javax.servlet.error.status_code", errorStatusCodeAndMessage.getStatusCode(), 0);
    errorAttributes.put("status", errorStatusCodeAndMessage.getStatusCode());


    log.error(
        errorStatusCodeAndMessage.getMessage(),
        StructuredArguments.keyValue("errorCode", errorStatusCodeAndMessage.getMessage()),
        StructuredArguments.keyValue("stackTrace", errorAttributes.get("trace"))
    );


    if (!globalIncludeStackTrace) {
        errorAttributes.remove("exception");
        errorAttributes.remove("trace");
    }
    errorAttributes.remove("message");

    return errorAttributes;
}
项目:renren-fast    文件:LoginUserHandlerMethodArgumentResolver.java   
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                              NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
    //获取用户ID
    Object object = request.getAttribute(AuthorizationInterceptor.LOGIN_USER_KEY, RequestAttributes.SCOPE_REQUEST);
    if(object == null){
        return null;
    }

    //获取用户信息
    UserEntity user = userService.queryObject((Long)object);

    return user;
}
项目:tx-lcn    文件:TxManagerInterceptor.java   
public Object around(ProceedingJoinPoint point) throws Throwable {

        TxTransactionCompensate compensate = TxTransactionCompensate.current();
        String groupId = null;
        int maxTimeOut = 0;
        if (compensate == null) {
            try {
                RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
                HttpServletRequest request = requestAttributes == null ? null : ((ServletRequestAttributes) requestAttributes).getRequest();
                groupId = request == null ? null : request.getHeader("tx-group");
                maxTimeOut = request == null?0:Integer.parseInt(request.getHeader("tx-maxTimeOut"));
            }catch (Exception e){}
        }
        return aspectBeforeService.around(groupId,maxTimeOut, point);
    }
项目:myfavor    文件:CustomErrorAttributes.java   
@Override
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
    Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
    ErrorMap errorMap = ErrorMap.of(errorAttributes.get("status") +"",
            (String)errorAttributes.get("error"), errorAttributes.get("message"));

    return JsonMap.ofError(errorMap);
}
项目:controller-logger    文件:RequestUtil.java   
@Nullable
private static HttpServletRequest getCurrentHttpRequest() {
    HttpServletRequest request = null;
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes != null && requestAttributes instanceof ServletRequestAttributes) {
        request = ((ServletRequestAttributes)requestAttributes).getRequest();
    }
    return request;
}
项目:lams    文件:WebAsyncUtils.java   
/**
 * Obtain the {@link WebAsyncManager} for the current request, or if not
 * found, create and associate it with the request.
 */
public static WebAsyncManager getAsyncManager(WebRequest webRequest) {
    int scope = RequestAttributes.SCOPE_REQUEST;
    WebAsyncManager asyncManager = (WebAsyncManager) webRequest.getAttribute(WEB_ASYNC_MANAGER_ATTRIBUTE, scope);
    if (asyncManager == null) {
        asyncManager = new WebAsyncManager();
        webRequest.setAttribute(WEB_ASYNC_MANAGER_ATTRIBUTE, asyncManager, scope);
    }
    return asyncManager;
}
项目:lams    文件:WebAsyncManager.java   
/**
 * Configure the {@link AsyncWebRequest} to use. This property may be set
 * more than once during a single request to accurately reflect the current
 * state of the request (e.g. following a forward, request/response
 * wrapping, etc). However, it should not be set while concurrent handling
 * is in progress, i.e. while {@link #isConcurrentHandlingStarted()} is
 * {@code true}.
 *
 * @param asyncWebRequest the web request to use
 */
public void setAsyncWebRequest(final AsyncWebRequest asyncWebRequest) {
    Assert.notNull(asyncWebRequest, "AsyncWebRequest must not be null");
    Assert.state(!isConcurrentHandlingStarted(), "Can't set AsyncWebRequest with concurrent handling in progress");
    this.asyncWebRequest = asyncWebRequest;
    this.asyncWebRequest.addCompletionHandler(new Runnable() {
        @Override
        public void run() {
            asyncWebRequest.removeAttribute(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
        }
    });
}
项目:lams    文件:WebApplicationContextUtils.java   
/**
 * Return the current RequestAttributes instance as ServletRequestAttributes.
 * @see RequestContextHolder#currentRequestAttributes()
 */
private static ServletRequestAttributes currentRequestAttributes() {
    RequestAttributes requestAttr = RequestContextHolder.currentRequestAttributes();
    if (!(requestAttr instanceof ServletRequestAttributes)) {
        throw new IllegalStateException("Current request is not a servlet request");
    }
    return (ServletRequestAttributes) requestAttr;
}
项目:spring-mvc-error-handling-example    文件:CustomErrorAttributes.java   
@Override
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
  Map<String, Object> result = new HashMap<>();
  result.put("timestamp", System.currentTimeMillis());
  result.put("error", "customized error");
  result.put("path", "customized path");
  result.put("status", 100);
  result.put("exception", "customized exception");
  result.put("message", "customized message");
  result.put("trace", "customized trace");
  result.put("add-attribute", "add-attribute");
  return result;
}
项目:school-express-delivery    文件:CurrentUserMethodArgumentResolver.java   
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

    //取出存入的用户ID
    String currentUserId = (String) webRequest.getAttribute(Constant.CURRENT_USER_ID, RequestAttributes.SCOPE_REQUEST);
    if (currentUserId != null) {
        return userDao.findById(currentUserId);
    }
    return new MissingServletRequestPartException(Constant.CURRENT_USER_ID);
}
项目:simple-openid-provider    文件:LoginFormController.java   
@GetMapping
public String getLoginForm(WebRequest request, Model model) {
    String continueUri = (String) request.getAttribute(AuthorizationEndpoint.AUTH_REQUEST_URI_ATTRIBUTE,
            RequestAttributes.SCOPE_SESSION);

    if (continueUri != null) {
        model.addAttribute(AuthorizationEndpoint.AUTH_REQUEST_URI_ATTRIBUTE, continueUri);
    }

    return LOGIN_FORM_VIEW_NAME;
}
项目:simple-openid-provider    文件:LoginFormController.java   
@GetMapping(params = ERROR_PARAMETER_NAME)
public String getLoginErrorForm(WebRequest request, Model model) {
    AuthenticationException error = (AuthenticationException) request
            .getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, RequestAttributes.SCOPE_SESSION);
    model.addAttribute(ERROR_PARAMETER_NAME, error != null ? error.getMessage() : DEFAULT_ERROR_MESSAGE);

    return getLoginForm(request, model);
}