org.springframework.web.context.request.RequestContextHolder Java Examples

The following examples show how to use org.springframework.web.context.request.RequestContextHolder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MailinglistController.java    From openemm with GNU Affero General Public License v3.0 7 votes vote down vote up
private void loadStatistics(ComAdmin admin, RecipientProgressStatisticDto statistic, MailinglistForm form, ModelMap model) throws Exception {
	if (statistic == null) {
		statistic = new RecipientProgressStatisticDto();
	}

	statistic.setMailinglistId(form.getId());

	if (statistic.getStartYear() == 0 && statistic.getStartMonth() == 0) {
		Calendar currentDate = Calendar.getInstance(AgnUtils.getTimeZone(admin));
		currentDate.set(Calendar.DAY_OF_MONTH, 1);

		statistic.setStartYear(currentDate.get(Calendar.YEAR));
		statistic.setStartMonth(currentDate.get(Calendar.MONTH));
	}

	String sessionId = RequestContextHolder.getRequestAttributes().getSessionId();
	String urlWithoutFormat = birtStatisticsService.getRecipientMonthlyStatisticsUrlWithoutFormat(admin, sessionId, statistic);

	model.addAttribute(YEAR_LIST, AgnUtils.getYearList(AgnUtils.getStatStartYearForCompany(admin)));
	model.addAttribute(MONTH_LIST, AgnUtils.getMonthList());
	model.addAttribute(BIRT_STATISTIC_URL_WITHOUT_FORMAT, urlWithoutFormat);

	form.setStatistic(statistic);
}
 
Example #2
Source File: LogRecordAspect.java    From teaching with Apache License 2.0 6 votes vote down vote up
@Around("excudeService()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
    RequestAttributes ra = RequestContextHolder.getRequestAttributes();
    ServletRequestAttributes sra = (ServletRequestAttributes) ra;
    HttpServletRequest request = sra.getRequest();

    String url = request.getRequestURL().toString();
    String method = request.getMethod();
    String uri = request.getRequestURI();
    String queryString = request.getQueryString();
    logger.info("请求开始, 各个参数, url: {}, method: {}, uri: {}, params: {}", url, method, uri, queryString);

    // result的值就是被拦截方法的返回值
    Object result = pjp.proceed();

    logger.info("请求结束,controller的返回值是 " + result);
    return result;
}
 
Example #3
Source File: ExpressionValueMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Before
@SuppressWarnings("resource")
public void setUp() throws Exception {
	GenericWebApplicationContext context = new GenericWebApplicationContext();
	context.refresh();
	resolver = new ExpressionValueMethodArgumentResolver(context.getBeanFactory());

	Method method = getClass().getMethod("params", int.class, String.class, String.class);
	paramSystemProperty = new MethodParameter(method, 0);
	paramContextPath = new MethodParameter(method, 1);
	paramNotSupported = new MethodParameter(method, 2);

	webRequest = new ServletWebRequest(new MockHttpServletRequest(), new MockHttpServletResponse());

	// Expose request to the current thread (for SpEL expressions)
	RequestContextHolder.setRequestAttributes(webRequest);
}
 
Example #4
Source File: ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testRequestScopeWithProxiedTargetClass() {
	RequestContextHolder.setRequestAttributes(oldRequestAttributes);
	ApplicationContext context = createContext(ScopedProxyMode.TARGET_CLASS);
	IScopedTestBean bean = (IScopedTestBean) context.getBean("request");

	// should be a class-based proxy
	assertTrue(AopUtils.isCglibProxy(bean));
	assertTrue(bean instanceof RequestScopedTestBean);

	assertEquals(DEFAULT_NAME, bean.getName());
	bean.setName(MODIFIED_NAME);

	RequestContextHolder.setRequestAttributes(newRequestAttributes);
	// this is a proxy so it should be reset to default
	assertEquals(DEFAULT_NAME, bean.getName());

	RequestContextHolder.setRequestAttributes(oldRequestAttributes);
	assertEquals(MODIFIED_NAME, bean.getName());
}
 
Example #5
Source File: CustomRequestAttributesRequestContextHolderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Before
public void setUp() {
	ServletContext servletContext = new MockServletContext();
	MockHttpServletRequest mockRequest = new MockHttpServletRequest(servletContext);
	mockRequest.setAttribute(FROM_CUSTOM_MOCK, FROM_CUSTOM_MOCK);
	RequestContextHolder.setRequestAttributes(new ServletWebRequest(mockRequest, new MockHttpServletResponse()));

	this.wac.setServletContext(servletContext);
	new AnnotatedBeanDefinitionReader(this.wac).register(WebConfig.class);
	this.wac.refresh();

	this.mockMvc = webAppContextSetup(this.wac)
			.defaultRequest(get("/").requestAttr(FROM_MVC_TEST_DEFAULT, FROM_MVC_TEST_DEFAULT))
			.alwaysExpect(status().isOk())
			.build();
}
 
Example #6
Source File: WebLogAspect.java    From dk-foundation with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
    // 接收到请求,记录请求内容
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    if (attributes == null) {
        return;
    }
    HttpServletRequest request = attributes.getRequest();

    // 记录下请求内容
    logger.info("URL : " + request.getRemoteAddr() + ":" + request.getMethod() + "->"
            + request.getRequestURL().toString());
    logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "."
            + joinPoint.getSignature().getName());
    logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));

}
 
Example #7
Source File: ServletTestExecutionListenerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void legacyWebTestCaseWithoutExistingRequestAttributes() throws Exception {
	BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(LegacyWebTestCase.class);

	RequestContextHolder.resetRequestAttributes();
	assertRequestAttributesDoNotExist();

	listener.beforeTestClass(testContext);

	listener.prepareTestInstance(testContext);
	assertRequestAttributesDoNotExist();
	verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
	given(testContext.getAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(null);

	listener.beforeTestMethod(testContext);
	assertRequestAttributesDoNotExist();
	verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);

	listener.afterTestMethod(testContext);
	verify(testContext, times(1)).removeAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE);
	assertRequestAttributesDoNotExist();
}
 
Example #8
Source File: ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testSingletonScopeIgnoresProxyTargetClass() {
	RequestContextHolder.setRequestAttributes(oldRequestAttributes);
	ApplicationContext context = createContext(ScopedProxyMode.TARGET_CLASS);
	ScopedTestBean bean = (ScopedTestBean) context.getBean("singleton");

	// should not be a proxy
	assertFalse(AopUtils.isAopProxy(bean));

	assertEquals(DEFAULT_NAME, bean.getName());
	bean.setName(MODIFIED_NAME);

	RequestContextHolder.setRequestAttributes(newRequestAttributes);
	// not a proxy so this should not have changed
	assertEquals(MODIFIED_NAME, bean.getName());

	// singleton bean, so name should be modified even after lookup
	ScopedTestBean bean2 = (ScopedTestBean) context.getBean("singleton");
	assertEquals(MODIFIED_NAME, bean2.getName());
}
 
Example #9
Source File: ExpressionValueMethodArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Before
@SuppressWarnings("resource")
public void setUp() throws Exception {
	GenericWebApplicationContext context = new GenericWebApplicationContext();
	context.refresh();
	resolver = new ExpressionValueMethodArgumentResolver(context.getBeanFactory());

	Method method = getClass().getMethod("params", int.class, String.class, String.class);
	paramSystemProperty = new MethodParameter(method, 0);
	paramContextPath = new MethodParameter(method, 1);
	paramNotSupported = new MethodParameter(method, 2);

	webRequest = new ServletWebRequest(new MockHttpServletRequest(), new MockHttpServletResponse());

	// Expose request to the current thread (for SpEL expressions)
	RequestContextHolder.setRequestAttributes(webRequest);
}
 
Example #10
Source File: GrayFeignRequestInterceptor.java    From lion with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(RequestTemplate template) {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    // 设置请求头header信息
    Enumeration<String> headerNames = request.getHeaderNames();
    if (null != headerNames) {
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            String value = request.getHeader(name);
            // 若version版本号为空,则赋值默认版本号
            if (name.equals(GrayConstant.VERSION) && StringUtils.isEmpty(value)) {
                value = GrayConstant.DEFAULT_VERSION;
            }
            template.header(name, value);
        }
    }

    // 设置灰度版本
    String version = request.getHeader(GrayConstant.VERSION);
    RibbonFilterContextHolder.getCurrentContext().add(GrayConstant.VERSION, version);
}
 
Example #11
Source File: RequestHeaderMethodArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Before
@SuppressWarnings("resource")
public void setup() throws Exception {
	GenericWebApplicationContext context = new GenericWebApplicationContext();
	context.refresh();
	resolver = new RequestHeaderMethodArgumentResolver(context.getBeanFactory());

	Method method = ReflectionUtils.findMethod(getClass(), "params", (Class<?>[]) null);
	paramNamedDefaultValueStringHeader = new SynthesizingMethodParameter(method, 0);
	paramNamedValueStringArray = new SynthesizingMethodParameter(method, 1);
	paramSystemProperty = new SynthesizingMethodParameter(method, 2);
	paramContextPath = new SynthesizingMethodParameter(method, 3);
	paramResolvedNameWithExpression = new SynthesizingMethodParameter(method, 4);
	paramResolvedNameWithPlaceholder = new SynthesizingMethodParameter(method, 5);
	paramNamedValueMap = new SynthesizingMethodParameter(method, 6);
	paramDate = new SynthesizingMethodParameter(method, 7);
	paramInstant = new SynthesizingMethodParameter(method, 8);

	servletRequest = new MockHttpServletRequest();
	webRequest = new ServletWebRequest(servletRequest, new MockHttpServletResponse());

	// Expose request to the current thread (for SpEL expressions)
	RequestContextHolder.setRequestAttributes(webRequest);
}
 
Example #12
Source File: LoginController.java    From pulsar-manager with Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "Logout pulsar manager")
@ApiResponses({
        @ApiResponse(code = 200, message = "ok"),
        @ApiResponse(code = 500, message = "Internal server error")
})
@RequestMapping(value = "/logout", method =  RequestMethod.POST)
public ResponseEntity<Map<String, Object>> logout() {
    Map<String, Object> result = Maps.newHashMap();
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    String username = request.getHeader("username");
    if (userManagementEnable) {
        usersRepository.findByUserName(username);
        Optional<UserInfoEntity> userInfoEntityOptional = usersRepository.findByUserName(username);
        if (!userInfoEntityOptional.isPresent()) {
            result.put("login", "The user is not exist");
            return ResponseEntity.ok(result);
        }
        UserInfoEntity userInfoEntity = userInfoEntityOptional.get();
        userInfoEntity.setAccessToken("");
        usersRepository.update(userInfoEntity);
    }
    result.put("logout", "success");
    jwtService.removeToken(request.getSession().getId());
    return ResponseEntity.ok(result);
}
 
Example #13
Source File: AbstractGrayHeaderCustomizer.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(R request) {
    try {
        ServletRequestAttributes requestAttributes =
            (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        List<String> headerNames =
            grayRulesStore.findHeader(registration.getApplicationInfoManager().getInfo().getAppName());
        if (headerNames != null) {
            headerNames.forEach(h -> {
                String headerKey = h.toLowerCase();
                String headerValue = requestAttributes.getRequest().getHeader(h);
                if (!containsKey(request, headerKey)) {
                    addHeaderToRequest(request, headerKey, headerValue);
                }
            });
        }
    } catch (Throwable ex) {
        logger.error(ex.getMessage(), ex);
    }
}
 
Example #14
Source File: FeignRequestInterceptor.java    From mall-swarm with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(RequestTemplate requestTemplate) {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
            .getRequestAttributes();
    if (attributes != null) {
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                requestTemplate.header(name, values);
            }
        }
    }
}
 
Example #15
Source File: ServletTestExecutionListenerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void legacyWebTestCaseWithoutExistingRequestAttributes() throws Exception {
	BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(LegacyWebTestCase.class);

	RequestContextHolder.resetRequestAttributes();
	assertRequestAttributesDoNotExist();

	listener.beforeTestClass(testContext);

	listener.prepareTestInstance(testContext);
	assertRequestAttributesDoNotExist();
	verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
	given(testContext.getAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(null);

	listener.beforeTestMethod(testContext);
	assertRequestAttributesDoNotExist();
	verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);

	listener.afterTestMethod(testContext);
	verify(testContext, times(1)).removeAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE);
	assertRequestAttributesDoNotExist();
}
 
Example #16
Source File: CustomAuthenticationProvider.java    From spring-security with Apache License 2.0 6 votes vote down vote up
/**
 * 验证用户输入的验证码
 * @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 #17
Source File: PageProcessAspect.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
@After("dataProcess()")
public void after(JoinPoint jp) throws IOException {
    // 接收到请求,记录请求内容
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

    HttpServletRequest request = attributes.getRequest();
    PageData pd = request.getAttribute(CommonConstant.CONTEXT_PAGE_DATA) != null ? (PageData) request.getAttribute(CommonConstant.CONTEXT_PAGE_DATA) : null;
    //保存日志处理
    if (pd == null) {
        return;
    }

    //写cookies信息
    writeCookieInfo(pd, attributes);

}
 
Example #18
Source File: LogAspect.java    From microservices-oauth with Apache License 2.0 6 votes vote down vote up
@Around("@annotation(logRequest)")
public Object LogRequest(ProceedingJoinPoint joinPoint, LogRequest logRequest) throws Throwable {

	// Intercepts called class and method name
	final String className = joinPoint.getSignature().getDeclaringTypeName();
	final Logger logger = LoggerFactory.getLogger(className);
	
	// Intercepts HTTP/HTTPS request
	HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
	
	// Logs info
	logger.info("[{}][{}][{}][{}][{}]",
			request.getHeader("X-Request-ID"), 	request.getRemoteHost(), request.getHeader("X-Forwarded-For"),
			request.getHeader("X-Forwarded-Host"), request.getHeader("X-Forwarded-Proto"));
	
	// Allows called method to execute and return it's result, if any
	return joinPoint.proceed();
}
 
Example #19
Source File: ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testSingletonScopeIgnoresProxyTargetClass() {
	RequestContextHolder.setRequestAttributes(oldRequestAttributes);
	ApplicationContext context = createContext(ScopedProxyMode.TARGET_CLASS);
	ScopedTestBean bean = (ScopedTestBean) context.getBean("singleton");

	// should not be a proxy
	assertFalse(AopUtils.isAopProxy(bean));

	assertEquals(DEFAULT_NAME, bean.getName());
	bean.setName(MODIFIED_NAME);

	RequestContextHolder.setRequestAttributes(newRequestAttributes);
	// not a proxy so this should not have changed
	assertEquals(MODIFIED_NAME, bean.getName());

	// singleton bean, so name should be modified even after lookup
	ScopedTestBean bean2 = (ScopedTestBean) context.getBean("singleton");
	assertEquals(MODIFIED_NAME, bean2.getName());
}
 
Example #20
Source File: ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testRequestScopeWithProxiedInterfaces() {
	RequestContextHolder.setRequestAttributes(oldRequestAttributes);
	ApplicationContext context = createContext(ScopedProxyMode.INTERFACES);
	IScopedTestBean bean = (IScopedTestBean) context.getBean("request");

	// should be dynamic proxy, implementing both interfaces
	assertTrue(AopUtils.isJdkDynamicProxy(bean));
	assertTrue(bean instanceof AnotherScopeTestInterface);

	assertEquals(DEFAULT_NAME, bean.getName());
	bean.setName(MODIFIED_NAME);

	RequestContextHolder.setRequestAttributes(newRequestAttributes);
	// this is a proxy so it should be reset to default
	assertEquals(DEFAULT_NAME, bean.getName());

	RequestContextHolder.setRequestAttributes(oldRequestAttributes);
	assertEquals(MODIFIED_NAME, bean.getName());
}
 
Example #21
Source File: ScheduleController.java    From kob with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/task_trigger_opt.json")
@ResponseBody
public ResponseData taskTriggerOpt() {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    ProjectUser projectUser = (ProjectUser) request.getSession().getAttribute(Attribute.PROJECT_SELECTED);
    String taskUuid = request.getParameter("taskUuid");
    int count = scheduleService.triggerTaskWaiting(taskUuid, projectUser.getProjectCode());
    return ResponseData.success();
}
 
Example #22
Source File: SessionUtils.java    From flash-waimai with MIT License 5 votes vote down vote up
public static HttpSession getSession() {
	if (RequestContextHolder.getRequestAttributes() == null) {
		return null;
	}
	HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	return request.getSession();
}
 
Example #23
Source File: TokenRequiredAspect.java    From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License 5 votes vote down vote up
@Before("@annotation(tokenRequired)")
public void tokenRequiredWithAnnotation(TokenRequired tokenRequired) throws Throwable{
	
	System.out.println("Before tokenRequiredWithAnnotation");
	
	ServletRequestAttributes reqAttributes = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
	HttpServletRequest request = reqAttributes.getRequest();
	
	// checks for token in request header
	String tokenInHeader = request.getHeader("token");
	
	if(StringUtils.isEmpty(tokenInHeader)){
		throw new IllegalArgumentException("Empty token");
	}
	
	Claims claims = Jwts.parser()         
		       .setSigningKey(DatatypeConverter.parseBase64Binary(SecurityServiceImpl.secretKey))
		       .parseClaimsJws(tokenInHeader).getBody();
	
	if(claims == null || claims.getSubject() == null){
		throw new IllegalArgumentException("Token Error : Claim is null");
	}
	
	if(!claims.getSubject().equalsIgnoreCase("packt")){
		throw new IllegalArgumentException("Subject doesn't match in the token");
	}
}
 
Example #24
Source File: RequestHolder.java    From springboot-shiro with MIT License 5 votes vote down vote up
/**
 * 获取request
 *
 * @return HttpServletRequest
 */
public static HttpServletRequest getRequest() {
    log.debug("getRequest -- Thread id :{}, name : {}", Thread.currentThread().getId(), Thread.currentThread().getName());
    ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
    if (null == servletRequestAttributes) {
        return null;
    }
    return servletRequestAttributes.getRequest();
}
 
Example #25
Source File: ServletUriComponentsBuilderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void fromCurrentRequest() {
	this.request.setRequestURI("/mvc-showcase/data/param");
	this.request.setQueryString("foo=123");
	RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(this.request));
	try {
		String result = ServletUriComponentsBuilder.fromCurrentRequest().build().toUriString();
		assertEquals("http://localhost/mvc-showcase/data/param?foo=123", result);
	}
	finally {
		RequestContextHolder.resetRequestAttributes();
	}
}
 
Example #26
Source File: RequestAwareRunnable.java    From mogu_blog_v2 with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    try {
        RequestContextHolder.setRequestAttributes(requestAttributes);
        onRun();
    } finally {
        if (Thread.currentThread() != thread) {
            RequestContextHolder.resetRequestAttributes();
        }
        thread = null;
    }
}
 
Example #27
Source File: CSRTokenRequiredAspect.java    From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License 5 votes vote down vote up
@Before("@annotation(csrTokenRequired)")
public void adminTokenRequiredWithAnnotation(CSRTokenRequired csrTokenRequired) throws Throwable{
	
	ServletRequestAttributes reqAttributes = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
	HttpServletRequest request = reqAttributes.getRequest();
	
	// checks for token in request header
	String tokenInHeader = request.getHeader("token");
	
	if(StringUtils.isEmpty(tokenInHeader)){
		throw new IllegalArgumentException("Empty token");
	}		
	
	Claims claims = Jwts.parser()         
		       .setSigningKey(DatatypeConverter.parseBase64Binary(SecurityServiceImpl.secretKey))
		       .parseClaimsJws(tokenInHeader).getBody();
	
	if(claims == null || claims.getSubject() == null){
		throw new IllegalArgumentException("Token Error : Claim is null");
	}
	
	String subject = claims.getSubject();
	
	if(subject.split("=").length != 2 || new Integer(subject.split("=")[1]) != 2){
		throw new IllegalArgumentException("User is not authorized");
	}		
}
 
Example #28
Source File: WebLogAspect.java    From macrozheng-mall with MIT License 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();
    webLog.setBasePath(RequestUtil.getBasePath(request));
    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.objectToJson(webLog));
    LOGGER.info(Markers.appendEntries(logMap),JsonUtil.objectToJson(webLog));
    return result;
}
 
Example #29
Source File: DomainStatisticController.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@RequestMapping("/view.action")
public String view(ComAdmin admin, DomainStatisticForm form, Model model) throws Exception {
	String sessionId = RequestContextHolder.getRequestAttributes().getSessionId();
	model.addAttribute(TARGET_LIST, targetService.getTargetLights(admin.getCompanyID()));
	model.addAttribute(MAILING_LISTS, mailinglistApprovalService.getEnabledMailinglistsNamesForAdmin(admin));
	model.addAttribute(BIRT_STATISTIC_URL_WITHOUT_FORMAT,
			birtStatisticsService.getDomainStatisticsUrlWithoutFormat(
					admin, sessionId, conversionService.convert(form, DomainStatisticDto.class), false));
	userActivityLogService.writeUserActivityLog(admin, "domain statistics", "active submenu - domain overview", logger);
	return "stats_birt_domain_stat";
}
 
Example #30
Source File: ScheduleController.java    From kob with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/job_suspend_opt.json")
@ResponseBody
public ResponseData jobSuspendOpt() {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    ProjectUser projectUser = (ProjectUser) request.getSession().getAttribute(Attribute.PROJECT_SELECTED);
    String jobUuid = request.getParameter("job_uuid");
    Boolean suspend = Boolean.valueOf(request.getParameter("suspend"));
    if (suspend) {
        scheduleService.startJobCron(jobUuid, suspend, projectUser.getProjectCode());
    } else {
        scheduleService.suspendJobCron(jobUuid, suspend, projectUser.getProjectCode());
    }
    return ResponseData.success();
}