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

项目:Code4Health-Platform    文件:CustomSignInAdapter.java   
@Override
public String signIn(String userId, Connection<?> connection, NativeWebRequest request){
    try {
        UserDetails user = userDetailsService.loadUserByUsername(userId);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
            user,
            null,
            user.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String jwt = tokenProvider.createToken(authenticationToken, false);
        ServletWebRequest servletWebRequest = (ServletWebRequest) request;
        servletWebRequest.getResponse().addCookie(getSocialAuthenticationCookie(jwt));
    } catch (AuthenticationException exception) {
        log.error("Social authentication error");
    }
    return jHipsterProperties.getSocial().getRedirectAfterSignIn();
}
项目:spring-io    文件:CustomSignInAdapter.java   
@Override
public String signIn(String userId, Connection<?> connection, NativeWebRequest request){
    try {
        UserDetails user = userDetailsService.loadUserByUsername(userId);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
            user,
            null,
            user.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String jwt = tokenProvider.createToken(authenticationToken, false);
        ServletWebRequest servletWebRequest = (ServletWebRequest) request;
        servletWebRequest.getResponse().addCookie(getSocialAuthenticationCookie(jwt));
    } catch (AuthenticationException ae) {
        log.error("Social authentication error");
        log.trace("Authentication exception trace: {}", ae);
    }
    return jHipsterProperties.getSocial().getRedirectAfterSignIn();
}
项目:tokamak    文件:RestExceptionRenderer.java   
public 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 {
        outputMessage.getBody();
    }
}
项目:spring4-understanding    文件:AnnotationMethodHandlerExceptionResolver.java   
@Override
protected ModelAndView doResolveException(
        HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    if (handler != null) {
        Method handlerMethod = findBestExceptionHandlerMethod(handler, ex);
        if (handlerMethod != null) {
            ServletWebRequest webRequest = new ServletWebRequest(request, response);
            try {
                Object[] args = resolveHandlerArguments(handlerMethod, handler, webRequest, ex);
                if (logger.isDebugEnabled()) {
                    logger.debug("Invoking request handler method: " + handlerMethod);
                }
                Object retVal = doInvokeMethod(handlerMethod, handler, args);
                return getModelAndView(handlerMethod, retVal, webRequest);
            }
            catch (Exception invocationEx) {
                logger.error("Invoking request method resulted in exception : " + handlerMethod, invocationEx);
            }
        }
    }
    return null;
}
项目:commons-rules    文件:RestExceptionHandler.java   
protected ModelAndView handleCustomException(HttpServletRequest request, HttpServletResponse response, Exception ex) {
    ServletWebRequest webRequest = new ServletWebRequest(request, response);

    RestError error = errorResolver.resolveError(ex);
    if (error == null) {
        return null;
    }
    applyStatusIfPossible(webRequest, error.getHttpStatus());

    try {
        return handleResponseBody(error.getErrorRS(), webRequest);
    } catch (IOException e) {
        if (logger.isWarnEnabled()) {
            logger.warn("Unable to write error message", e);
        }
        return null;
    }
}
项目:Thesis-JHipster    文件:_CustomSignInAdapter.java   
@Override
public String signIn(String userId, Connection<?> connection, NativeWebRequest request){
    try {
        UserDetails user = userDetailsService.loadUserByUsername(userId);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
            user,
            null,
            user.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String jwt = tokenProvider.createToken(authenticationToken, false);
        ServletWebRequest servletWebRequest = (ServletWebRequest) request;
        servletWebRequest.getResponse().addCookie(getSocialAuthenticationCookie(jwt));
    } catch (AuthenticationException exception) {
        log.error("Social authentication error");
    }
    return jHipsterProperties.getSocial().getRedirectAfterSignIn();
}
项目:spring4-understanding    文件:MatrixVariablesMethodArgumentResolverTests.java   
@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);
}
项目:spring4-understanding    文件:RequestMappingHandlerAdapterIntegrationTests.java   
@Before
public void setup() throws Exception {
    ConfigurableWebBindingInitializer bindingInitializer = new ConfigurableWebBindingInitializer();
    bindingInitializer.setValidator(new StubValidator());

    List<HandlerMethodArgumentResolver> customResolvers = new ArrayList<HandlerMethodArgumentResolver>();
    customResolvers.add(new ServletWebArgumentResolverAdapter(new ColorArgumentResolver()));

    GenericWebApplicationContext context = new GenericWebApplicationContext();
    context.refresh();

    handlerAdapter = new RequestMappingHandlerAdapter();
    handlerAdapter.setWebBindingInitializer(bindingInitializer);
    handlerAdapter.setCustomArgumentResolvers(customResolvers);
    handlerAdapter.setApplicationContext(context);
    handlerAdapter.setBeanFactory(context.getBeanFactory());
    handlerAdapter.afterPropertiesSet();

    request = new MockHttpServletRequest();
    response = new MockHttpServletResponse();

    request.setMethod("POST");

    // Expose request to the current thread (for SpEL expressions)
    RequestContextHolder.setRequestAttributes(new ServletWebRequest(request));
}
项目:spring4-understanding    文件:ResponseBodyEmitterReturnValueHandlerTests.java   
@Before
public void setUp() throws Exception {

    List<HttpMessageConverter<?>> converters = Arrays.asList(
            new StringHttpMessageConverter(), new MappingJackson2HttpMessageConverter());

    this.handler = new ResponseBodyEmitterReturnValueHandler(converters);
    this.mavContainer = new ModelAndViewContainer();

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

    AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response);
    WebAsyncUtils.getAsyncManager(this.webRequest).setAsyncWebRequest(asyncWebRequest);
    this.request.setAsyncSupported(true);
}
项目:spring4-understanding    文件:RequestResponseBodyMethodProcessorMockTests.java   
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
    messageConverter = mock(HttpMessageConverter.class);
    given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));

    processor = new RequestResponseBodyMethodProcessor(Collections.<HttpMessageConverter<?>>singletonList(messageConverter));

    Method methodHandle1 = getClass().getMethod("handle1", String.class, Integer.TYPE);
    paramRequestBodyString = new MethodParameter(methodHandle1, 0);
    paramInt = new MethodParameter(methodHandle1, 1);
    returnTypeString = new MethodParameter(methodHandle1, -1);
    returnTypeInt = new MethodParameter(getClass().getMethod("handle2"), -1);
    returnTypeStringProduces = new MethodParameter(getClass().getMethod("handle3"), -1);
    paramValidBean = new MethodParameter(getClass().getMethod("handle4", SimpleBean.class), 0);
    paramStringNotRequired = new MethodParameter(getClass().getMethod("handle5", String.class), 0);

    mavContainer = new ModelAndViewContainer();

    servletRequest = new MockHttpServletRequest();
    servletRequest.setMethod("POST");
    webRequest = new ServletWebRequest(servletRequest, new MockHttpServletResponse());
}
项目:spring4-understanding    文件:CustomRequestAttributesRequestContextHolderTests.java   
@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();
}
项目:unity    文件:DefaultSocialAuthenticationService.java   
@Override
public RedirectView authenticate(final WebRequest request) {
    try {
        final Connection<?> connection = providerSignInUtils.getConnectionFromSession(request);

        final User user = socialUserService.create(connection);

        final String jwt = tokenService.getToken(user.getUsername(), user.getPassword());

        final ServletWebRequest servletWebRequest = (ServletWebRequest) request;

        servletWebRequest.getResponse().addCookie(getSocialAuthenticationCookie(jwt));

        return new RedirectView(URIBuilder.fromUri(redirectUrl)
                .build().toString(), true);
    } catch (Exception e) {
        return new RedirectView(URIBuilder.fromUri(redirectUrl)
                .queryParam("success", "false")
                .build().toString(), true);
    }
}
项目:spring4-understanding    文件:RequestResponseBodyMethodProcessorTests.java   
private void assertContentDisposition(RequestResponseBodyMethodProcessor processor,
        boolean expectContentDisposition, String requestURI, String comment) throws Exception {

    this.servletRequest.setRequestURI(requestURI);
    processor.handleReturnValue("body", this.returnTypeString, this.mavContainer, this.webRequest);

    String header = servletResponse.getHeader("Content-Disposition");
    if (expectContentDisposition) {
        assertEquals("Expected 'Content-Disposition' header. Use case: '" + comment + "'",
                "inline;filename=f.txt", header);
    }
    else {
        assertNull("Did not expect 'Content-Disposition' header. Use case: '" + comment + "'", header);
    }

    this.servletRequest = new MockHttpServletRequest();
    this.servletResponse = new MockHttpServletResponse();
    this.webRequest = new ServletWebRequest(servletRequest, servletResponse);
}
项目:spring-cloud-gateway    文件:ProxyExchange.java   
@Override
public ServletInputStream getInputStream() throws IOException {
    Object body = body();
    MethodParameter output = new MethodParameter(
            ClassUtils.getMethod(BodySender.class, "body"), -1);
    ServletOutputToInputConverter response = new ServletOutputToInputConverter(
            this.response);
    ServletWebRequest webRequest = new ServletWebRequest(this.request, response);
    try {
        delegate.handleReturnValue(body, output, mavContainer, webRequest);
    }
    catch (HttpMessageNotWritableException
            | HttpMediaTypeNotAcceptableException e) {
        throw new IllegalStateException("Cannot convert body", e);
    }
    return response.getInputStream();
}
项目:spring4-understanding    文件:MvcNamespaceTests.java   
@Test
public void testContentNegotiationManager() throws Exception {
    loadBeanDefinitions("mvc-config-content-negotiation-manager.xml", 15);

    RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
    ContentNegotiationManager manager = mapping.getContentNegotiationManager();

    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo.xml");
    NativeWebRequest webRequest = new ServletWebRequest(request);
    assertEquals(Arrays.asList(MediaType.valueOf("application/rss+xml")), manager.resolveMediaTypes(webRequest));

    ViewResolverComposite compositeResolver = this.appContext.getBean(ViewResolverComposite.class);
    assertNotNull(compositeResolver);
    assertEquals("Actual: " + compositeResolver.getViewResolvers(), 1, compositeResolver.getViewResolvers().size());

    ViewResolver resolver = compositeResolver.getViewResolvers().get(0);
    assertEquals(ContentNegotiatingViewResolver.class, resolver.getClass());
    ContentNegotiatingViewResolver cnvr = (ContentNegotiatingViewResolver) resolver;
    assertSame(manager, cnvr.getContentNegotiationManager());
}
项目:spring4-understanding    文件:ModelAttributeMethodProcessorTests.java   
@Before
public void setUp() throws Exception {
    processor = new ModelAttributeMethodProcessor(false);

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

    paramNamedValidModelAttr = new MethodParameter(method, 0);
    paramErrors = new MethodParameter(method, 1);
    paramInt = new MethodParameter(method, 2);
    paramModelAttr = new MethodParameter(method, 3);
    paramNonSimpleType = new MethodParameter(method, 4);

    returnParamNamedModelAttr = new MethodParameter(getClass().getDeclaredMethod("annotatedReturnValue"), -1);
    returnParamNonSimpleType = new MethodParameter(getClass().getDeclaredMethod("notAnnotatedReturnValue"), -1);

    mavContainer = new ModelAndViewContainer();

    webRequest = new ServletWebRequest(new MockHttpServletRequest());
}
项目:unity    文件:SocialSignInAdapterTest.java   
public void signIn_Success() throws Exception {
    final UserDetails user = createUser();
    final String token = "token";

    final HttpServletRequest servletRequest = mock(HttpServletRequest.class);
    final HttpServletResponse servletResponse = mock(HttpServletResponse.class);

    final ServletWebRequest request = new ServletWebRequest(servletRequest, servletResponse);

    doReturn(user).when(userDetailsService).loadUserByUsername(user.getUsername());
    doReturn(token).when(tokenService).getToken(user.getUsername(), user.getPassword());

    socialSignInAdapter.signIn(user.getUsername(), null, request);

    verify(servletResponse).addCookie(captor.capture());
    assertThat(captor.getValue().getName(), equalTo(SOCIAL_AUTHENTICATION_COOKIE_NAME));
    assertThat(captor.getValue().getValue(), equalTo(token));
}
项目:spring4-understanding    文件:RequestParamMethodArgumentResolverTests.java   
@Test
public void resolvePartList() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockPart expected1 = new MockPart("pfilelist", "Hello World 1".getBytes());
    MockPart expected2 = new MockPart("pfilelist", "Hello World 2".getBytes());
    request.setMethod("POST");
    request.setContentType("multipart/form-data");
    request.addPart(expected1);
    request.addPart(expected2);
    webRequest = new ServletWebRequest(request);

    Object result = resolver.resolveArgument(paramPartList, null, webRequest, null);

    assertTrue(result instanceof List);
    assertEquals(Arrays.asList(expected1, expected2), result);
}
项目:spring4-understanding    文件:RequestParamMethodArgumentResolverTests.java   
@Test
public void resolvePartArray() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockPart expected1 = new MockPart("pfilearray", "Hello World 1".getBytes());
    MockPart expected2 = new MockPart("pfilearray", "Hello World 2".getBytes());
    request.setMethod("POST");
    request.setContentType("multipart/form-data");
    request.addPart(expected1);
    request.addPart(expected2);
    webRequest = new ServletWebRequest(request);

    Object result = resolver.resolveArgument(paramPartArray, null, webRequest, null);

    assertTrue(result instanceof Part[]);
    Part[] parts = (Part[]) result;
    assertEquals(parts[0], expected1);
    assertEquals(parts[1], expected2);
}
项目:spring4-understanding    文件:WebRequestDataBinderTests.java   
@Test
public void testBindingWithNestedObjectCreation() throws Exception {
    TestBean tb = new TestBean();

    WebRequestDataBinder binder = new WebRequestDataBinder(tb, "person");
    binder.registerCustomEditor(ITestBean.class, new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            setValue(new TestBean());
        }
    });

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter("spouse", "someValue");
    request.addParameter("spouse.name", "test");
    binder.bind(new ServletWebRequest(request));

    assertNotNull(tb.getSpouse());
    assertEquals("test", tb.getSpouse().getName());
}
项目:spring4-understanding    文件:WebRequestDataBinderTests.java   
@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());
}
项目:spring4-understanding    文件:WebRequestDataBinderTests.java   
@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);
}
项目:burpextender-proxyhistory-webui    文件:JdbcConnectionInterceptor.java   
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
    ServletWebRequest wr = new ServletWebRequest(req);
    ServletContext sctx = req.getServletContext();
    String dbname = (String) sctx.getAttribute("dbname");
    Connection dbconn = (Connection) wr.getAttribute("dbconn", WebRequest.SCOPE_REQUEST);
    if (Objects.isNull(dbconn) && !Strings.isEmpty(dbname)) {
        dbconn = DataStore.getConnection(dbname);
        wr.setAttribute("dbconn", dbconn, WebRequest.SCOPE_REQUEST);
    }
    return super.preHandle(req, res, handler);
}
项目:burpextender-proxyhistory-webui    文件:JdbcConnectionInterceptor.java   
@Override
public void postHandle(HttpServletRequest req, HttpServletResponse res, Object handler, ModelAndView mav)
        throws Exception {
    // postHandle()はcontroller内で例外が発生しても呼ばれるので安心。
    // ただしこの後にviewが呼ばれるので、viewの中からはDB接続使えないようにしておく、という意図はある。
    ServletWebRequest wr = new ServletWebRequest(req);
    Connection dbconn = (Connection) wr.getAttribute("dbconn", WebRequest.SCOPE_REQUEST);
    DataStore.closeConnection(dbconn);
}
项目:xm-uaa    文件:CustomSignInAdapter.java   
@Override
public String signIn(String userId, Connection<?> connection, NativeWebRequest request) {
    UserDetails user = userDetailsService.loadUserByUsername(connection.fetchUserProfile().getEmail());
    Authentication userAuth = new UsernamePasswordAuthenticationToken(
        user,
        "N/A",
        user.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(userAuth);

    String jwt = createToken(userAuth);
    ((ServletWebRequest) request).getResponse().addCookie(getSocialAuthenticationCookie(jwt));

    return TenantUtil.getApplicationUrl() + "/social-auth";
}
项目:crnk-framework    文件:SpringParameterProvider.java   
@Override
@SuppressWarnings("unchecked")
public <T> T provide(Method method, int parameterIndex) {
    MethodParameter methodParameter = new MethodParameter(method, parameterIndex);
    ModelAndViewContainer modelAndViewContainer = new ModelAndViewContainer();
    NativeWebRequest webRequest = new ServletWebRequest(request);
    DefaultDataBinderFactory binderFactory = new DefaultDataBinderFactory(new ConfigurableWebBindingInitializer());

    try {
        return (T) argumentResolvers.resolveArgument(methodParameter, modelAndViewContainer, webRequest, binderFactory);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}
项目:akir    文件:ErrorController.java   
@RequestMapping("/error")
public Object handleError(HttpServletRequest request) {
    WebRequest req = new ServletWebRequest(request);
    Map<String, Object> attributes = errorAttributes.getErrorAttributes(req, false);
    int code = (int) attributes.get("status");
    if (code == 999)
        throw new AccessDeniedException("Access is denied");
    ErrorMessage msg = new ErrorMessage((String) attributes.get("error"), code, (String) attributes.get("message"));

    String logMsg = MessageFormat.format("ip={1}; session={2}; user={3}; url={4}; {0}",
            msg,
            request.getRemoteAddr(),
            Optional.ofNullable(request.getSession(false)).map(HttpSession::getId).orElse(null),
            UserService.getCurrentAuthentication().map(Authentication::getPrincipal).orElse(null),
            request.getAttribute("javax.servlet.error.request_uri"));
    Throwable ex = errorAttributes.getError(req);
    if (code >= 500 && code <= 599) {
        // it's a server internal error
        LOGGER.warn(logMsg, ex);
    } else {
        LOGGER.debug(logMsg, ex);
    }

    if (isAjax(request)) {
        return msg.toResponseEntity();
    } else {
        ModelAndView view = new ModelAndView("error", msg.getStatus());
        view.addObject("error", msg);
        return view;
    }
}
项目:spring4-understanding    文件:OpenEntityManagerInViewTests.java   
@Before
public void setUp() throws Exception {
    factory = mock(EntityManagerFactory.class);
    manager = mock(EntityManager.class);

    given(factory.createEntityManager()).willReturn(manager);

    this.request = new MockHttpServletRequest();
    this.request.setAsyncSupported(true);
    this.response = new MockHttpServletResponse();
    this.webRequest = new ServletWebRequest(this.request);
}
项目:spring4-understanding    文件:OpenEntityManagerInViewTests.java   
@Test
public void testOpenEntityManagerInViewInterceptor() throws Exception {
    OpenEntityManagerInViewInterceptor interceptor = new OpenEntityManagerInViewInterceptor();
    interceptor.setEntityManagerFactory(this.factory);

    MockServletContext sc = new MockServletContext();
    MockHttpServletRequest request = new MockHttpServletRequest(sc);

    interceptor.preHandle(new ServletWebRequest(request));
    assertTrue(TransactionSynchronizationManager.hasResource(this.factory));

    // check that further invocations simply participate
    interceptor.preHandle(new ServletWebRequest(request));

    interceptor.preHandle(new ServletWebRequest(request));
    interceptor.postHandle(new ServletWebRequest(request), null);
    interceptor.afterCompletion(new ServletWebRequest(request), null);

    interceptor.postHandle(new ServletWebRequest(request), null);
    interceptor.afterCompletion(new ServletWebRequest(request), null);

    interceptor.preHandle(new ServletWebRequest(request));
    interceptor.postHandle(new ServletWebRequest(request), null);
    interceptor.afterCompletion(new ServletWebRequest(request), null);

    interceptor.postHandle(new ServletWebRequest(request), null);
    assertTrue(TransactionSynchronizationManager.hasResource(factory));

    given(manager.isOpen()).willReturn(true);

    interceptor.afterCompletion(new ServletWebRequest(request), null);
    assertFalse(TransactionSynchronizationManager.hasResource(factory));

    verify(manager).close();
}
项目:commons-rules    文件:RestExceptionHandler.java   
@SuppressWarnings({ "rawtypes", "unchecked", "resource" })
private ModelAndView handleResponseBody(Object body, ServletWebRequest webRequest) throws HttpMessageNotWritableException, IOException {

    HttpInputMessage inputMessage = new ServletServerHttpRequest(webRequest.getRequest());

    List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
    if (acceptedMediaTypes.isEmpty()) {
        acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    }

    MediaType.sortByQualityValue(acceptedMediaTypes);

    HttpOutputMessage outputMessage = new ServletServerHttpResponse(webRequest.getResponse());

    Class<?> bodyType = body.getClass();

    List<HttpMessageConverter<?>> converters = this.messageConverters;

    if (converters != null) {
        for (MediaType acceptedMediaType : acceptedMediaTypes) {
            for (HttpMessageConverter messageConverter : converters) {
                if (messageConverter.canWrite(bodyType, acceptedMediaType)) {
                    messageConverter.write(body, acceptedMediaType, outputMessage);
                    // return empty model and view to short circuit the
                    // iteration and to let
                    // Spring know that we've rendered the view ourselves:
                    return new ModelAndView();
                }
            }
        }
    }

    if (logger.isWarnEnabled()) {
        logger.warn("Could not find HttpMessageConverter that supports return type [" + bodyType + "] and " + acceptedMediaTypes);
    }
    return null;
}
项目:spring4-understanding    文件:OpenPersistenceManagerInViewTests.java   
@Test
public void testOpenPersistenceManagerInViewInterceptor() throws Exception {
    PersistenceManagerFactory pmf = mock(PersistenceManagerFactory.class);
    PersistenceManager pm = mock(PersistenceManager.class);

    OpenPersistenceManagerInViewInterceptor interceptor = new OpenPersistenceManagerInViewInterceptor();
    interceptor.setPersistenceManagerFactory(pmf);

    MockServletContext sc = new MockServletContext();
    MockHttpServletRequest request = new MockHttpServletRequest(sc);

    given(pmf.getPersistenceManager()).willReturn(pm);
    interceptor.preHandle(new ServletWebRequest(request));
    assertTrue(TransactionSynchronizationManager.hasResource(pmf));

    // check that further invocations simply participate
    interceptor.preHandle(new ServletWebRequest(request));

    interceptor.preHandle(new ServletWebRequest(request));
    interceptor.postHandle(new ServletWebRequest(request), null);
    interceptor.afterCompletion(new ServletWebRequest(request), null);

    interceptor.postHandle(new ServletWebRequest(request), null);
    interceptor.afterCompletion(new ServletWebRequest(request), null);

    interceptor.preHandle(new ServletWebRequest(request));
    interceptor.postHandle(new ServletWebRequest(request), null);
    interceptor.afterCompletion(new ServletWebRequest(request), null);

    interceptor.postHandle(new ServletWebRequest(request), null);
    assertTrue(TransactionSynchronizationManager.hasResource(pmf));

    interceptor.afterCompletion(new ServletWebRequest(request), null);
    assertFalse(TransactionSynchronizationManager.hasResource(pmf));
}
项目:spring4-understanding    文件:OpenSessionInViewTests.java   
@Before
public void setup() {
    this.sc = new MockServletContext();
    this.request = new MockHttpServletRequest(sc);
    this.request.setAsyncSupported(true);
    this.response = new MockHttpServletResponse();
    this.webRequest = new ServletWebRequest(this.request);
}
项目:spring4-understanding    文件:ServletTestExecutionListener.java   
private void setUpRequestContextIfNecessary(TestContext testContext) {
    if (notAnnotatedWithWebAppConfiguration(testContext) || alreadyPopulatedRequestContextHolder(testContext)) {
        return;
    }

    ApplicationContext context = testContext.getApplicationContext();

    if (context instanceof WebApplicationContext) {
        WebApplicationContext wac = (WebApplicationContext) context;
        ServletContext servletContext = wac.getServletContext();
        Assert.state(servletContext instanceof MockServletContext, String.format(
            "The WebApplicationContext for test context %s must be configured with a MockServletContext.",
            testContext));

        if (logger.isDebugEnabled()) {
            logger.debug(String.format(
                "Setting up MockHttpServletRequest, MockHttpServletResponse, ServletWebRequest, and RequestContextHolder for test context %s.",
                testContext));
        }

        MockServletContext mockServletContext = (MockServletContext) servletContext;
        MockHttpServletRequest request = new MockHttpServletRequest(mockServletContext);
        request.setAttribute(CREATED_BY_THE_TESTCONTEXT_FRAMEWORK, Boolean.TRUE);
        MockHttpServletResponse response = new MockHttpServletResponse();
        ServletWebRequest servletWebRequest = new ServletWebRequest(request, response);

        RequestContextHolder.setRequestAttributes(servletWebRequest);
        testContext.setAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
        testContext.setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);

        if (wac instanceof ConfigurableApplicationContext) {
            @SuppressWarnings("resource")
            ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) wac;
            ConfigurableListableBeanFactory bf = configurableApplicationContext.getBeanFactory();
            bf.registerResolvableDependency(MockHttpServletResponse.class, response);
            bf.registerResolvableDependency(ServletWebRequest.class, servletWebRequest);
        }
    }
}
项目:spring4-understanding    文件:AnnotationMethodHandlerAdapter.java   
private void handleResponseBody(Object returnValue, ServletWebRequest webRequest) throws Exception {
    if (returnValue == null) {
        return;
    }
    HttpInputMessage inputMessage = createHttpInputMessage(webRequest);
    HttpOutputMessage outputMessage = createHttpOutputMessage(webRequest);
    writeWithMessageConverters(returnValue, inputMessage, outputMessage);
}
项目:pivotal-cla    文件:ImportedSignaturesSessionAttrResolverTests.java   
@Test
public void resolveArgumentFalse() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    NativeWebRequest webRequest = new ServletWebRequest(request);
    MethodParameter parameter = new MethodParameter(method, 0);

    ImportedSignaturesSessionAttr resolved = (ImportedSignaturesSessionAttr) resolver.resolveArgument(parameter, null, webRequest, null);
    assertThat(resolved.getValue()).isFalse();
}
项目:leopard    文件:LeopardDispatcherServlet.java   
protected void noHandlerFound(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String uri = request.getRequestURI();
    String mimeType = getServletContext().getMimeType(uri);
    // System.err.println("request:" + uri + " mimeType:" + mimeType);
    InputStream input = request.getServletContext().getResourceAsStream(uri);
    if (input == null) {
        super.noHandlerFound(request, response);
        return;
    }

    {
        URL url = request.getServletContext().getResource(uri);
        File file = new File(url.getFile());
        if (new ServletWebRequest(request, response).checkNotModified(file.lastModified())) {
            logger.debug("Resource not modified - returning 304");
            return;
        }
    }

    byte[] bytes = IOUtils.toByteArray(input);

    response.setContentLength(bytes.length);
    if (mimeType != null) {
        response.setContentType(mimeType);
    }

    ServletOutputStream out = response.getOutputStream();
    out.write(bytes);
}
项目:spring4-understanding    文件:ServletInvocableHandlerMethod.java   
/**
 * Set the response status according to the {@link ResponseStatus} annotation.
 */
private void setResponseStatus(ServletWebRequest webRequest) throws IOException {
    if (this.responseStatus == null) {
        return;
    }
    if (StringUtils.hasText(this.responseReason)) {
        webRequest.getResponse().sendError(this.responseStatus.value(), this.responseReason);
    }
    else {
        webRequest.getResponse().setStatus(this.responseStatus.value());
    }
    // to be picked up by the RedirectView
    webRequest.getRequest().setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, this.responseStatus);
}
项目:spring4-understanding    文件:ServletWebArgumentResolverAdapter.java   
@Override
protected NativeWebRequest getWebRequest() {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes instanceof ServletRequestAttributes) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        return new ServletWebRequest(servletRequestAttributes.getRequest());
    }
    return null;
}
项目:spring4-understanding    文件:ServletRequestMethodArgumentResolverTests.java   
@Before
public void setUp() throws Exception {
    method = getClass().getMethod("supportedParams", ServletRequest.class, MultipartRequest.class,
            HttpSession.class, Principal.class, Locale.class, InputStream.class, Reader.class,
            WebRequest.class, TimeZone.class, ZoneId.class, HttpMethod.class);
    mavContainer = new ModelAndViewContainer();
    servletRequest = new MockHttpServletRequest("GET", "");
    webRequest = new ServletWebRequest(servletRequest, new MockHttpServletResponse());
}
项目:spring4-understanding    文件:ResponseEntityExceptionHandlerTests.java   
@Before
public void setup() {
    this.servletRequest = new MockHttpServletRequest("GET", "/");
    this.servletResponse = new MockHttpServletResponse();
    this.request = new ServletWebRequest(this.servletRequest, this.servletResponse);

    this.exceptionHandlerSupport = new ApplicationExceptionHandler();
    this.defaultExceptionResolver = new DefaultHandlerExceptionResolver();
}