@Test
  public void resolveViewNameRedirectView() throws Exception {
    request.addHeader("Accept", "application/json");
    request.setRequestURI("/test");

    StaticWebApplicationContext webAppContext = new StaticWebApplicationContext();
    webAppContext.setServletContext(new MockServletContext());
    webAppContext.refresh();

    UrlBasedViewResolver urlViewResolver = new InternalResourceViewResolver();
    urlViewResolver.setApplicationContext(webAppContext);
    ViewResolver xmlViewResolver = createMock(ViewResolver.class);
    viewResolver.setViewResolvers(Arrays.<ViewResolver>asList(xmlViewResolver, urlViewResolver));

    View xmlView = createMock("application_xml", View.class);
    View jsonView = createMock("application_json", View.class);
    viewResolver.setDefaultViews(Arrays.asList(jsonView));

    String viewName = "redirect:anotherTest";
    Locale locale = Locale.ENGLISH;

    expect(xmlViewResolver.resolveViewName(viewName, locale)).andReturn(xmlView);
    expect(jsonView.getContentType()).andReturn("application/json").anyTimes();

    replay(xmlViewResolver, xmlView, jsonView);

    View actualView = viewResolver.resolveViewName(viewName, locale);
    assertEquals("Invalid view", RedirectView.class, actualView.getClass());

    verify(xmlViewResolver, xmlView, jsonView);
  }
Exemplo n.º 2
0
  @Test
  public void updateTargetUrlWithContextLoader() throws Exception {
    StaticWebApplicationContext wac = new StaticWebApplicationContext();
    wac.registerSingleton("requestDataValueProcessor", RequestDataValueProcessorWrapper.class);

    MockServletContext servletContext = new MockServletContext();
    ContextLoader contextLoader = new ContextLoader(wac);
    contextLoader.initWebApplicationContext(servletContext);

    try {
      RequestDataValueProcessor mockProcessor = mock(RequestDataValueProcessor.class);
      wac.getBean(RequestDataValueProcessorWrapper.class)
          .setRequestDataValueProcessor(mockProcessor);

      RedirectView rv = new RedirectView();
      rv.setUrl("/path");

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

      given(mockProcessor.processUrl(request, "/path")).willReturn("/path?key=123");

      rv.render(new ModelMap(), request, response);

      verify(mockProcessor).processUrl(request, "/path");
    } finally {
      contextLoader.closeWebApplicationContext(servletContext);
    }
  }
  /** It's not that complicated so we'll just run it straight through here. */
  @Test
  public void publishedEventIsReceivedbyListener() {
    HttpSessionEventPublisher publisher = new HttpSessionEventPublisher();

    StaticWebApplicationContext context = new StaticWebApplicationContext();

    MockServletContext servletContext = new MockServletContext();
    servletContext.setAttribute(
        StaticWebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);

    context.setServletContext(servletContext);
    context.registerSingleton("listener", MockApplicationListener.class, null);
    context.refresh();

    MockHttpSession session = new MockHttpSession(servletContext);
    MockApplicationListener listener = (MockApplicationListener) context.getBean("listener");

    HttpSessionEvent event = new HttpSessionEvent(session);

    publisher.sessionCreated(event);

    assertNotNull(listener.getCreatedEvent());
    assertNull(listener.getDestroyedEvent());
    assertEquals(session, listener.getCreatedEvent().getSession());

    listener.setCreatedEvent(null);
    listener.setDestroyedEvent(null);

    publisher.sessionDestroyed(event);
    assertNotNull(listener.getDestroyedEvent());
    assertNull(listener.getCreatedEvent());
    assertEquals(session, listener.getDestroyedEvent().getSession());
  }
 @Before
 public void createViewResolver() {
   StaticWebApplicationContext wac = new StaticWebApplicationContext();
   wac.setServletContext(new MockServletContext());
   wac.refresh();
   viewResolver = new ContentNegotiatingViewResolver();
   viewResolver.setApplicationContext(wac);
   request = new MockHttpServletRequest("GET", "/test");
   RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
 }
  @Test
  public void testVelocityToolboxView() throws Exception {
    final String templateName = "test.vm";

    StaticWebApplicationContext wac = new StaticWebApplicationContext();
    wac.setServletContext(new MockServletContext());
    final Template expectedTemplate = new Template();
    VelocityConfig vc =
        new VelocityConfig() {
          public VelocityEngine getVelocityEngine() {
            return new TestVelocityEngine(templateName, expectedTemplate);
          }
        };
    wac.getDefaultListableBeanFactory().registerSingleton("velocityConfigurer", vc);

    final HttpServletRequest expectedRequest = new MockHttpServletRequest();
    final HttpServletResponse expectedResponse = new MockHttpServletResponse();

    VelocityToolboxView vv =
        new VelocityToolboxView() {
          protected void mergeTemplate(
              Template template, Context context, HttpServletResponse response) throws Exception {
            assertTrue(template == expectedTemplate);
            assertTrue(response == expectedResponse);
            assertTrue(context instanceof ChainedContext);

            assertEquals("this is foo.", context.get("foo"));
            assertTrue(context.get("map") instanceof HashMap<?, ?>);
            assertTrue(context.get("date") instanceof DateTool);
            assertTrue(context.get("math") instanceof MathTool);

            assertTrue(context.get("link") instanceof LinkTool);
            LinkTool linkTool = (LinkTool) context.get("link");
            assertNotNull(linkTool.getContextURL());

            assertTrue(context.get("link2") instanceof LinkTool);
            LinkTool linkTool2 = (LinkTool) context.get("link2");
            assertNotNull(linkTool2.getContextURL());
          }
        };

    vv.setUrl(templateName);
    vv.setApplicationContext(wac);
    @SuppressWarnings("unchecked")
    Map<String, Class> toolAttributes = new HashMap<String, Class>();
    toolAttributes.put("math", MathTool.class);
    toolAttributes.put("link2", LinkTool.class);
    vv.setToolAttributes(toolAttributes);
    vv.setToolboxConfigLocation("org/springframework/web/servlet/view/velocity/toolbox.xml");
    vv.setExposeSpringMacroHelpers(false);

    vv.render(new HashMap<String, Object>(), expectedRequest, expectedResponse);
  }
Exemplo n.º 6
0
  @Test
  public void requestMappingHandlerMapping() throws Exception {
    StaticWebApplicationContext cxt = new StaticWebApplicationContext();
    cxt.registerSingleton("controller", TestController.class);

    RequestMappingHandlerMapping handlerMapping = mvcConfiguration.requestMappingHandlerMapping();
    assertEquals(0, handlerMapping.getOrder());

    handlerMapping.setApplicationContext(cxt);
    HandlerExecutionChain chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/"));
    assertNotNull(chain.getInterceptors());
    assertEquals(ConversionServiceExposingInterceptor.class, chain.getInterceptors()[0].getClass());
  }
Exemplo n.º 7
0
  protected void onSetUpInTransaction() throws Exception {
    System.err.println("onSetUpInTransaction");
    super.onSetUpInTransaction();
    this.nodeService = (NodeService) super.applicationContext.getBean("dbNodeService");
    assertNotNull(this.nodeService);
    final FileFolderService fileFolderService =
        (FileFolderService) super.applicationContext.getBean("fileFolderService");
    assertNotNull(fileFolderService);
    this.formsService = (FormsService) super.applicationContext.getBean("FormsService");
    assertNotNull(this.formsService);
    final MutableAuthenticationService authenticationService =
        (MutableAuthenticationService) applicationContext.getBean("authenticationService");
    authenticationService.clearCurrentSecurityContext();
    final MutableAuthenticationDao authenticationDAO =
        (MutableAuthenticationDao) applicationContext.getBean("authenticationDao");

    // Create a workspace that contains the 'live' nodes
    final StoreRef testStoreRef =
        this.nodeService.createStore(
            StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis());

    // Get a reference to the root node
    final NodeRef rootNodeRef = this.nodeService.getRootNode(testStoreRef);

    // Create an authenticate the user
    if (!authenticationDAO.userExists(AuthenticationUtil.getAdminUserName())) {
      authenticationService.createAuthentication(
          AuthenticationUtil.getAdminUserName(), "admin".toCharArray());
    }

    TestWithUserUtils.authenticateUser(
        AuthenticationUtil.getAdminUserName(), "admin", rootNodeRef, authenticationService);

    // set up a faces context
    final MockExternalContext ec =
        new MockExternalContext(
            new MockServletContext(), new MockHttpServletRequest(), new MockHttpServletResponse());
    final StaticWebApplicationContext ac = new StaticWebApplicationContext();
    ac.setParent(this.applicationContext);
    this.applicationContext = ac;
    ec.getApplicationMap()
        .put(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.applicationContext);
    new MockFacesContext(ec);

    final FileInfo folderInfo =
        fileFolderService.create(rootNodeRef, "test_form", WCMAppModel.TYPE_FORMFOLDER);
    final HashMap<QName, Serializable> props = new HashMap<QName, Serializable>();
    this.nodeService.addAspect(folderInfo.getNodeRef(), WCMAppModel.ASPECT_FORM, props);
    this.mockForm = new MockForm(folderInfo.getNodeRef(), this.formsService);
  }
Exemplo n.º 8
0
  @Test
  public void beanNameHandlerMapping() throws Exception {
    StaticWebApplicationContext cxt = new StaticWebApplicationContext();
    cxt.registerSingleton("/controller", TestController.class);

    HttpServletRequest request = new MockHttpServletRequest("GET", "/controller");

    BeanNameUrlHandlerMapping handlerMapping = mvcConfiguration.beanNameHandlerMapping();
    assertEquals(2, handlerMapping.getOrder());

    handlerMapping.setApplicationContext(cxt);
    HandlerExecutionChain chain = handlerMapping.getHandler(request);
    assertNotNull(chain.getInterceptors());
    assertEquals(2, chain.getInterceptors().length);
    assertEquals(ConversionServiceExposingInterceptor.class, chain.getInterceptors()[1].getClass());
  }
  @Before
  public void setUp() throws Exception {
    SecurityContextHolder.getContext().setAuthentication(currentUser);
    StaticWebApplicationContext ctx = new StaticWebApplicationContext();

    BeanDefinitionBuilder webExpressionHandler =
        BeanDefinitionBuilder.rootBeanDefinition(DefaultWebSecurityExpressionHandler.class);
    webExpressionHandler.addPropertyValue("permissionEvaluator", permissionEvaluator);

    ctx.registerBeanDefinition("expressionHandler", webExpressionHandler.getBeanDefinition());
    ctx.registerSingleton("wipe", MockWebInvocationPrivilegeEvaluator.class);
    MockServletContext servletCtx = new MockServletContext();
    servletCtx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ctx);
    authorizeTag = new JspAuthorizeTag();
    authorizeTag.setPageContext(
        new MockPageContext(servletCtx, request, new MockHttpServletResponse()));
  }
Exemplo n.º 10
0
 @Override
 protected void setUp() throws Exception {
   super.setUp();
   prefStore = control.createMock(PreferencesStore.class);
   wac.getBeanFactory().registerSingleton("preferencesStore", prefStore);
   context.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
   filter.init(filterConfig);
 }
Exemplo n.º 11
0
 @Before
 public void setUp() {
   servletCtx = new MockServletContext("org/springframework/web/servlet/view/document");
   request = new MockHttpServletRequest(servletCtx);
   response = new MockHttpServletResponse();
   webAppCtx = new StaticWebApplicationContext();
   webAppCtx.setServletContext(servletCtx);
 }
  @Test
  public void nestedViewResolverIsNotSpringBean() throws Exception {
    StaticWebApplicationContext webAppContext = new StaticWebApplicationContext();
    webAppContext.setServletContext(new MockServletContext());
    webAppContext.refresh();

    InternalResourceViewResolver nestedResolver = new InternalResourceViewResolver();
    nestedResolver.setApplicationContext(webAppContext);
    nestedResolver.setViewClass(InternalResourceView.class);
    viewResolver.setViewResolvers(new ArrayList<ViewResolver>(Arrays.asList(nestedResolver)));
    viewResolver.setDefaultContentType(MediaType.TEXT_HTML);

    String viewName = "view";
    Locale locale = Locale.ENGLISH;

    View result = viewResolver.resolveViewName(viewName, locale);
    assertNotNull("Invalid view", result);
  }
Exemplo n.º 13
0
  @Test
  public void updateTargetUrl() throws Exception {
    StaticWebApplicationContext wac = new StaticWebApplicationContext();
    wac.registerSingleton("requestDataValueProcessor", RequestDataValueProcessorWrapper.class);
    wac.setServletContext(new MockServletContext());
    wac.refresh();

    RequestDataValueProcessor mockProcessor = mock(RequestDataValueProcessor.class);
    wac.getBean(RequestDataValueProcessorWrapper.class).setRequestDataValueProcessor(mockProcessor);

    RedirectView rv = new RedirectView();
    rv.setApplicationContext(wac); // Init RedirectView with WebAppCxt
    rv.setUrl("/path");

    MockHttpServletRequest request = createRequest();
    request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
    HttpServletResponse response = new MockHttpServletResponse();

    given(mockProcessor.processUrl(request, "/path")).willReturn("/path?key=123");

    rv.render(new ModelMap(), request, response);

    verify(mockProcessor).processUrl(request, "/path");
  }
 @Before
 public void setUp() {
   StaticWebApplicationContext context = new StaticWebApplicationContext();
   context.registerSingleton("freeMarkerConfigurer", FreeMarkerConfigurer.class);
   this.registry = new ViewResolverRegistry(context);
 }
  public void testOpenPersistenceManagerInViewFilter() throws Exception {
    MockControl pmfControl = MockControl.createControl(PersistenceManagerFactory.class);
    final PersistenceManagerFactory pmf = (PersistenceManagerFactory) pmfControl.getMock();
    MockControl pmControl = MockControl.createControl(PersistenceManager.class);
    PersistenceManager pm = (PersistenceManager) pmControl.getMock();

    pmf.getPersistenceManager();
    pmfControl.setReturnValue(pm, 1);
    pm.close();
    pmControl.setVoidCallable(1);
    pmfControl.replay();
    pmControl.replay();

    MockControl pmf2Control = MockControl.createControl(PersistenceManagerFactory.class);
    final PersistenceManagerFactory pmf2 = (PersistenceManagerFactory) pmf2Control.getMock();
    MockControl pm2Control = MockControl.createControl(PersistenceManager.class);
    PersistenceManager pm2 = (PersistenceManager) pm2Control.getMock();

    pmf2.getPersistenceManager();
    pmf2Control.setReturnValue(pm2, 1);
    pm2.close();
    pm2Control.setVoidCallable(1);
    pmf2Control.replay();
    pm2Control.replay();

    MockServletContext sc = new MockServletContext();
    StaticWebApplicationContext wac = new StaticWebApplicationContext();
    wac.setServletContext(sc);
    wac.getDefaultListableBeanFactory().registerSingleton("persistenceManagerFactory", pmf);
    wac.getDefaultListableBeanFactory().registerSingleton("myPersistenceManagerFactory", pmf2);
    wac.refresh();
    sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
    MockHttpServletRequest request = new MockHttpServletRequest(sc);
    MockHttpServletResponse response = new MockHttpServletResponse();

    MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter");
    MockFilterConfig filterConfig2 = new MockFilterConfig(wac.getServletContext(), "filter2");
    filterConfig2.addInitParameter(
        "persistenceManagerFactoryBeanName", "myPersistenceManagerFactory");

    final OpenPersistenceManagerInViewFilter filter = new OpenPersistenceManagerInViewFilter();
    filter.init(filterConfig);
    final OpenPersistenceManagerInViewFilter filter2 = new OpenPersistenceManagerInViewFilter();
    filter2.init(filterConfig2);

    final FilterChain filterChain =
        new FilterChain() {
          public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) {
            assertTrue(TransactionSynchronizationManager.hasResource(pmf));
            servletRequest.setAttribute("invoked", Boolean.TRUE);
          }
        };

    final FilterChain filterChain2 =
        new FilterChain() {
          public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
              throws IOException, ServletException {
            assertTrue(TransactionSynchronizationManager.hasResource(pmf2));
            filter.doFilter(servletRequest, servletResponse, filterChain);
          }
        };

    FilterChain filterChain3 = new PassThroughFilterChain(filter2, filterChain2);

    assertFalse(TransactionSynchronizationManager.hasResource(pmf));
    assertFalse(TransactionSynchronizationManager.hasResource(pmf2));
    filter2.doFilter(request, response, filterChain3);
    assertFalse(TransactionSynchronizationManager.hasResource(pmf));
    assertFalse(TransactionSynchronizationManager.hasResource(pmf2));
    assertNotNull(request.getAttribute("invoked"));

    pmfControl.verify();
    pmControl.verify();
    pmf2Control.verify();
    pm2Control.verify();

    wac.close();
  }
Exemplo n.º 16
0
  @Test
  public void webMvcConfigurerExtensionHooks() throws Exception {

    StaticWebApplicationContext appCxt = new StaticWebApplicationContext();
    appCxt.setServletContext(new MockServletContext(new FileSystemResourceLoader()));
    appCxt.registerSingleton("controller", TestController.class);

    WebConfig webConfig = new WebConfig();
    webConfig.setApplicationContext(appCxt);
    webConfig.setServletContext(appCxt.getServletContext());

    String actual = webConfig.mvcConversionService().convert(new TestBean(), String.class);
    assertEquals("converted", actual);

    RequestMappingHandlerAdapter adapter = webConfig.requestMappingHandlerAdapter();
    assertEquals(1, adapter.getMessageConverters().size());

    ConfigurableWebBindingInitializer initializer =
        (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
    assertNotNull(initializer);

    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(null, "");
    initializer.getValidator().validate(null, bindingResult);
    assertEquals("invalid", bindingResult.getAllErrors().get(0).getCode());

    @SuppressWarnings("unchecked")
    List<HandlerMethodArgumentResolver> argResolvers =
        (List<HandlerMethodArgumentResolver>)
            new DirectFieldAccessor(adapter).getPropertyValue("customArgumentResolvers");
    assertEquals(1, argResolvers.size());

    @SuppressWarnings("unchecked")
    List<HandlerMethodReturnValueHandler> handlers =
        (List<HandlerMethodReturnValueHandler>)
            new DirectFieldAccessor(adapter).getPropertyValue("customReturnValueHandlers");
    assertEquals(1, handlers.size());

    HandlerExceptionResolverComposite composite =
        (HandlerExceptionResolverComposite) webConfig.handlerExceptionResolver();
    assertEquals(1, composite.getExceptionResolvers().size());

    RequestMappingHandlerMapping rmHandlerMapping = webConfig.requestMappingHandlerMapping();
    rmHandlerMapping.setApplicationContext(appCxt);
    HandlerExecutionChain chain =
        rmHandlerMapping.getHandler(new MockHttpServletRequest("GET", "/"));
    assertNotNull(chain.getInterceptors());
    assertEquals(2, chain.getInterceptors().length);
    assertEquals(LocaleChangeInterceptor.class, chain.getInterceptors()[0].getClass());
    assertEquals(ConversionServiceExposingInterceptor.class, chain.getInterceptors()[1].getClass());

    AbstractHandlerMapping handlerMapping =
        (AbstractHandlerMapping) webConfig.viewControllerHandlerMapping();
    handlerMapping.setApplicationContext(appCxt);
    assertNotNull(handlerMapping);
    assertEquals(1, handlerMapping.getOrder());
    HandlerExecutionChain handler =
        handlerMapping.getHandler(new MockHttpServletRequest("GET", "/path"));
    assertNotNull(handler.getHandler());

    handlerMapping = (AbstractHandlerMapping) webConfig.resourceHandlerMapping();
    handlerMapping.setApplicationContext(appCxt);
    assertNotNull(handlerMapping);
    assertEquals(Integer.MAX_VALUE - 1, handlerMapping.getOrder());
    handler = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/resources/foo.gif"));
    assertNotNull(handler.getHandler());

    handlerMapping = (AbstractHandlerMapping) webConfig.defaultServletHandlerMapping();
    handlerMapping.setApplicationContext(appCxt);
    assertNotNull(handlerMapping);
    assertEquals(Integer.MAX_VALUE, handlerMapping.getOrder());
    handler = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/anyPath"));
    assertNotNull(handler.getHandler());
  }