Example usage for org.springframework.web.context WebApplicationContext getServletContext

List of usage examples for org.springframework.web.context WebApplicationContext getServletContext

Introduction

In this page you can find the example usage for org.springframework.web.context WebApplicationContext getServletContext.

Prototype

@Nullable
ServletContext getServletContext();

Source Link

Document

Return the standard Servlet API ServletContext for this application.

Usage

From source file:org.hdiv.web.servlet.view.freemarker.FreeMarkerViewTests.java

@Test
public void testValidTemplateName() throws Exception {
    FreeMarkerView fv = new FreeMarkerView();

    MockControl wmc = MockControl.createNiceControl(WebApplicationContext.class);
    WebApplicationContext wac = (WebApplicationContext) wmc.getMock();
    MockServletContext sc = new MockServletContext();

    wac.getBeansOfType(FreeMarkerConfig.class, true, false);
    Map configs = new HashMap();
    FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
    configurer.setConfiguration(new FreeMarkerTestConfiguration());
    configs.put("configurer", configurer);
    wmc.setReturnValue(configs);/*from  w w w  .  j  a v  a 2  s. c om*/
    wac.getParentBeanFactory();
    wmc.setReturnValue(null);
    wac.getServletContext();
    wmc.setReturnValue(sc, 5);
    wmc.replay();

    fv.setUrl("templateName");
    fv.setApplicationContext(wac);

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addPreferredLocale(Locale.US);
    request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
    request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, new AcceptHeaderLocaleResolver());
    HttpServletResponse response = new MockHttpServletResponse();

    Map model = new HashMap();
    model.put("myattr", "myvalue");
    fv.render(model, request, response);

    wmc.verify();
    assertEquals(AbstractView.DEFAULT_CONTENT_TYPE, response.getContentType());
}

From source file:org.hdiv.web.servlet.view.freemarker.FreeMarkerViewTests.java

@Test
public void testKeepExistingContentType() throws Exception {
    FreeMarkerView fv = new FreeMarkerView();

    MockControl wmc = MockControl.createNiceControl(WebApplicationContext.class);
    WebApplicationContext wac = (WebApplicationContext) wmc.getMock();
    MockServletContext sc = new MockServletContext();

    wac.getBeansOfType(FreeMarkerConfig.class, true, false);
    Map configs = new HashMap();
    FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
    configurer.setConfiguration(new FreeMarkerTestConfiguration());
    configs.put("configurer", configurer);
    wmc.setReturnValue(configs);// ww w . ja v a  2s  .c  om
    wac.getParentBeanFactory();
    wmc.setReturnValue(null);
    wac.getServletContext();
    wmc.setReturnValue(sc, 5);
    wmc.replay();

    fv.setUrl("templateName");
    fv.setApplicationContext(wac);

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addPreferredLocale(Locale.US);
    request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
    request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, new AcceptHeaderLocaleResolver());
    HttpServletResponse response = new MockHttpServletResponse();
    response.setContentType("myContentType");

    Map model = new HashMap();
    model.put("myattr", "myvalue");
    fv.render(model, request, response);

    wmc.verify();
    assertEquals("myContentType", response.getContentType());
}

From source file:org.terasoluna.gfw.web.pagination.PaginationTagTest.java

protected MockPageContext createPageContext() {
    MockServletContext sc = new MockServletContext();
    WebApplicationContext wac = mock(WebApplicationContext.class);
    when(wac.getServletContext()).thenReturn(sc);
    MockHttpServletRequest request = new MockHttpServletRequest(sc);
    MockHttpServletResponse response = new MockHttpServletResponse();
    sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
    return new MockPageContext(sc, request, response);
}

From source file:net.paoding.rose.web.impl.module.ModulesBuilderImpl.java

public List<Module> build(List<ModuleResource> moduleResources, WebApplicationContext rootContext)
        throws Exception {

    // ????????/*from   ww  w. ja  v a 2  s .c o  m*/
    moduleResources = new ArrayList<ModuleResource>(moduleResources);
    Collections.sort(moduleResources);

    // ??
    List<Module> modules = new ArrayList<Module>(moduleResources.size());
    Map<ModuleResource, Module> modulesAsMap = new HashMap<ModuleResource, Module>();

    // 
    for (ModuleResource moduleResource : moduleResources) {
        final Module parentModule = (moduleResource.getParent() == null) ? null//
                : modulesAsMap.get(moduleResource.getParent());
        final WebApplicationContext parentContext = (parentModule == null) ? rootContext//
                : parentModule.getApplicationContext();
        final String namespace = "context@controllers" + moduleResource.getRelativePath().replace('/', '.');

        // modulespring context
        final ServletContext servletContext = parentContext == null ? null //
                : parentContext.getServletContext();
        final ModuleAppContext moduleContext = ModuleAppContext.createModuleContext(//
                parentContext, //
                moduleResource.getContextResources(), //
                moduleResource.getMessageBasenames(), //
                /*id*/moduleResource.getModuleUrl().toString(), //
                namespace//
        );

        // ??...applicationContext
        registerBeanDefinitions(moduleContext, moduleResource.getModuleClasses());

        // module
        final ModuleImpl module = new ModuleImpl(//
                parentModule, //
                moduleResource.getModuleUrl(), //
                moduleResource.getMappingPath(), //
                moduleResource.getRelativePath(), //
                moduleContext);
        //
        modulesAsMap.put(moduleResource, module);

        // servletContext
        if (servletContext != null) {
            String contextAttrKey = WebApplicationContext.class.getName() + "@" + moduleResource.getModuleUrl();
            servletContext.setAttribute(contextAttrKey, moduleContext);
        }

        // Springweb??ParamValidatorParamResolver, ControllerInterceptor, ControllerErrorHandler
        List<ParamResolver> customerResolvers = findContextResolvers(moduleContext);

        // resolvers
        module.setCustomerResolvers(customerResolvers);
        if (logger.isDebugEnabled()) {
            logger.debug("module '" + module.getMappingPath() + "': apply resolvers " + customerResolvers);
        }

        // module
        List<InterceptorDelegate> interceptors = findInterceptors(moduleContext);
        for (Iterator<InterceptorDelegate> iter = interceptors.iterator(); iter.hasNext();) {
            InterceptorDelegate interceptor = iter.next();

            ControllerInterceptor most = InterceptorDelegate.getMostInnerInterceptor(interceptor);

            if (!most.getClass().getName().startsWith("net.paoding.rose.web")) {

                // deny?
                if (moduleResource.getInterceptedDeny() != null) {
                    if (RoseStringUtil.matches(moduleResource.getInterceptedDeny(), interceptor.getName())) {
                        iter.remove();
                        if (logger.isDebugEnabled()) {
                            logger.debug("module '" + module.getMappingPath()
                                    + "': remove interceptor by rose.properties: " + most.getClass().getName());
                        }
                        continue;
                    }
                }
                //  allow?
                if (moduleResource.getInterceptedAllow() != null) {
                    if (!RoseStringUtil.matches(moduleResource.getInterceptedAllow(), interceptor.getName())) {
                        iter.remove();
                        if (logger.isDebugEnabled()) {
                            logger.debug("module '" + module.getMappingPath()
                                    + "': remove interceptor by rose.properties: " + most.getClass().getName());
                        }
                        continue;
                    }
                }
            }
        }
        module.setControllerInterceptors(interceptors);
        if (logger.isDebugEnabled()) {
            logger.debug("module '" + module.getMappingPath() + "': apply intercetpors " + interceptors);
        }

        // validatormodule
        List<ParamValidator> validators = findContextValidators(moduleContext);
        module.setValidators(validators);
        if (logger.isDebugEnabled()) {
            logger.debug("module '" + module.getMappingPath() + "': apply global validators " + validators);
        }

        // errorhandler
        ControllerErrorHandler errorHandler = getContextErrorHandler(moduleContext);
        if (errorHandler != null) {
            if (Proxy.isProxyClass(errorHandler.getClass())) {
                module.setErrorHandler(errorHandler);
            } else {
                ErrorHandlerDispatcher dispatcher = new ErrorHandlerDispatcher(errorHandler);
                module.setErrorHandler(dispatcher);
            }
            if (logger.isInfoEnabled()) {
                logger.info("set errorHandler: " + module.getMappingPath() + "  " + errorHandler);
            }
        }

        // controllers
        final ListableBeanFactory beanFactory = moduleContext.getBeanFactory();
        for (String beanName : beanFactory.getBeanDefinitionNames()) {
            checkController(moduleContext, beanName, module);
        }

        // 
        modules.add(module);
    }

    return modules;
}

From source file:com.laxser.blitz.web.impl.module.ModulesBuilderImpl.java

public List<Module> build(List<ModuleResource> moduleResources, WebApplicationContext rootContext)
        throws Exception {

    // ????????/*  www  .  j av  a 2 s  . c  o m*/
    moduleResources = new ArrayList<ModuleResource>(moduleResources);
    Collections.sort(moduleResources);

    // ??
    List<Module> modules = new ArrayList<Module>(moduleResources.size());
    Map<ModuleResource, Module> modulesAsMap = new HashMap<ModuleResource, Module>();

    // 
    for (ModuleResource moduleResource : moduleResources) {
        final Module parentModule = (moduleResource.getParent() == null) ? null//
                : modulesAsMap.get(moduleResource.getParent());
        final WebApplicationContext parentContext = (parentModule == null) ? rootContext//
                : parentModule.getApplicationContext();
        final String namespace = "context@controllers" + moduleResource.getRelativePath().replace('/', '.');

        // modulespring context
        final ServletContext servletContext = parentContext == null ? null //
                : parentContext.getServletContext();
        final ModuleAppContext moduleContext = ModuleAppContext.createModuleContext(//
                parentContext, //
                moduleResource.getContextResources(), //
                moduleResource.getMessageBasenames(), //
                /*id*/moduleResource.getModuleUrl().toString(), //
                namespace//
        );

        // ??...applicationContext
        registerBeanDefinitions(moduleContext, moduleResource.getModuleClasses());

        // module
        final ModuleImpl module = new ModuleImpl(//
                parentModule, //
                moduleResource.getModuleUrl(), //
                moduleResource.getMappingPath(), //
                moduleResource.getRelativePath(), //
                moduleContext);
        //
        modulesAsMap.put(moduleResource, module);

        // servletContext
        if (servletContext != null) {
            String contextAttrKey = WebApplicationContext.class.getName() + "@" + moduleResource.getModuleUrl();
            servletContext.setAttribute(contextAttrKey, moduleContext);
        }

        // Springweb??ParamValidatorParamResolver, ControllerInterceptor, ControllerErrorHandler
        List<ParamResolver> customerResolvers = findContextResolvers(moduleContext);

        // resolvers
        module.setCustomerResolvers(customerResolvers);
        if (logger.isDebugEnabled()) {
            logger.debug("module '" + module.getMappingPath() + "': apply resolvers " + customerResolvers);
        }

        // module
        List<InterceptorDelegate> interceptors = findInterceptors(moduleContext);
        for (Iterator<InterceptorDelegate> iter = interceptors.iterator(); iter.hasNext();) {
            InterceptorDelegate interceptor = iter.next();

            ControllerInterceptor most = InterceptorDelegate.getMostInnerInterceptor(interceptor);

            if (!most.getClass().getName().startsWith("net.paoding.rose.web")) {

                // deny?
                if (moduleResource.getInterceptedDeny() != null) {
                    if (BlitzStringUtil.matches(moduleResource.getInterceptedDeny(), interceptor.getName())) {
                        iter.remove();
                        if (logger.isDebugEnabled()) {
                            logger.debug("module '" + module.getMappingPath()
                                    + "': remove interceptor by rose.properties: " + most.getClass().getName());
                        }
                        continue;
                    }
                }
                //  allow?
                if (moduleResource.getInterceptedAllow() != null) {
                    if (!BlitzStringUtil.matches(moduleResource.getInterceptedAllow(), interceptor.getName())) {
                        iter.remove();
                        if (logger.isDebugEnabled()) {
                            logger.debug("module '" + module.getMappingPath()
                                    + "': remove interceptor by rose.properties: " + most.getClass().getName());
                        }
                        continue;
                    }
                }
            }
        }
        module.setControllerInterceptors(interceptors);
        if (logger.isDebugEnabled()) {
            logger.debug("module '" + module.getMappingPath() + "': apply intercetpors " + interceptors);
        }

        // validatormodule
        List<ParamValidator> validators = findContextValidators(moduleContext);
        module.setValidators(validators);
        if (logger.isDebugEnabled()) {
            logger.debug("module '" + module.getMappingPath() + "': apply global validators " + validators);
        }

        // errorhandler
        ControllerErrorHandler errorHandler = getContextErrorHandler(moduleContext);
        if (errorHandler != null) {
            if (Proxy.isProxyClass(errorHandler.getClass())) {
                module.setErrorHandler(errorHandler);
            } else {
                ErrorHandlerDispatcher dispatcher = new ErrorHandlerDispatcher(errorHandler);
                module.setErrorHandler(dispatcher);
            }
            if (logger.isInfoEnabled()) {
                logger.info("set errorHandler: " + module.getMappingPath() + "  " + errorHandler);
            }
        }

        // controllers
        final ListableBeanFactory beanFactory = moduleContext.getBeanFactory();
        for (String beanName : beanFactory.getBeanDefinitionNames()) {
            checkController(moduleContext, beanName, module);
        }

        // 
        modules.add(module);
    }

    return modules;
}

From source file:com.sinosoft.one.mvc.web.impl.module.ModulesBuilderImpl.java

public List<Module> build(List<ModuleResource> moduleResources, WebApplicationContext rootContext)
        throws Exception {

    // ????????//from www .  j  av  a  2s  .c  om
    moduleResources = new ArrayList<ModuleResource>(moduleResources);
    Collections.sort(moduleResources);

    // ??
    List<Module> modules = new ArrayList<Module>(moduleResources.size());
    Map<ModuleResource, Module> modulesAsMap = new HashMap<ModuleResource, Module>();

    /*
     * ModuleResource ?web???
     * modelResourcesmodel
     *  
     */
    for (ModuleResource moduleResource : moduleResources) {
        final Module parentModule = (moduleResource.getParent() == null) ? null//
                : modulesAsMap.get(moduleResource.getParent());
        final WebApplicationContext parentContext = (parentModule == null) ? rootContext//
                : parentModule.getApplicationContext();
        final String namespace = "context@controllers" + moduleResource.getRelativePath().replace('/', '.');

        // modulespring context
        final ServletContext servletContext = parentContext == null ? null //
                : parentContext.getServletContext();
        final ModuleAppContext moduleContext = ModuleAppContext.createModuleContext(//
                parentContext, //
                moduleResource.getContextResources(), //
                moduleResource.getMessageBasenames(), //
                /*id*/moduleResource.getModuleUrl().toString(), //
                namespace//
        );

        // ??...applicationContext
        registerBeanDefinitions(moduleContext, moduleResource.getModuleClasses());

        // module
        final ModuleImpl module = new ModuleImpl(//
                parentModule, //
                moduleResource.getModuleUrl(), //
                moduleResource.getMappingPath(), //
                moduleResource.getRelativePath(), //
                moduleContext);
        //
        modulesAsMap.put(moduleResource, module);

        // servletContext
        if (servletContext != null) {
            String contextAttrKey = WebApplicationContext.class.getName() + "@" + moduleResource.getModuleUrl();
            servletContext.setAttribute(contextAttrKey, moduleContext);
        }

        // Springweb??ParamValidatorParamResolver, ControllerInterceptor, ControllerErrorHandler
        List<ParamResolver> customerResolvers = findContextResolvers(moduleContext);

        // resolvers
        module.setCustomerResolvers(customerResolvers);
        if (logger.isDebugEnabled()) {
            logger.debug("module '" + module.getMappingPath() + "': apply resolvers " + customerResolvers);
        }

        // module
        List<InterceptorDelegate> interceptors = findInterceptors(moduleContext);
        for (Iterator<InterceptorDelegate> iter = interceptors.iterator(); iter.hasNext();) {
            InterceptorDelegate interceptor = iter.next();

            ControllerInterceptor most = InterceptorDelegate.getMostInnerInterceptor(interceptor);

            if (!most.getClass().getName().startsWith("com.sinosoft.one.mvc.web")) {

                // deny?
                if (moduleResource.getInterceptedDeny() != null) {
                    if (MvcStringUtil.matches(moduleResource.getInterceptedDeny(), interceptor.getName())) {
                        iter.remove();
                        if (logger.isDebugEnabled()) {
                            logger.debug("module '" + module.getMappingPath()
                                    + "': remove interceptor by mvc.properties: " + most.getClass().getName());
                        }
                        continue;
                    }
                }
                //  allow?
                if (moduleResource.getInterceptedAllow() != null) {
                    if (!MvcStringUtil.matches(moduleResource.getInterceptedAllow(), interceptor.getName())) {
                        iter.remove();
                        if (logger.isDebugEnabled()) {
                            logger.debug("module '" + module.getMappingPath()
                                    + "': remove interceptor by mvc.properties: " + most.getClass().getName());
                        }
                        continue;
                    }
                }
            }
        }
        module.setControllerInterceptors(interceptors);
        if (logger.isDebugEnabled()) {
            logger.debug("module '" + module.getMappingPath() + "': apply intercetpors " + interceptors);
        }

        // validatormodule
        List<ParamValidator> validators = findContextValidators(moduleContext);
        module.setValidators(validators);
        if (logger.isDebugEnabled()) {
            logger.debug("module '" + module.getMappingPath() + "': apply global validators " + validators);
        }

        // errorhandler
        ControllerErrorHandler errorHandler = getContextErrorHandler(moduleContext);
        if (errorHandler != null) {
            if (Proxy.isProxyClass(errorHandler.getClass())) {
                module.setErrorHandler(errorHandler);
            } else {
                ErrorHandlerDispatcher dispatcher = new ErrorHandlerDispatcher(errorHandler);
                module.setErrorHandler(dispatcher);
            }
            if (logger.isInfoEnabled()) {
                logger.info("set errorHandler: " + module.getMappingPath() + "  " + errorHandler);
            }
        }

        // controllers
        final ListableBeanFactory beanFactory = moduleContext.getBeanFactory();
        for (String beanName : beanFactory.getBeanDefinitionNames()) {
            checkController(moduleContext, beanName, module);
        }

        // 
        modules.add(module);
    }

    return modules;
}

From source file:org.alfresco.web.app.servlet.BaseServlet.java

/**
 * Resolves the given path elements to a NodeRef in the current repository
 * /* w  w  w  . j  av a  2 s .co m*/
 * @param wc WebApplicationContext Context
 * @param args    The elements of the path to lookup
 * @param decode  True to decode the arg from UTF-8 format, false for no decoding
 */
private static NodeRef resolveWebDAVPath(final WebApplicationContext wc, final String[] args,
        final boolean decode) {
    return AuthenticationUtil.runAs(new RunAsWork<NodeRef>() {
        public NodeRef doWork() throws Exception {
            NodeRef nodeRef = null;

            List<String> paths = new ArrayList<String>(args.length - 1);

            FileInfo file = null;
            try {
                // create a list of path elements (decode the URL as we go)
                for (int x = 1; x < args.length; x++) {
                    paths.add(decode ? URLDecoder.decode(args[x]) : args[x]);
                }

                if (logger.isDebugEnabled())
                    logger.debug("Attempting to resolve webdav path: " + paths);

                // get the company home node to start the search from
                nodeRef = new NodeRef(Repository.getStoreRef(), Application.getCompanyRootId());

                TenantService tenantService = (TenantService) wc.getBean("tenantService");
                if (tenantService != null && tenantService.isEnabled()) {
                    if (logger.isDebugEnabled())
                        logger.debug("MT is enabled.");

                    NodeService nodeService = (NodeService) wc.getBean("NodeService");
                    SearchService searchService = (SearchService) wc.getBean("SearchService");
                    NamespaceService namespaceService = (NamespaceService) wc.getBean("NamespaceService");

                    // TODO: since these constants are used more widely than just the WebDAVServlet, 
                    // they should be defined somewhere other than in that servlet
                    String rootPath = wc.getServletContext().getInitParameter(BaseServlet.KEY_ROOT_PATH);

                    // note: rootNodeRef is required (for storeRef part)
                    nodeRef = tenantService.getRootNode(nodeService, searchService, namespaceService, rootPath,
                            nodeRef);
                }

                if (paths.size() != 0) {
                    FileFolderService ffs = (FileFolderService) wc.getBean("FileFolderService");
                    file = ffs.resolveNamePath(nodeRef, paths);
                    nodeRef = file.getNodeRef();
                }

                if (logger.isDebugEnabled())
                    logger.debug("Resolved webdav path to NodeRef: " + nodeRef);
            } catch (FileNotFoundException fne) {
                if (logger.isWarnEnabled())
                    logger.warn("Failed to resolve webdav path", fne);

                nodeRef = null;
            }
            return nodeRef;
        }
    }, AuthenticationUtil.getSystemUserName());
}

From source file:org.codehaus.groovy.grails.web.mapping.DefaultUrlMappingEvaluator.java

public DefaultUrlMappingEvaluator(WebApplicationContext applicationContext) {
    if (applicationContext != null) {
        this.servletContext = applicationContext.getServletContext();
    }/*  ww w  .  ja  v a2s .  c om*/
    this.applicationContext = applicationContext;
}

From source file:org.geoserver.jdbcconfig.JDBCConfigTestSupport.java

protected void configureAppContext(WebApplicationContext appContext) {
    expect(appContext.getBeansOfType((Class) anyObject())).andReturn(Collections.EMPTY_MAP).anyTimes();
    expect(appContext.getBeanNamesForType((Class) anyObject())).andReturn(new String[] {}).anyTimes();

    ServletContext servletContext = createNiceMock(ServletContext.class);
    replay(servletContext);// www. j av a2s. co  m

    expect(appContext.getServletContext()).andReturn(servletContext);
}