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

The following examples show how to use org.springframework.web.context.request.ServletWebRequest. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Before
public void setup() throws Exception {
	container = new ModelAndViewContainer();
	servletRequest = new MockHttpServletRequest();
	servletRequest.setMethod("POST");
	servletResponse = new MockHttpServletResponse();
	request = new ServletWebRequest(servletRequest, servletResponse);
	this.factory = new ValidatingBinderFactory();

	Method method = getClass().getDeclaredMethod("handle",
			List.class, SimpleBean.class, MultiValueMap.class, String.class);
	paramGenericList = new MethodParameter(method, 0);
	paramSimpleBean = new MethodParameter(method, 1);
	paramMultiValueMap = new MethodParameter(method, 2);
	paramString = new MethodParameter(method, 3);
	returnTypeString = new MethodParameter(method, -1);
}
 
Example 2
@Test
public void testFieldPrefixCausesFieldResetWithIgnoreUnknownFields() throws Exception {
	TestBean target = new TestBean();
	WebRequestDataBinder binder = new WebRequestDataBinder(target);
	binder.setIgnoreUnknownFields(false);

	MockHttpServletRequest request = new MockHttpServletRequest();
	request.addParameter("_postProcessed", "visible");
	request.addParameter("postProcessed", "on");
	binder.bind(new ServletWebRequest(request));
	assertTrue(target.isPostProcessed());

	request.removeParameter("postProcessed");
	binder.bind(new ServletWebRequest(request));
	assertFalse(target.isPostProcessed());
}
 
Example 3
Source Project: spring-analysis-note   Source File: WebRequestDataBinderTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testWithCommaSeparatedStringArray() throws Exception {
	TestBean target = new TestBean();
	WebRequestDataBinder binder = new WebRequestDataBinder(target);

	MockHttpServletRequest request = new MockHttpServletRequest();
	request.addParameter("stringArray", "bar");
	request.addParameter("stringArray", "abc");
	request.addParameter("stringArray", "123,def");
	binder.bind(new ServletWebRequest(request));
	assertEquals("Expected all three items to be bound", 3, target.getStringArray().length);

	request.removeParameter("stringArray");
	request.addParameter("stringArray", "123,def");
	binder.bind(new ServletWebRequest(request));
	assertEquals("Expected only 1 item to be bound", 1, target.getStringArray().length);
}
 
Example 4
/**
 * Customize the response for NoHandlerFoundException.
 * <p>This method delegates to {@link #handleExceptionInternal}.
 * @param ex the exception
 * @param headers the headers to be written to the response
 * @param status the selected response status
 * @param webRequest the current request
 * @return a {@code ResponseEntity} instance
 * @since 4.2.8
 */
@Nullable
protected ResponseEntity<Object> handleAsyncRequestTimeoutException(
		AsyncRequestTimeoutException ex, HttpHeaders headers, HttpStatus status, WebRequest webRequest) {

	if (webRequest instanceof ServletWebRequest) {
		ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest;
		HttpServletResponse response = servletWebRequest.getResponse();
		if (response != null && response.isCommitted()) {
			if (logger.isWarnEnabled()) {
				logger.warn("Async request timed out");
			}
			return null;
		}
	}

	return handleExceptionInternal(ex, null, headers, status, webRequest);
}
 
Example 5
@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 6
@Before
public void setup() throws Exception {
	this.request = new ServletWebRequest(new MockHttpServletRequest());
	this.container = new ModelAndViewContainer();
	this.processor = new ModelAttributeMethodProcessor(false);

	Method method = ModelAttributeHandler.class.getDeclaredMethod("modelAttribute",
			TestBean.class, Errors.class, int.class, TestBean.class,
			TestBean.class, TestBean.class);

	this.paramNamedValidModelAttr = new SynthesizingMethodParameter(method, 0);
	this.paramErrors = new SynthesizingMethodParameter(method, 1);
	this.paramInt = new SynthesizingMethodParameter(method, 2);
	this.paramModelAttr = new SynthesizingMethodParameter(method, 3);
	this.paramBindingDisabledAttr = new SynthesizingMethodParameter(method, 4);
	this.paramNonSimpleType = new SynthesizingMethodParameter(method, 5);

	method = getClass().getDeclaredMethod("annotatedReturnValue");
	this.returnParamNamedModelAttr = new MethodParameter(method, -1);

	method = getClass().getDeclaredMethod("notAnnotatedReturnValue");
	this.returnParamNonSimpleType = new MethodParameter(method, -1);
}
 
Example 7
@Before
public void setUp() throws Exception {
	this.resolver = new MatrixVariableMethodArgumentResolver();

	Method method = getClass().getMethod("handle", String.class, List.class, int.class);
	this.paramString = new MethodParameter(method, 0);
	this.paramColors = new MethodParameter(method, 1);
	this.paramYear = new MethodParameter(method, 2);

	this.paramColors.initParameterNameDiscovery(new LocalVariableTableParameterNameDiscoverer());

	this.mavContainer = new ModelAndViewContainer();
	this.request = new MockHttpServletRequest();
	this.webRequest = new ServletWebRequest(request, new MockHttpServletResponse());

	Map<String, MultiValueMap<String, String>> params = new LinkedHashMap<String, MultiValueMap<String, String>>();
	this.request.setAttribute(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE, params);
}
 
Example 8
@Test
void resolveArgument_notificationMessageTypeWithSubject_reportsErrors()
		throws Exception {
	// Arrange
	NotificationSubjectHandlerMethodArgumentResolver resolver = new NotificationSubjectHandlerMethodArgumentResolver();

	byte[] subscriptionRequestJsonContent = FileCopyUtils.copyToByteArray(
			new ClassPathResource("notificationMessage.json", getClass())
					.getInputStream());
	MockHttpServletRequest servletRequest = new MockHttpServletRequest();
	servletRequest.setContent(subscriptionRequestJsonContent);

	MethodParameter methodParameter = new MethodParameter(
			ReflectionUtils.findMethod(NotificationMethods.class,
					"subscriptionMethod", NotificationStatus.class),
			0);

	// Act
	Object argument = resolver.resolveArgument(methodParameter, null,
			new ServletWebRequest(servletRequest), null);

	// Assert
	assertThat(argument).isEqualTo("asdasd");
}
 
Example 9
@Override
public ModelAndView writeTo(HttpServletRequest request, HttpServletResponse response,
		Context context) throws ServletException, IOException {

	try {
		writeStatusAndHeaders(response);

		long lastModified = headers().getLastModified();
		ServletWebRequest servletWebRequest = new ServletWebRequest(request, response);
		HttpMethod httpMethod = HttpMethod.resolve(request.getMethod());
		if (SAFE_METHODS.contains(httpMethod) &&
				servletWebRequest.checkNotModified(headers().getETag(), lastModified)) {
			return null;
		}
		else {
			return writeToInternal(request, response, context);
		}
	}
	catch (Throwable throwable) {
		return handleError(throwable, request, response, context);
	}
}
 
Example 10
@Test
@SuppressWarnings("unchecked")
public void resolveMultiValueMapOfPart() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setContentType("multipart/form-data");
	Part expected1 = new MockPart("mfilelist", "Hello World 1".getBytes());
	Part expected2 = new MockPart("mfilelist", "Hello World 2".getBytes());
	Part expected3 = new MockPart("other", "Hello World 3".getBytes());
	request.addPart(expected1);
	request.addPart(expected2);
	request.addPart(expected3);
	webRequest = new ServletWebRequest(request);

	MethodParameter param = this.testMethod.annot(requestParam().noName()).arg(MultiValueMap.class, String.class, Part.class);
	Object result = resolver.resolveArgument(param, null, webRequest, null);

	assertTrue(result instanceof MultiValueMap);
	MultiValueMap<String, Part> resultMap = (MultiValueMap<String, Part>) result;
	assertEquals(2, resultMap.size());
	assertEquals(2, resultMap.get("mfilelist").size());
	assertEquals(expected1, resultMap.get("mfilelist").get(0));
	assertEquals(expected2, resultMap.get("mfilelist").get(1));
	assertEquals(1, resultMap.get("other").size());
	assertEquals(expected3, resultMap.get("other").get(0));
}
 
Example 11
private void handleHttpEntityResponse(HttpEntity<?> responseEntity, ServletWebRequest webRequest) throws Exception {
	if (responseEntity == null) {
		return;
	}
	HttpInputMessage inputMessage = createHttpInputMessage(webRequest);
	HttpOutputMessage outputMessage = createHttpOutputMessage(webRequest);
	if (responseEntity instanceof ResponseEntity && outputMessage instanceof ServerHttpResponse) {
		((ServerHttpResponse) outputMessage).setStatusCode(((ResponseEntity<?>) responseEntity).getStatusCode());
	}
	HttpHeaders entityHeaders = responseEntity.getHeaders();
	if (!entityHeaders.isEmpty()) {
		outputMessage.getHeaders().putAll(entityHeaders);
	}
	Object body = responseEntity.getBody();
	if (body != null) {
		writeWithMessageConverters(body, inputMessage, outputMessage);
	}
	else {
		// flush headers
		outputMessage.getBody();
	}
}
 
Example 12
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    if (requestMatcher.matches(request)){
        String grantType = getGrantType(request);
        if ("sms".equalsIgnoreCase(grantType) || "email".equalsIgnoreCase(grantType)){
            try {
                log.info("请求需要验证!验证请求:" + request.getRequestURI() + " 验证类型:" + grantType);
                validateCodeProcessorHolder.findValidateCodeProcessor(grantType)
                        .validate(new ServletWebRequest(request, response));
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
        }
    }
    filterChain.doFilter(request, response);
}
 
Example 13
@Test
@SuppressWarnings("unchecked")
public void resolveMapOfPart() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setContentType("multipart/form-data");
	Part expected1 = new MockPart("mfile", "Hello World".getBytes());
	Part expected2 = new MockPart("other", "Hello World 3".getBytes());
	request.addPart(expected1);
	request.addPart(expected2);
	webRequest = new ServletWebRequest(request);

	MethodParameter param = this.testMethod.annot(requestParam().noName()).arg(Map.class, String.class, Part.class);
	Object result = resolver.resolveArgument(param, null, webRequest, null);

	assertTrue(result instanceof Map);
	Map<String, Part> resultMap = (Map<String, Part>) result;
	assertEquals(2, resultMap.size());
	assertEquals(expected1, resultMap.get("mfile"));
	assertEquals(expected2, resultMap.get("other"));
}
 
Example 14
Source Project: FEBS-Security   Source File: SmsCodeFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

    boolean match = false;
    for (String u : url) {
        if (pathMatcher.match(u, httpServletRequest.getRequestURI())) {
            match = true;
        }
    }
    if (match) {
        try {
            validateSmsCode(new ServletWebRequest(httpServletRequest));
        } catch (ValidateCodeException e) {
            authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
            return;
        }
    }
    filterChain.doFilter(httpServletRequest, httpServletResponse);
}
 
Example 15
Source Project: SpringAll   Source File: SmsCodeFilter.java    License: MIT License 6 votes vote down vote up
private void validateCode(ServletWebRequest servletWebRequest) throws ServletRequestBindingException {
    String smsCodeInRequest = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(), "smsCode");
    String mobileInRequest = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(), "smsCode");

    SmsCode codeInSession = (SmsCode) sessionStrategy.getAttribute(servletWebRequest, ValidateController.SESSION_KEY_SMS_CODE + mobileInRequest);

    if (StringUtils.isBlank(smsCodeInRequest)) {
        throw new ValidateCodeException("验证码不能为空!");
    }
    if (codeInSession == null) {
        throw new ValidateCodeException("验证码不存在!");
    }
    if (codeInSession.isExpire()) {
        sessionStrategy.removeAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);
        throw new ValidateCodeException("验证码已过期!");
    }
    if (!StringUtils.equalsIgnoreCase(codeInSession.getCode(), smsCodeInRequest)) {
        throw new ValidateCodeException("验证码不正确!");
    }
    sessionStrategy.removeAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);

}
 
Example 16
Source Project: SpringAll   Source File: ValidateCodeFilter.java    License: MIT License 6 votes vote down vote up
private void validateCode(ServletWebRequest servletWebRequest) throws ServletRequestBindingException {
    ImageCode codeInSession = (ImageCode) sessionStrategy.getAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);
    String codeInRequest = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(), "imageCode");

    if (StringUtils.isBlank(codeInRequest)) {
        throw new ValidateCodeException("验证码不能为空!");
    }
    if (codeInSession == null) {
        throw new ValidateCodeException("验证码不存在!");
    }
    if (codeInSession.isExpire()) {
        sessionStrategy.removeAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);
        throw new ValidateCodeException("验证码已过期!");
    }
    if (!StringUtils.equalsIgnoreCase(codeInSession.getCode(), codeInRequest)) {
        throw new ValidateCodeException("验证码不正确!");
    }
    sessionStrategy.removeAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);

}
 
Example 17
@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 18
private void handleHttpEntityResponse(HttpEntity<?> responseEntity, ServletWebRequest webRequest) throws Exception {
	if (responseEntity == null) {
		return;
	}
	HttpInputMessage inputMessage = createHttpInputMessage(webRequest);
	HttpOutputMessage outputMessage = createHttpOutputMessage(webRequest);
	if (responseEntity instanceof ResponseEntity && outputMessage instanceof ServerHttpResponse) {
		((ServerHttpResponse) outputMessage).setStatusCode(((ResponseEntity<?>) responseEntity).getStatusCode());
	}
	HttpHeaders entityHeaders = responseEntity.getHeaders();
	if (!entityHeaders.isEmpty()) {
		outputMessage.getHeaders().putAll(entityHeaders);
	}
	Object body = responseEntity.getBody();
	if (body != null) {
		writeWithMessageConverters(body, inputMessage, outputMessage);
	}
	else {
		// flush headers
		outputMessage.getBody();
	}
}
 
Example 19
@Test
@SuppressWarnings("unchecked")
public void resolveMultiValueMapOfMultipartFile() throws Exception {
	MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
	MultipartFile expected1 = new MockMultipartFile("mfilelist", "Hello World 1".getBytes());
	MultipartFile expected2 = new MockMultipartFile("mfilelist", "Hello World 2".getBytes());
	MultipartFile expected3 = new MockMultipartFile("other", "Hello World 3".getBytes());
	request.addFile(expected1);
	request.addFile(expected2);
	request.addFile(expected3);
	webRequest = new ServletWebRequest(request);

	MethodParameter param = this.testMethod.annot(requestParam().noName()).arg(MultiValueMap.class, String.class, MultipartFile.class);
	Object result = resolver.resolveArgument(param, null, webRequest, null);

	assertTrue(result instanceof MultiValueMap);
	MultiValueMap<String, MultipartFile> resultMap = (MultiValueMap<String, MultipartFile>) result;
	assertEquals(2, resultMap.size());
	assertEquals(2, resultMap.get("mfilelist").size());
	assertEquals(expected1, resultMap.get("mfilelist").get(0));
	assertEquals(expected2, resultMap.get("mfilelist").get(1));
	assertEquals(1, resultMap.get("other").size());
	assertEquals(expected3, resultMap.get("other").get(0));
}
 
Example 20
@Test
@SuppressWarnings("unchecked")
public void resolveMultiValueMapOfPart() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setContentType("multipart/form-data");
	Part expected1 = new MockPart("mfilelist", "Hello World 1".getBytes());
	Part expected2 = new MockPart("mfilelist", "Hello World 2".getBytes());
	Part expected3 = new MockPart("other", "Hello World 3".getBytes());
	request.addPart(expected1);
	request.addPart(expected2);
	request.addPart(expected3);
	webRequest = new ServletWebRequest(request);

	MethodParameter param = this.testMethod.annot(requestParam().noName()).arg(MultiValueMap.class, String.class, Part.class);
	Object result = resolver.resolveArgument(param, null, webRequest, null);

	assertTrue(result instanceof MultiValueMap);
	MultiValueMap<String, Part> resultMap = (MultiValueMap<String, Part>) result;
	assertEquals(2, resultMap.size());
	assertEquals(2, resultMap.get("mfilelist").size());
	assertEquals(expected1, resultMap.get("mfilelist").get(0));
	assertEquals(expected2, resultMap.get("mfilelist").get(1));
	assertEquals(1, resultMap.get("other").size());
	assertEquals(expected3, resultMap.get("other").get(0));
}
 
Example 21
@Test
@SuppressWarnings("unchecked")
public void resolveMultiValueMapOfMultipartFile() throws Exception {
	MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
	MultipartFile expected1 = new MockMultipartFile("mfilelist", "Hello World 1".getBytes());
	MultipartFile expected2 = new MockMultipartFile("mfilelist", "Hello World 2".getBytes());
	MultipartFile expected3 = new MockMultipartFile("other", "Hello World 3".getBytes());
	request.addFile(expected1);
	request.addFile(expected2);
	request.addFile(expected3);
	webRequest = new ServletWebRequest(request);

	MethodParameter param = this.testMethod.annot(requestParam().noName()).arg(MultiValueMap.class, String.class, MultipartFile.class);
	Object result = resolver.resolveArgument(param, null, webRequest, null);

	assertTrue(result instanceof MultiValueMap);
	MultiValueMap<String, MultipartFile> resultMap = (MultiValueMap<String, MultipartFile>) result;
	assertEquals(2, resultMap.size());
	assertEquals(2, resultMap.get("mfilelist").size());
	assertEquals(expected1, resultMap.get("mfilelist").get(0));
	assertEquals(expected2, resultMap.get("mfilelist").get(1));
	assertEquals(1, resultMap.get("other").size());
	assertEquals(expected3, resultMap.get("other").get(0));
}
 
Example 22
@Before
public void setup() throws Exception {
	this.resolver = new UriComponentsBuilderMethodArgumentResolver();
	this.servletRequest = new MockHttpServletRequest();
	this.webRequest = new ServletWebRequest(this.servletRequest);

	Method method = this.getClass().getDeclaredMethod(
			"handle", UriComponentsBuilder.class, ServletUriComponentsBuilder.class, int.class);
	this.builderParam = new MethodParameter(method, 0);
	this.servletBuilderParam = new MethodParameter(method, 1);
	this.intParam = new MethodParameter(method, 2);
}
 
Example 23
Source Project: SpringAll   Source File: SmsCodeFilter.java    License: MIT License 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
    if (StringUtils.equalsIgnoreCase("/login/mobile", httpServletRequest.getRequestURI())
            && StringUtils.equalsIgnoreCase(httpServletRequest.getMethod(), "post")) {
        try {
            validateCode(new ServletWebRequest(httpServletRequest));
        } catch (ValidateCodeException e) {
            authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
            return;
        }
    }
    filterChain.doFilter(httpServletRequest, httpServletResponse);
}
 
Example 24
/**
 * 校验验证码实现
 * @param bodyString 请求体
 */
@SuppressWarnings("unchecked")
@Override
public void validate(ServletWebRequest request, String bodyString) {

	ValidateCodeType codeType = getValidateCodeType(request);

	C codeInSession = (C) validateCodeRepository.get(request, codeType);

	String codeInRequest;

	Map<String, Object> map = JsonUtil.jsonToMap(bodyString);
	codeInRequest = map.get(codeType.getParamNameOnValidate())+"";

	if (StringUtils.isBlank(codeInRequest)) {
		throw new ValidateCodeException(codeType + "验证码的值不能为空");
	}

	if (codeInSession == null) {
		throw new ValidateCodeException(codeType + "验证码不存在");
	}

	if (codeInSession.isExpried()) {
		validateCodeRepository.remove(request, codeType);
		throw new ValidateCodeException(codeType + "验证码已过期");
	}

	if (!StringUtils.equals(codeInSession.getCode(), codeInRequest)) {
		throw new ValidateCodeException(codeType + "验证码不匹配");
	}
	
	validateCodeRepository.remove(request, codeType);
	
}
 
Example 25
Source Project: fw-spring-cloud   Source File: ValidateCodeServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ImageCode generate(ServletWebRequest request) {
	int width = ServletRequestUtils.getIntParameter(request.getRequest(), "width",
			securityProperties.getCode().getImage().getWidth());
	int height = ServletRequestUtils.getIntParameter(request.getRequest(), "height",
			securityProperties.getCode().getImage().getHeight());
	BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

	Graphics g = image.getGraphics();

	Random random = new Random();

	g.setColor(getRandColor(200, 250));
	g.fillRect(0, 0, width, height);
	g.setFont(new Font("Times New Roman", Font.ITALIC, 20));
	g.setColor(getRandColor(160, 200));
	for (int i = 0; i < 155; i++) {
		int x = random.nextInt(width);
		int y = random.nextInt(height);
		int xl = random.nextInt(12);
		int yl = random.nextInt(12);
		g.drawLine(x, y, x + xl, y + yl);
	}

	String sRand = "";
	for (int i = 0; i < securityProperties.getCode().getImage().getLength(); i++) {
		String rand = String.valueOf(random.nextInt(10));
		sRand += rand;
		g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
		g.drawString(rand, 13 * i + 6, 16);
	}

	g.dispose();

	return new ImageCode(image, sRand, securityProperties.getCode().getImage().getExpireIn());
}
 
Example 26
Source Project: SpringAll   Source File: ValidateCodeFilter.java    License: MIT License 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
    if (StringUtils.equalsIgnoreCase("/login", httpServletRequest.getRequestURI())
            && StringUtils.equalsIgnoreCase(httpServletRequest.getMethod(), "post")) {
        try {
            validateCode(new ServletWebRequest(httpServletRequest));
        } catch (ValidateCodeException e) {
            authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
            return;
        }
    }
    filterChain.doFilter(httpServletRequest, httpServletResponse);
}
 
Example 27
Source Project: SpringAll   Source File: ValidateController.java    License: MIT License 5 votes vote down vote up
@GetMapping("/code/image")
public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
    ImageCode imageCode = createImageCode();
    ImageCode codeInRedis = new ImageCode(null,imageCode.getCode(),imageCode.getExpireTime());
    sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY_IMAGE_CODE, codeInRedis);
    ImageIO.write(imageCode.getImage(), "jpeg", response.getOutputStream());
}
 
Example 28
private boolean isResourceNotModified(ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage) {
	ServletWebRequest servletWebRequest =
			new ServletWebRequest(inputMessage.getServletRequest(), outputMessage.getServletResponse());
	HttpHeaders responseHeaders = outputMessage.getHeaders();
	String etag = responseHeaders.getETag();
	long lastModifiedTimestamp = responseHeaders.getLastModified();
	if (inputMessage.getMethod() == HttpMethod.GET || inputMessage.getMethod() == HttpMethod.HEAD) {
		responseHeaders.remove(HttpHeaders.ETAG);
		responseHeaders.remove(HttpHeaders.LAST_MODIFIED);
	}

	return servletWebRequest.checkNotModified(etag, lastModifiedTimestamp);
}
 
Example 29
Source Project: spring-cloud-config   Source File: ResourceController.java    License: Apache License 2.0 5 votes vote down vote up
private String getFilePath(ServletWebRequest request, String name, String profile,
		String label) {
	String stem;
	if (label != null) {
		stem = String.format("/%s/%s/%s/", name, profile, label);
	}
	else {
		stem = String.format("/%s/%s/", name, profile);
	}
	String path = this.helper.getPathWithinApplication(request.getRequest());
	path = path.substring(path.indexOf(stem) + stem.length());
	return path;
}
 
Example 30
@Test
public void testMultipartFileAsStringArray() {
	TestBean target = new TestBean();
	WebRequestDataBinder binder = new WebRequestDataBinder(target);
	binder.registerCustomEditor(String.class, new StringMultipartFileEditor());

	MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
	request.addFile(new MockMultipartFile("stringArray", "Juergen".getBytes()));
	binder.bind(new ServletWebRequest(request));
	assertEquals(1, target.getStringArray().length);
	assertEquals("Juergen", target.getStringArray()[0]);
}