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

The following examples show how to use org.springframework.web.context.request.ServletRequestAttributes. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: my-site   Source File: WebLogAspect.java    License: Apache License 2.0 6 votes vote down vote up
@Before("webLog()")
public void doBefore(JoinPoint joinPoint){

    startTime.set(System.currentTimeMillis());

    //接收到请求,记录请求内容
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    HttpSession session = request.getSession();
    // 记录下请求内容
    LOGGER.info("URL : " + request.getRequestURL().toString());
    LOGGER.info("HTTP_METHOD : " + request.getMethod());
    LOGGER.info("IP : " + request.getRemoteAddr());
    LOGGER.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
    LOGGER.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
}
 
Example 2
Source Project: halo   Source File: ControllerLogAop.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Around("controller()")
public Object controller(ProceedingJoinPoint joinPoint) throws Throwable {
    String className = joinPoint.getTarget().getClass().getSimpleName();
    String methodName = joinPoint.getSignature().getName();
    Object[] args = joinPoint.getArgs();

    // Get request attribute
    ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = Objects.requireNonNull(requestAttributes).getRequest();

    printRequestLog(request, className, methodName, args);
    long start = System.currentTimeMillis();
    Object returnObj = joinPoint.proceed();
    printResponseLog(request, className, methodName, returnObj, System.currentTimeMillis() - start);
    return returnObj;
}
 
Example 3
Source Project: SpringBoot-Course   Source File: HttpAspect.java    License: MIT License 6 votes vote down vote up
@Before("log()")
public void doBefore(JoinPoint joinPoint) {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    Map params = new HashMap();
    params.put("url", request.getRequestURL()); // 获取请求的url
    params.put("method", request.getMethod()); // 获取请求的方式
    params.put("ip", request.getRemoteAddr()); // 获取请求的ip地址
    params.put("className", joinPoint.getSignature().getDeclaringTypeName()); // 获取类名
    params.put("classMethod", joinPoint.getSignature().getName()); // 获取类方法
    params.put("args", joinPoint.getArgs()); // 请求参数

    // 输出格式化后的json字符串
    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    // logger.info("REQUEST: {}", gson.toJson(params));
}
 
Example 4
protected User getApiUser(boolean required) {
    HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder
            .getRequestAttributes())).getRequest();
    String token = request.getHeader("token");
    //    String token = request.getParameter("token");
    if (required) { // token必须要
        // 判断token是否存在,不存在要抛异常
        ApiAssert.notEmpty(token, "token不能为空");
        // 用token查用户信息,查不到要抛异常
        User user = userService.selectByToken(token);
        ApiAssert.notNull(user, "token不正确,请在网站上登录自己的帐号,然后进入个人设置页面扫描二维码获取token");
        return user;
    } else { // token非必须
        // 先判断token存在不,不存在直接返回null
        if (StringUtils.isEmpty(token)) return null;
        // 如果token存在,直接查询用户信息,不管查到查不到,都直接返回
        return userService.selectByToken(token);
    }
}
 
Example 5
Source Project: seckill-rocketmq   Source File: OrderChargeController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 平台下单接口
 * @param chargeOrderRequest
 * @return
 */
@RequestMapping(value = "charge.do", method = {RequestMethod.POST})
public @ResponseBody Result chargeOrder(@ModelAttribute ChargeOrderRequest chargeOrderRequest) {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    String sessionId = attributes.getSessionId();
    // 下单前置参数校验
    if (!secKillChargeService.checkParamsBeforeSecKillCharge(chargeOrderRequest, sessionId)) {
        return Result.error(CodeMsg.PARAM_INVALID);
    }
    // 前置商品校验
    String prodId = chargeOrderRequest.getProdId();
    if (!secKillChargeService.checkProdConfigBeforeKillCharge(prodId, sessionId)) {
        return Result.error(CodeMsg.PRODUCT_NOT_EXIST);
    }
    // 前置预减库存
    if (!secKillProductConfig.preReduceProdStock(prodId)) {
        return Result.error(CodeMsg.PRODUCT_STOCK_NOT_ENOUGH);
    }
    // 秒杀订单入队
    return secKillChargeService.secKillOrderEnqueue(chargeOrderRequest, sessionId);
}
 
Example 6
Source Project: jshERP   Source File: MsgService.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * create by: qiankunpingtai
 * website:https://qiankunpingtai.cn
 * description:
 *  逻辑删除角色信息
 * create time: 2019/3/28 15:44
 * @Param: ids
 * @return int
 */
@Transactional(value = "transactionManager", rollbackFor = Exception.class)
public int batchDeleteMsgByIds(String ids) throws Exception{
    logService.insertLog("序列号",
            new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_DELETE).append(ids).toString(),
            ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
    String [] idArray=ids.split(",");
    int result=0;
    try{
        result=msgMapperEx.batchDeleteMsgByIds(idArray);
    }catch(Exception e){
        logger.error("异常码[{}],异常提示[{}],异常[{}]",
                ExceptionConstants.DATA_WRITE_FAIL_CODE, ExceptionConstants.DATA_WRITE_FAIL_MSG,e);
        throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                ExceptionConstants.DATA_WRITE_FAIL_MSG);
    }
    return result;
}
 
Example 7
Source Project: softservice   Source File: WebExceptionAspect.java    License: MIT License 6 votes vote down vote up
/**
 * 将内容输出到浏览器
 *
 * @param content
 *            输出内容
 */
private void writeContent(String content) {
    HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
            .getResponse();
    response.reset();
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Content-Type", "text/plain;charset=UTF-8");
    response.setHeader("icop-content-type", "exception");
    PrintWriter writer = null;
    try {
        writer = response.getWriter();

        writer.print((content == null) ? "" : content);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 8
Source Project: jshERP   Source File: SupplierService.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Transactional(value = "transactionManager", rollbackFor = Exception.class)
public BaseResponseInfo importExcel(List<Supplier> mList) throws Exception {
    logService.insertLog("商家",
            new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_IMPORT).append(mList.size()).append(BusinessConstants.LOG_DATA_UNIT).toString(),
            ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
    BaseResponseInfo info = new BaseResponseInfo();
    Map<String, Object> data = new HashMap<String, Object>();
    try {
        for(Supplier s: mList) {
            supplierMapper.insertSelective(s);
        }
        info.code = 200;
        data.put("message", "成功");
    } catch (Exception e) {
        e.printStackTrace();
        info.code = 500;
        data.put("message", e.getMessage());
    }
    info.data = data;
    return info;
}
 
Example 9
@Override
protected void doFilterInternal(
		HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
		throws ServletException, IOException {

	ServletRequestAttributes attributes = new ServletRequestAttributes(request, response);
	initContextHolders(request, attributes);

	try {
		filterChain.doFilter(request, response);
	}
	finally {
		resetContextHolders();
		if (logger.isDebugEnabled()) {
			logger.debug("Cleared thread-bound request context: " + request);
		}
		attributes.requestCompleted();
	}
}
 
Example 10
@Test
public void testLocalizeConfigured() {
	AutomaticDispatcherUrlService adus = new AutomaticDispatcherUrlService();
	adus.setLocalDispatcherUrl("http://my:8080/local/dispatcher/");

	// set mock request in context holder
	MockHttpServletRequest mockRequest = new MockHttpServletRequest();
	mockRequest.setScheme("http");
	mockRequest.setServerName("myhost");
	mockRequest.setServerPort(80);
	mockRequest.setLocalName("localhost");
	mockRequest.setLocalPort(8080);
	mockRequest.setContextPath("/test");
	mockRequest.addHeader(X_FORWARD_HOST_HEADER, "geomajas.org");
	ServletRequestAttributes attributes = new ServletRequestAttributes(mockRequest);
	RequestContextHolder.setRequestAttributes(attributes);
	Assert.assertEquals("http://my:8080/local/dispatcher/something", adus.localize("http://geomajas.org/test/d/something"));

	// clean up
	RequestContextHolder.setRequestAttributes(null);
}
 
Example 11
Source Project: summerframework   Source File: GrayServerFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<Server> match(List<Server> servers) {
    if (servers == null || servers.size() == 0) {
        return servers;
    }
    ServletRequestAttributes requestAttributes =
        (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
    if (requestAttributes == null) {
        logger.debug("No servletRequestAttributes in current thread. Match all servers");
        return Lists.newArrayList(servers);
    }
    HttpServletRequest request = requestAttributes.getRequest();

    List<Map<String, String>> matchList = grayScriptEngine.execute(servers, convertRequest(request));
    List<Server> allServers = new ArrayList<>();
    allServers.addAll(servers);
    for (Map<String, String> m : matchList) {
        allServers = match(allServers, m);
    }
    if (allServers.size() == 0) {
        logger.info("No server found");
    }
    return allServers;
}
 
Example 12
Source Project: ProxyPool   Source File: WebLogAspect.java    License: Apache License 2.0 6 votes vote down vote up
@Before("log()")
public void doBeforeController(JoinPoint joinPoint) {

    // 接收到请求,记录请求内容
    log.debug("WebLogAspect.doBefore()");
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    // 记录下请求内容
    log.debug("URL : " + request.getRequestURL().toString());
    log.debug("HTTP_METHOD : " + request.getMethod());
    log.debug("IP : " + request.getRemoteAddr());
    log.debug("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
    log.debug("ARGS : " + Arrays.toString(joinPoint.getArgs()));
    //获取所有参数方法一:
    Enumeration<String> enu = request.getParameterNames();
    while (enu.hasMoreElements()) {
        String paraName = (String) enu.nextElement();
        System.out.println(paraName + ": " + request.getParameter(paraName));
    }
}
 
Example 13
@Test
public void validateCertificateForUnrecognizedCommonNameReturnsBadRequestHttpStatus() throws Throwable {
    var proceedingJoinPoint = mock(ProceedingJoinPoint.class);
    var additionalCertificateValidations = createAdditionalCertificateValidations();

    X509Certificate x509Certificate = mock(X509Certificate.class);
    X509Certificate[] x509Certificates = new X509Certificate[]{x509Certificate};
    X500Principal x500Principal = mock(X500Principal.class);

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setAttribute("javax.servlet.request.X509Certificate", x509Certificates);
    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));

    when(x509Certificate.getSubjectX500Principal()).thenReturn(x500Principal);
    when(x500Principal.getName()).thenReturn("qwertyuiop");

    Object response = victim.validate(proceedingJoinPoint, additionalCertificateValidations);

    verify(proceedingJoinPoint, times(0)).proceed();
    assertThat(response).isInstanceOf(ResponseEntity.class);

    ResponseEntity responseEntity = (ResponseEntity) response;
    assertThat(responseEntity.getStatusCode().value()).isEqualTo(400);
    assertThat(responseEntity.getBody()).isEqualTo("This certificate is not a valid one");
}
 
Example 14
/**
 * 验证用户输入的验证码
 * @param inputVerifyCode
 * @return
 */
public boolean validateVerifyCode(String inputVerifyCode){
    //获取当前线程绑定的request对象
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    // 这个VerifyCodeFactory.SESSION_KEY是在servlet中存入session的名字
    HttpSession session = request.getSession();
    String verifyCode = (String)session.getAttribute(VerifyCodeUtil.SESSION_KEY);
    if(null == verifyCode || verifyCode.isEmpty()){
        log.warn("验证码过期请重新验证");
        throw new DisabledException("验证码过期,请重新验证");
    }
    // 不分区大小写
    verifyCode = verifyCode.toLowerCase();
    inputVerifyCode = inputVerifyCode.toLowerCase();

    log.info("验证码:{}, 用户输入:{}", verifyCode, inputVerifyCode);

    return verifyCode.equals(inputVerifyCode);
}
 
Example 15
Source Project: mall-learning   Source File: WebLogAspect.java    License: Apache License 2.0 5 votes vote down vote up
@Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //记录请求信息
        WebLog webLog = new WebLog();
        Object result = joinPoint.proceed();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method.isAnnotationPresent(ApiOperation.class)) {
            ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
            webLog.setDescription(apiOperation.value());
        }
        long endTime = System.currentTimeMillis();
        String urlStr = request.getRequestURL().toString();
        webLog.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
        webLog.setIp(request.getRemoteUser());
        webLog.setMethod(request.getMethod());
        webLog.setParameter(getParameter(method, joinPoint.getArgs()));
        webLog.setResult(result);
        webLog.setSpendTime((int) (endTime - startTime));
        webLog.setStartTime(startTime);
        webLog.setUri(request.getRequestURI());
        webLog.setUrl(request.getRequestURL().toString());
//        LOGGER.info("{}", JSONUtil.parse(webLog));
        Map<String,Object> logMap = new HashMap<>();
        logMap.put("url",webLog.getUrl());
        logMap.put("method",webLog.getMethod());
        logMap.put("parameter",webLog.getParameter());
        logMap.put("spendTime",webLog.getSpendTime());
        logMap.put("description",webLog.getDescription());
        LOGGER.info(Markers.appendEntries(logMap), JSONUtil.parse(webLog).toString());
        return result;
    }
 
Example 16
Source Project: jeewx-boot   Source File: WeixinNewstemplateServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
private String updateContent(String content, String jwid) {
	if (content != null) {
		//获取token方法替换
		String accessToken =WeiXinHttpUtil.getRedisWeixinToken(jwid);
		//String baseImageUrl = ResourceUtil.getWebProjectPath();
		//update-begin--Author:zhangweijian  Date: 20180831 for:接口方法替换
		HttpServletRequest request =((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		String baseImageUrl=request.getSession().getServletContext().getRealPath("/");
		//update-end--Author:zhangweijian  Date: 20180831 for:接口方法替换
		String[] urls = ReadImgUrls.getImgs(content);
		if(urls!=null){
			for(String url:urls){
				if(url.indexOf("mmbiz.qpic.cn")!=-1){
					continue;
				}
				String relativeImgurl =url.replace(CommonWeixinProperties.domain,"");
				String tempimgurl ="";
				if(relativeImgurl.startsWith("http")){
					tempimgurl = relativeImgurl;
				}else{
					tempimgurl = baseImageUrl + relativeImgurl;
				}
				JSONObject retObj=JwSendMessageAPI.uploadImgReturnObj(accessToken, tempimgurl);
				if(null!=retObj&&retObj.containsKey("url")){
					String newUrl=retObj.getString("url");
					content = content.replace(url, newUrl);
					System.out.println("正文图片"+relativeImgurl+"同步微信成功!\r\n");
				}else{
					System.out.println("正文图片"+relativeImgurl+"同步微信成功!\r\n");
				}
			}
		}
	}
	
	return content;
}
 
Example 17
Source Project: mica   Source File: WebUtil.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 获取 HttpServletRequest
 *
 * @return {HttpServletRequest}
 */
@Nullable
public static HttpServletRequest getRequest() {
	return Optional.ofNullable(RequestContextHolder.getRequestAttributes())
		.map(x -> (ServletRequestAttributes) x)
		.map(ServletRequestAttributes::getRequest)
		.orElse(null);
}
 
Example 18
Source Project: cuba   Source File: PortalHttpSessionUrlsHolder.java    License: Apache License 2.0 5 votes vote down vote up
private HttpSession getHttpSession() {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes instanceof ServletRequestAttributes) {
    	HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        return request.getSession();
    } else {
        return null;
    }
}
 
Example 19
Source Project: HIS   Source File: WebLogAspect.java    License: Apache License 2.0 5 votes vote down vote up
@Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //记录请求信息(通过logstash传入elasticsearch)
        WebLog webLog = new WebLog();
        Object result = joinPoint.proceed();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method.isAnnotationPresent(ApiOperation.class)) {
            ApiOperation log = method.getAnnotation(ApiOperation.class);
            webLog.setDescription(log.value());
        }
        long endTime = System.currentTimeMillis();
        String urlStr = request.getRequestURL().toString();
        webLog.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
        webLog.setIp(request.getRemoteUser());
        webLog.setMethod(request.getMethod());
        webLog.setParameter(getParameter(method, joinPoint.getArgs()));
        webLog.setResult(result);
        webLog.setSpendTime((int) (endTime - startTime.get()));
        webLog.setStartTime(startTime.get());
        webLog.setUri(request.getRequestURI());
        webLog.setUrl(request.getRequestURL().toString());
        Map<String,Object> logMap = new HashMap<>();
        logMap.put("url",webLog.getUrl());
        logMap.put("method",webLog.getMethod());
        logMap.put("parameter",webLog.getParameter());
        logMap.put("spendTime",webLog.getSpendTime());
        logMap.put("description",webLog.getDescription());
//        LOGGER.info("{}", JSONUtil.parse(webLog));
        LOGGER.info(Markers.appendEntries(logMap), JSONUtil.parse(webLog).toString());
        return result;
    }
 
Example 20
Source Project: spring-microservice-exam   Source File: LogUtil.java    License: MIT License 5 votes vote down vote up
public static Log getLog() {
    HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    Log sysLog = new Log();
    sysLog.setCreator(Objects.requireNonNull(getUsername()));
    sysLog.setType(CommonConstant.STATUS_NORMAL);
    sysLog.setIp(ServletUtil.getClientIP(request));
    sysLog.setRequestUri(URLUtil.getPath(request.getRequestURI()));
    sysLog.setMethod(request.getMethod());
    sysLog.setUserAgent(request.getHeader("user-agent"));
    sysLog.setParams(HttpUtil.toParams(request.getParameterMap()));
    sysLog.setServiceId(getClientId());
    return sysLog;
}
 
Example 21
Source Project: XUpdateService   Source File: RestControllerAspect.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 环绕通知
 * @param joinPoint 连接点
 * @return 切入点返回值
 * @throws Throwable 异常信息
 */
@Around("@within(org.springframework.web.bind.annotation.RestController) || @annotation(org.springframework.web.bind.annotation.RestController)")
public Object apiLog(ProceedingJoinPoint joinPoint) throws Throwable {
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method method = signature.getMethod();

    boolean logFlag = this.needToLog(method);
    if (!logFlag) {
        return joinPoint.proceed();
    }
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

    String userAgent = request.getHeader("user-agent");
    String ip = IpUtils.getRealIp(request);
    String methodName = AspectJUtils.getMethodName(joinPoint);
    String params = AspectJUtils.getMethodParams(joinPoint);

    logger.info("\n\r" +
            "---------->|开始请求方法:{} \n\r" +
            "           |请求参数:{} \n\r" +
            "           |IP:{} \n\r" +
            "           |userAgent:{}", methodName, params, ip, userAgent);
    long start = System.currentTimeMillis();
    Object result = joinPoint.proceed();
    long end = System.currentTimeMillis();
    String deleteSensitiveContent =  AspectJUtils.deleteSensitiveContent(result);
    logger.info("\n\r" +
            "<----------|结束请求方法:{}\n\r" +
            "           |返回结果{} \n\r" +
            "           |耗时:{}毫秒 ", methodName, deleteSensitiveContent, end - start);
    return result;
}
 
Example 22
Source Project: ZTuoExchange_framework   Source File: UpdatePayAspect.java    License: MIT License 5 votes vote down vote up
public void check(JoinPoint joinPoint) throws Exception {
    startTime.set(System.currentTimeMillis());
    // 接收到请求,记录请求内容
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    AuthMember authMember = (AuthMember) request.getSession().getAttribute(SESSION_MEMBER);
    List<Order> list1 = orderService.getAllOrdering(authMember.getId());
    if (list1.size()>0){
        throw new IllegalArgumentException(msService.getMessage("HAVE_ORDER_ING"));
    }
    List<Advertise> list = advertiseService.getAllPutOnAdvertis(authMember.getId());
    if (list.size()>0){
        throw new IllegalArgumentException(msService.getMessage("MUST_PUT_OFF_ALL_ADVERTISE"));
    }
}
 
Example 23
Source Project: xmall   Source File: UmsAdminServiceImpl.java    License: MIT License 5 votes vote down vote up
/**
 * 添加登录记录
 * @param username 用户名
 */
private void insertLoginLog(String username) {
    UmsAdmin admin = getAdminByUsername(username);
    UmsAdminLoginLog loginLog = new UmsAdminLoginLog();
    loginLog.setAdminId(admin.getId());
    loginLog.setCreateTime(new Date());
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    loginLog.setIp(request.getRemoteAddr());
    loginLogMapper.insert(loginLog);
}
 
Example 24
Source Project: pulsar-manager   Source File: RoleBindingController.java    License: Apache License 2.0 5 votes vote down vote up
@ApiOperation(value = "Get the list of role binding")
@ApiResponses({
        @ApiResponse(code = 200, message = "ok"),
        @ApiResponse(code = 404, message = "Not found"),
        @ApiResponse(code = 500, message = "Internal server error")
})
@RequestMapping(value = "/role-binding", method =  RequestMethod.GET)
public ResponseEntity<Map<String, Object>> getRoleBingList(
        @ApiParam(value = "page_num", defaultValue = "1", example = "1")
        @RequestParam(name = "page_num", defaultValue = "1")
        @Min(value = 1, message = "page_num is incorrect, should be greater than 0.")
                Integer pageNum,
        @ApiParam(value = "page_size", defaultValue = "10", example = "10")
        @RequestParam(name="page_size", defaultValue = "10")
        @Range(min = 1, max = 1000, message = "page_size is incorrect, should be greater than 0 and less than 1000.")
                Integer pageSize) {
    Map<String, Object> result = Maps.newHashMap();
    HttpServletRequest request = ((ServletRequestAttributes)
            RequestContextHolder.getRequestAttributes()).getRequest();
    String token = request.getHeader("token");
    String tenant = request.getHeader("tenant");
    if (rolesService.isSuperUser(token)) {
        List<Map<String, Object>> roleBindingList = roleBindingService.getAllRoleBindingList();
        result.put("total", roleBindingList.size());
        result.put("data", roleBindingList);
        return ResponseEntity.ok(result);
    }
    Map<String, String> validateResult = rolesService.validateCurrentTenant(token, tenant);
    if (validateResult.get("error") != null) {
        result.put("error", validateResult.get("error"));
        return ResponseEntity.ok(result);
    }
    List<Map<String, Object>> userRoleInfo = roleBindingService.getRoleBindingList(token, tenant);
    result.put("total", userRoleInfo.size());
    result.put("data", userRoleInfo);
    return ResponseEntity.ok(result);
}
 
Example 25
Source Project: Gatekeeper   Source File: GatekeeperCommonConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public IGatekeeperUserProfile userProfile() {
    HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    Principal p = req.getUserPrincipal();
    return (IGatekeeperUserProfile) p;
}
 
Example 26
Source Project: seckill-rocketmq   Source File: OrderChargeController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 平台查单接口
 * @param queryOrderRequest
 * @return
 */
@RequestMapping(value = "query.do", method = {RequestMethod.GET})
public @ResponseBody String queryOrder(@ModelAttribute QueryOrderRequest queryOrderRequest) {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    String sessionId = attributes.getSessionId();
    // 查询前置参数校验
    if (!secKillChargeService.checkParamsBeforeSecKillQuery(queryOrderRequest, sessionId)) {
        return JSON.toJSONString(Result.error(CodeMsg.PARAM_INVALID));
    }
    // 查询订单
    return JSON.toJSONString(secKillChargeService.queryOrder(queryOrderRequest, sessionId));
}
 
Example 27
@BeforeEach
void setUp() {
  MockHttpServletRequest request = new MockHttpServletRequest();
  RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));

  gson = new Gson();
  EntityType entityType = mock(EntityType.class);
  when(entityType.getId()).thenReturn("sys_job_test");
  when(scriptJobExecution.getIdValue()).thenReturn("ID");
  when(scriptJobExecution.getEntityType()).thenReturn(entityType);
  when(scriptJobExecutionFactory.create()).thenReturn(scriptJobExecution);
  controller =
      new ScriptRunnerController(
          scriptJobExecutionFactory, jobExecutor, savedScriptRunner, gson, jobsController);
}
 
Example 28
private static String httpHeaderValue(final String header) {
    final String value;
    final ServletRequestAttributes requestAttributes = (ServletRequestAttributes) getRequestAttributes();
    if (requestAttributes != null && requestAttributes.getRequest() != null) {
        value = requestAttributes.getRequest().getHeader(header);
    } else {
        value = "";
    }
    return value != null ? value : "";
}
 
Example 29
Source Project: blog-sample   Source File: ValidateCodeFilter.java    License: Apache License 2.0 5 votes vote down vote up
private boolean validateVerify(String inputVerify) {
    //获取当前线程绑定的request对象
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    // 不分区大小写
    // 这个validateCode是在servlet中存入session的名字
    String validateCode = ((String) request.getSession().getAttribute("validateCode")).toLowerCase();
    inputVerify = inputVerify.toLowerCase();

    log.info("验证码:{}, 用户输入:{}", validateCode, inputVerify);
    return validateCode.equals(inputVerify);
}
 
Example 30
/**
 * 使用feign client访问别的微服务时,将上游传过来的access_token、username、roles等信息放入header传递给下一个服务
 */
@Bean
public RequestInterceptor httpFeignInterceptor() {
    return template -> {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                String headerName;
                String headerValue;
                while(headerNames.hasMoreElements()) {
                    headerName = headerNames.nextElement();
                    if (requestHeaders.contains(headerName)) {
                        headerValue = request.getHeader(headerName);
                        template.header(headerName, headerValue);
                    }
                }
            }
            //传递access_token,无网络隔离时需要传递
            /*
            String token = extractHeaderToken(request);
            if (StrUtil.isEmpty(token)) {
                token = request.getParameter(CommonConstant.ACCESS_TOKEN);
            }
            if (StrUtil.isNotEmpty(token)) {
                template.header(CommonConstant.TOKEN_HEADER, CommonConstant.BEARER_TYPE + " " + token);
            }
            */
        }
    };
}