Java Code Examples for org.springframework.mock.web.MockServletContext#setAttribute()

The following examples show how to use org.springframework.mock.web.MockServletContext#setAttribute() . 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: MockTdsContextLoader.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public ApplicationContext loadContext(String... locations) throws Exception {
  final MockServletContext servletContext = new MockTdsServletContext();
  final MockServletConfig servletConfig = new MockServletConfig(servletContext);
  final XmlWebApplicationContext webApplicationContext = new XmlWebApplicationContext();

  servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext);
  webApplicationContext.setServletConfig(servletConfig);
  webApplicationContext.setConfigLocations(locations);
  webApplicationContext.refresh();

  TdsContext tdsContext = webApplicationContext.getBean(TdsContext.class);
  checkContentRootPath(webApplicationContext, tdsContext);

  webApplicationContext.registerShutdownHook();

  return webApplicationContext;
}
 
Example 2
Source File: AbstractRepositoryServletTestCase.java    From archiva with Apache License 2.0 6 votes vote down vote up
protected void startRepository()
    throws Exception
{

    final MockServletContext mockServletContext = new MockServletContext();

    WebApplicationContext webApplicationContext =
        new TestWebapplicationContext( applicationContext, mockServletContext );

    mockServletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
                                     webApplicationContext );

    MockServletConfig mockServletConfig = new MockServletConfig()
    {
        @Override
        public ServletContext getServletContext()
        {
            return mockServletContext;
        }
    };

    unauthenticatedRepositoryServlet.init( mockServletConfig );

}
 
Example 3
Source File: GuiceBindingSpringContextLoaderListenerTest.java    From attic-rave with Apache License 2.0 6 votes vote down vote up
@Test
public void initialize_test() {
    Injector injector = Guice.createInjector(createNiceMock(Module.class));

    MockServletContext mockServletContext = new MockServletContext();
    mockServletContext.addInitParameter("contextConfigLocation",
            "classpath:rave-shindig-test-applicationContext.xml, classpath:rave-shindig-test-dataContext.xml");
    mockServletContext.setAttribute(GuiceServletContextListener.INJECTOR_ATTRIBUTE, injector);

    GuiceBindingSpringContextLoaderListener listener = new GuiceBindingSpringContextLoaderListener();
    ServletContextEvent event = createNiceMock(ServletContextEvent.class);
    expect(event.getServletContext()).andReturn(mockServletContext).anyTimes();
    replay(event);

    listener.contextInitialized(event);
    assertThat((Injector)mockServletContext.getAttribute(GuiceServletContextListener.INJECTOR_ATTRIBUTE), is(not(sameInstance(injector))));

}
 
Example 4
Source File: TrimouViewTest.java    From trimou with Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
    context.refresh();
    final MockServletContext servletContext = new MockServletContext();
    context.setServletContext(servletContext);
    servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
}
 
Example 5
Source File: StandaloneMockMvcBuilder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected WebApplicationContext initWebAppContext() {
	MockServletContext servletContext = new MockServletContext();
	StubWebApplicationContext wac = new StubWebApplicationContext(servletContext);
	registerMvcSingletons(wac);
	servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
	return wac;
}
 
Example 6
Source File: IbisTester.java    From iaf with Apache License 2.0 5 votes vote down vote up
@Override
public String call() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setServletPath("/larva/index.jsp");
	boolean silent;
	if (scenario == null) {
		String ibisContextKey = appConstants.getResolvedProperty(IbisApplicationServlet.KEY_CONTEXT);
		application = new MockServletContext("file:" + webAppPath, null);
		application.setAttribute(ibisContextKey, ibisContext);
		silent = false;
	} else {
		request.setParameter("loglevel", "scenario passed/failed");
		request.setParameter("execute", scenario);
		silent = true;
	}
	if (scenariosRootDir != null) {
		request.setParameter("scenariosrootdirectory", scenariosRootDir);
	}
	Writer writer = new StringWriter();
	runScenarios(application, request, writer, silent);
	if (scenario == null) {
		String htmlString = "<html><head/><body>" + writer.toString() + "</body></html>";
		return XmlUtils.toXhtml(htmlString);
	} else {
		return writer.toString();
	}
}
 
Example 7
Source File: RssFeedServletTest.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Before
@Override
public void setUp()
    throws Exception
{
    final MockServletContext mockServletContext = new MockServletContext();

    WebApplicationContext webApplicationContext =
        new TestWebapplicationContext( applicationContext, mockServletContext );

    mockServletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
                                     webApplicationContext );

    MockServletConfig mockServletConfig = new MockServletConfig()
    {
        @Override
        public ServletContext getServletContext()
        {
            return mockServletContext;
        }
    };

    repositoryRegistry.reload();
    repositoryRegistry.putRepository( new BasicManagedRepository( "internal", "internal",
        new FilesystemStorage( Paths.get( "target/appserver-base/repositories/internal" ), new DefaultFileLockManager( ) ) ) );
    rssFeedServlet.init( mockServletConfig );
}
 
Example 8
Source File: PageNavigationTagTest.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {

    MockServletContext sc = new MockServletContext();
    WebApplicationContext wac = new StaticWebApplicationContext();
    sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
    req = new MockHttpServletRequest(sc);
    resp = new MockHttpServletResponse();
    context = new MockPageContext(sc, req, resp);
    rcon = new RequestContext(req, sc);
    context.setAttribute(RequestContextAwareTag.REQUEST_CONTEXT_PAGE_ATTRIBUTE, rcon);
}
 
Example 9
Source File: ApsAdminBaseTestCase.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    boolean refresh = false;
    if (null == applicationContext) {
        // Link the servlet context and the Spring context
        servletContext = new MockServletContext("", new FileSystemResourceLoader());
        applicationContext = this.getConfigUtils().createApplicationContext(servletContext);
        servletContext.setAttribute(
                WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, applicationContext);
    } else {
        refresh = true;
    }
    RequestContext reqCtx = BaseTestCase.createRequestContext(applicationContext, servletContext);
    this.request = new MockHttpServletRequest();
    this.request.setAttribute(RequestContext.REQCTX, reqCtx);
    this.response = new MockHttpServletResponse();
    this.request.setSession(new MockHttpSession(servletContext));
    if (refresh) {
        try {
            ApsWebApplicationUtils.executeSystemRefresh(this.request);
            this.waitNotifyingThread();
        } catch (Throwable e) {
        }
    }
    // Use spring as the object factory for Struts
    StrutsSpringObjectFactory ssf = new StrutsSpringObjectFactory(null, null, null, null, servletContext, null, this.createContainer());
    ssf.setApplicationContext(applicationContext);
    // Dispatcher is the guy that actually handles all requests.  Pass in
    // an empty Map as the parameters but if you want to change stuff like
    // what config files to read, you need to specify them here
    // (see Dispatcher's source code)
    java.net.URL url = ClassLoader.getSystemResource("struts.properties");
    Properties props = new Properties();
    props.load(url.openStream());
    this.setInitParameters(props);
    Map params = new HashMap(props);
    this.dispatcher = new Dispatcher(servletContext, params);
    this.dispatcher.init();
    Dispatcher.setInstance(this.dispatcher);
}
 
Example 10
Source File: StandaloneMockMvcBuilder.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected WebApplicationContext initWebAppContext() {
	MockServletContext servletContext = new MockServletContext();
	StubWebApplicationContext wac = new StubWebApplicationContext(servletContext);
	registerMvcSingletons(wac);
	servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
	return wac;
}
 
Example 11
Source File: StandaloneMockMvcBuilder.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected WebApplicationContext initWebAppContext() {
	MockServletContext servletContext = new MockServletContext();
	StubWebApplicationContext wac = new StubWebApplicationContext(servletContext);
	registerMvcSingletons(wac);
	servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
	return wac;
}
 
Example 12
Source File: CacheUtil.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
public static void cacheSessionAndToken(WebApplicationContext webApplicationContext,String authenticationResult) {
    JSONObject jsonObj=JSONUtils.string2JSON(authenticationResult);
    String sessionID=(String) jsonObj.get("sessionID");
    String token=(String) jsonObj.get("token");
    MockServletContext application = (MockServletContext) webApplicationContext.getServletContext();
    application.setAttribute("sessionID", sessionID);
    application.setAttribute("token", token);
}
 
Example 13
Source File: CacheUtil.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
public static void cacheKey(WebApplicationContext webApplicationContext,String result) {
    JSONObject jsonObj=JSONUtils.string2JSON(result);
    JSONObject data=(JSONObject) jsonObj.get("data");
    String key=(String) data.get("key");
    MockServletContext application = (MockServletContext) webApplicationContext.getServletContext();
    application.setAttribute("key", key);
}
 
Example 14
Source File: CacheUtil.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
public static void cacheSessionAndToken(WebApplicationContext webApplicationContext,String authenticationResult) {
    JSONObject jsonObj=JSONUtils.string2JSON(authenticationResult);
    String sessionID=(String) jsonObj.get("sessionID");
    String token=(String) jsonObj.get("token");
    MockServletContext application = (MockServletContext) webApplicationContext.getServletContext();
    application.setAttribute("sessionID", sessionID);
    application.setAttribute("token", token);
}
 
Example 15
Source File: CacheUtil.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
public static void cacheKey(WebApplicationContext webApplicationContext,String result) {
    JSONObject jsonObj=JSONUtils.string2JSON(result);
    JSONObject data=(JSONObject) jsonObj.get("data");
    String key=(String) data.get("key");
    MockServletContext application = (MockServletContext) webApplicationContext.getServletContext();
    application.setAttribute("key", key);
}
 
Example 16
Source File: MockServletContextWebContextLoader.java    From olat with Apache License 2.0 4 votes vote down vote up
@Override
public final XmlWebApplicationContext loadContext(final String... locations) throws Exception {

    System.out.println("Loading ApplicationContext for locations [" + StringUtils.arrayToCommaDelimitedString(locations) + "].");

    final XmlWebApplicationContext appContext = new XmlWebApplicationContext();
    final MockServletContext servletContext = new MockServletContext();

    servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appContext);

    appContext.setServletContext(servletContext);
    appContext.setConfigLocations(locations);
    appContext.refresh();
    appContext.registerShutdownHook();

    return appContext;

}
 
Example 17
Source File: MockServletContextWebContextLoader.java    From olat with Apache License 2.0 4 votes vote down vote up
@Override
public final XmlWebApplicationContext loadContext(final String... locations) throws Exception {

    System.out.println("Loading ApplicationContext for locations [" + StringUtils.arrayToCommaDelimitedString(locations) + "].");

    final XmlWebApplicationContext appContext = new XmlWebApplicationContext();
    final MockServletContext servletContext = new MockServletContext();

    servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appContext);

    appContext.setServletContext(servletContext);
    appContext.setConfigLocations(locations);
    appContext.refresh();
    appContext.registerShutdownHook();

    return appContext;

}
 
Example 18
Source File: HandlerMethodResolverTest.java    From spring-webmvc-support with GNU General Public License v3.0 4 votes vote down vote up
@Before
public void init() {

    handlerMethodResolver = new HandlerMethodResolver();

    servletContext = new MockServletContext();

    request = new MockHttpServletRequest(servletContext);

    webApplicationContext = new AnnotationConfigWebApplicationContext();

    webApplicationContext.setServletContext(servletContext);

    request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext);

    servletContext.setAttribute(ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext);

    webApplicationContext.register(TestController.class);
    webApplicationContext.register(DelegatingWebMvcConfiguration.class);
    webApplicationContext.register(TestWebMvcConfigurer.class);

    webApplicationContext.refresh();

    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request), true);
}
 
Example 19
Source File: RepositoryServletSecurityTest.java    From archiva with Apache License 2.0 4 votes vote down vote up
@Before
@Override
public void setUp()
    throws Exception
{
    
    super.setUp();

    String appserverBase =
        System.getProperty( "appserver.base", getProjectBase().resolve( "target/appserver-base" ).toAbsolutePath().toString() );

    Path testConf = getProjectBase().resolve( "src/test/resources/repository-archiva.xml" );
    Path testConfDest = Paths.get(appserverBase, "conf/archiva.xml" );
    FileUtils.copyFile( testConf.toFile(), testConfDest.toFile() );
    
    
 
    Configuration config = archivaConfiguration.getConfiguration();
    // clear managed repository
    List<ManagedRepositoryConfiguration> f1 = new ArrayList<>(config.getManagedRepositories());
    for (ManagedRepositoryConfiguration f: f1 ) {
        config.removeManagedRepository(f);
    }
    assertEquals(0,config.getManagedRepositories().size());
    // add internal repo
    config.addManagedRepository(
            createManagedRepository( REPOID_INTERNAL, "Internal Test Repo", repoRootInternal.getRoot() ) );
    
    saveConfiguration( archivaConfiguration );

    CacheManager.getInstance().clearAll();


    servletAuthControl = EasyMock.createControl();

    servletAuth = servletAuthControl.createMock( ServletAuthenticator.class );

    httpAuthControl = EasyMock.createControl();

    httpAuth = httpAuthControl.createMock( HttpAuthenticator.class );

    davSessionProvider = new ArchivaDavSessionProvider( servletAuth, httpAuth );

    final MockServletContext mockServletContext = new MockServletContext();

    WebApplicationContext webApplicationContext =
        new AbstractRepositoryServletTestCase.TestWebapplicationContext( applicationContext, mockServletContext );

    mockServletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
                                     webApplicationContext );

    MockServletConfig mockServletConfig = new MockServletConfig()
    {
        @Override
        public ServletContext getServletContext()
        {
            return mockServletContext;
        }
    };

    servlet = new RepositoryServlet();

    servlet.init( mockServletConfig );
}