Example usage for org.springframework.mock.web MockServletContext MockServletContext

List of usage examples for org.springframework.mock.web MockServletContext MockServletContext

Introduction

In this page you can find the example usage for org.springframework.mock.web MockServletContext MockServletContext.

Prototype

public MockServletContext() 

Source Link

Document

Create a new MockServletContext , using no base path and a DefaultResourceLoader (i.e.

Usage

From source file:com.wxxr.nirvana.json.JSONInterceptorTest.java

@Override
protected void setUp() throws Exception {
    super.setUp();

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

    ActionContext context = ActionContext.getContext();
    ValueStack stack = context.getValueStack();

    ActionContext.setContext(context);/*ww  w.j  ava  2  s.  c om*/
    context.put(StrutsStatics.HTTP_REQUEST, this.request);
    context.put(StrutsStatics.HTTP_RESPONSE, this.response);

    MockServletContext servletContext = new MockServletContext();

    context.put(StrutsStatics.SERVLET_CONTEXT, servletContext);
    this.invocation = new MockActionInvocationEx();
    this.invocation.setInvocationContext(context);
    this.invocation.setStack(stack);
}

From source file:com.wxxr.nirvana.json.JSONResultTest.java

@Override
protected void setUp() throws Exception {
    super.setUp();
    this.response = new MockHttpServletResponse();
    this.request = new MockHttpServletRequest();
    this.request.setRequestURI("http://sumeruri");
    this.context = ActionContext.getContext();
    this.context.put(StrutsStatics.HTTP_RESPONSE, this.response);
    this.context.put(StrutsStatics.HTTP_REQUEST, this.request);
    this.stack = context.getValueStack();
    this.servletContext = new MockServletContext();
    this.context.put(StrutsStatics.SERVLET_CONTEXT, this.servletContext);
    this.invocation = new MockActionInvocation();
    this.invocation.setInvocationContext(this.context);
    this.invocation.setStack(this.stack);
}

From source file:org.apache.archiva.web.rss.RssFeedServletTest.java

@Before
@Override//from  w w  w.  ja  v a  2 s.  c om
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;
        }
    };

    rssFeedServlet.init(mockServletConfig);
}

From source file:org.apache.archiva.webdav.AbstractRepositoryServletTestCase.java

protected void startRepository() throws Exception {

    final MockServletContext mockServletContext = new MockServletContext();

    WebApplicationContext webApplicationContext = new TestWebapplicationContext(applicationContext,
            mockServletContext);//  w ww  . j av  a 2s  .co  m

    mockServletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
            webApplicationContext);

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

    unauthenticatedRepositoryServlet.init(mockServletConfig);

}

From source file:org.apache.archiva.webdav.RepositoryServletSecurityTest.java

@Before
@Override//from  w  w w. j a v a2s .c o m
public void setUp() throws Exception {

    super.setUp();

    String appserverBase = System.getProperty("appserver.base",
            new File("target/appserver-base").getAbsolutePath());

    File testConf = new File("src/test/resources/repository-archiva.xml");
    File testConfDest = new File(appserverBase, "conf/archiva.xml");
    FileUtils.copyFile(testConf, testConfDest);

    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);
}

From source file:org.apache.struts2.EmbeddedJSPResultTest.java

@Override
protected void setUp() throws Exception {
    super.setUp();

    result = new EmbeddedJSPResult();

    request = EasyMock.createNiceMock(HttpServletRequest.class);
    response = new MockHttpServletResponse();
    context = new MockServletContext();

    final Map params = new HashMap();

    HttpSession session = EasyMock.createNiceMock(HttpSession.class);
    EasyMock.replay(session);/* w w  w  .  ja v a2s . co m*/

    EasyMock.expect(request.getSession()).andReturn(session).anyTimes();
    EasyMock.expect(request.getParameterMap()).andReturn(params).anyTimes();
    EasyMock.expect(request.getParameter("username")).andAnswer(new IAnswer<String>() {
        public String answer() throws Throwable {
            return ((String[]) params.get("username"))[0];
        }
    });
    EasyMock.expect(request.getAttribute("something")).andReturn("somethingelse").anyTimes();

    EasyMock.replay(request);

    ActionContext actionContext = new ActionContext(new HashMap<String, Object>());
    ActionContext.setContext(actionContext);
    actionContext.setParameters(params);
    ServletActionContext.setRequest(request);
    ServletActionContext.setResponse(response);
    ServletActionContext.setServletContext(context);

    //mock value stack
    Map stackContext = new HashMap();
    ValueStack valueStack = EasyMock.createNiceMock(ValueStack.class);
    EasyMock.expect(valueStack.getContext()).andReturn(stackContext).anyTimes();
    EasyMock.replay(valueStack);

    //mock converter
    XWorkConverter converter = new DummyConverter();

    DefaultFileManager fileManager = new DefaultFileManager();
    fileManager.setReloadingConfigs(false);

    //mock container
    Container container = EasyMock.createNiceMock(Container.class);
    EasyMock.expect(container.getInstance(XWorkConverter.class)).andReturn(converter).anyTimes();
    TextParser parser = new OgnlTextParser();
    EasyMock.expect(container.getInstance(TextParser.class)).andReturn(parser).anyTimes();
    EasyMock.expect(container.getInstanceNames(FileManager.class)).andReturn(new HashSet<String>()).anyTimes();
    EasyMock.expect(container.getInstance(FileManager.class)).andReturn(fileManager).anyTimes();

    UrlHelper urlHelper = new DefaultUrlHelper();
    EasyMock.expect(container.getInstance(UrlHelper.class)).andReturn(urlHelper).anyTimes();
    FileManagerFactory fileManagerFactory = new DummyFileManagerFactory();
    EasyMock.expect(container.getInstance(FileManagerFactory.class)).andReturn(fileManagerFactory).anyTimes();

    EasyMock.replay(container);
    stackContext.put(ActionContext.CONTAINER, container);
    actionContext.setContainer(container);

    actionContext.setValueStack(valueStack);
}

From source file:org.cloudfoundry.identity.uaa.BootstrapTests.java

private ConfigurableApplicationContext getServletContext(String... resources) {
    String environmentConfigLocations = "required_configuration.yml,${LOGIN_CONFIG_URL},file:${LOGIN_CONFIG_PATH}/login.yml,file:${CLOUD_FOUNDRY_CONFIG_PATH}/login.yml,${UAA_CONFIG_URL},file:${UAA_CONFIG_FILE},file:${UAA_CONFIG_PATH}/uaa.yml,file:${CLOUD_FOUNDRY_CONFIG_PATH}/uaa.yml";
    String profiles = null;/*  w w  w.  jav  a 2  s. c o  m*/
    String[] resourcesToLoad = resources;
    if (!resources[0].endsWith(".xml")) {
        profiles = resources[0];
        resourcesToLoad = new String[resources.length - 1];
        System.arraycopy(resources, 1, resourcesToLoad, 0, resourcesToLoad.length);
    }

    final String[] configLocations = resourcesToLoad;

    AbstractRefreshableWebApplicationContext context = new AbstractRefreshableWebApplicationContext() {

        @Override
        protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
                throws BeansException, IOException {
            XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

            // Configure the bean definition reader with this context's
            // resource loading environment.
            beanDefinitionReader.setEnvironment(this.getEnvironment());
            beanDefinitionReader.setResourceLoader(this);
            beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

            if (configLocations != null) {
                for (String configLocation : configLocations) {
                    beanDefinitionReader.loadBeanDefinitions(configLocation);
                }
            }
        }

    };
    MockServletContext servletContext = new MockServletContext() {
        @Override
        public RequestDispatcher getNamedDispatcher(String path) {
            return new MockRequestDispatcher("/");
        }

        public String getVirtualServerName() {
            return null;
        }
    };
    context.setServletContext(servletContext);
    MockServletConfig servletConfig = new MockServletConfig(servletContext);
    servletConfig.addInitParameter("environmentConfigLocations", environmentConfigLocations);
    context.setServletConfig(servletConfig);

    YamlServletProfileInitializer initializer = new YamlServletProfileInitializer();
    initializer.initialize(context);

    if (profiles != null) {
        context.getEnvironment().setActiveProfiles(StringUtils.commaDelimitedListToStringArray(profiles));
    }

    context.refresh();

    return context;
}

From source file:org.cloudfoundry.identity.uaa.login.BootstrapTests.java

private ConfigurableApplicationContext getServletContext(String profiles, String loginYmlPath,
        String uaaYamlPath, String... resources) {
    String[] resourcesToLoad = resources;
    if (!resources[0].endsWith(".xml")) {
        resourcesToLoad = new String[resources.length - 1];
        System.arraycopy(resources, 1, resourcesToLoad, 0, resourcesToLoad.length);
    }/*  w w w .  j av a 2s  . co  m*/

    final String[] configLocations = resourcesToLoad;

    AbstractRefreshableWebApplicationContext context = new AbstractRefreshableWebApplicationContext() {

        @Override
        protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
                throws BeansException, IOException {
            XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

            // Configure the bean definition reader with this context's
            // resource loading environment.
            beanDefinitionReader.setEnvironment(this.getEnvironment());
            beanDefinitionReader.setResourceLoader(this);
            beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

            if (configLocations != null) {
                for (String configLocation : configLocations) {
                    beanDefinitionReader.loadBeanDefinitions(configLocation);
                }
            }
        }

    };

    if (profiles != null) {
        context.getEnvironment().setActiveProfiles(StringUtils.commaDelimitedListToStringArray(profiles));
    }

    MockServletContext servletContext = new MockServletContext() {
        @Override
        public RequestDispatcher getNamedDispatcher(String path) {
            return new MockRequestDispatcher("/");
        }
    };
    context.setServletContext(servletContext);
    MockServletConfig servletConfig = new MockServletConfig(servletContext);
    servletConfig.addInitParameter("environmentConfigLocations", loginYmlPath + "," + uaaYamlPath);
    context.setServletConfig(servletConfig);

    YamlServletProfileInitializer initializer = new YamlServletProfileInitializer();
    initializer.initialize(context);

    if (profiles != null) {
        context.getEnvironment().setActiveProfiles(StringUtils.commaDelimitedListToStringArray(profiles));
    }

    context.refresh();

    return context;
}

From source file:org.cloudfoundry.identity.uaa.mock.audit.AuditCheckMvcMockTests.java

@Before
public void setUp() throws Exception {
    MockEnvironment mockEnvironment = new MockEnvironment();

    webApplicationContext = new XmlWebApplicationContext();
    webApplicationContext.setServletContext(new MockServletContext());
    webApplicationContext.setEnvironment(mockEnvironment);
    new YamlServletProfileInitializerContextInitializer().initializeContext(webApplicationContext,
            "uaa.yml,login.yml");
    webApplicationContext.setConfigLocation("file:./src/main/webapp/WEB-INF/spring-servlet.xml");
    webApplicationContext.refresh();/*from   w  w w  .j  a  va  2s.c  om*/
    FilterChainProxy springSecurityFilterChain = webApplicationContext.getBean("springSecurityFilterChain",
            FilterChainProxy.class);

    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).addFilter(springSecurityFilterChain)
            .build();

    clientRegistrationService = (ClientRegistrationService) webApplicationContext
            .getBean("clientRegistrationService");
    listener = mock(new DefaultApplicationListener<AbstractUaaEvent>() {
    }.getClass());
    authSuccessListener = mock(new DefaultApplicationListener<UserAuthenticationSuccessEvent>() {
    }.getClass());
    webApplicationContext.addApplicationListener(listener);
    webApplicationContext.addApplicationListener(authSuccessListener);
    testListener = TestApplicationEventListener.forEventClass(AbstractUaaEvent.class);
    webApplicationContext.addApplicationListener(testListener);

    testClient = new TestClient(mockMvc);
    testAccounts = UaaTestAccounts.standard(null);
}

From source file:org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator.java

public WebApplicationContext configureDomainOnly() {
    WebRuntimeSpringConfiguration springConfig = new WebRuntimeSpringConfiguration(parent,
            application.getClassLoader());
    springConfig.setServletContext(new MockServletContext());

    if (!pluginManager.isInitialised()) {
        pluginManager.loadPlugins();//w  w w.  j a v a  2s  . com
    }

    if (pluginManager.hasGrailsPlugin("hibernate")) {
        pluginManager.doRuntimeConfiguration("hibernate", springConfig);
    } else if (pluginManager.hasGrailsPlugin("hibernate4")) {
        pluginManager.doRuntimeConfiguration("hibernate4", springConfig);
    }

    WebApplicationContext ctx = (WebApplicationContext) springConfig.getApplicationContext();

    performPostProcessing(ctx);
    application.refreshConstraints();

    return ctx;
}