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:com.exp.tracker.services.impl.JasperReportGenerationServiceTests.java

@Before
public void setup() {
    // Sanity check
    Assert.assertTrue("Expected an WebApplicationContext", appContext instanceof WebApplicationContext);
    WebApplicationContext ctx = (WebApplicationContext) appContext;
    context = ctx.getServletContext();

    // Set current user
    userDetailService = appContext.getBean(JdbcDaoImpl.class);
    UserDetails userDetails = userDetailService.loadUserByUsername("Admin");
    Authentication authToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(),
            userDetails.getPassword(), userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(authToken);
    rCtx = new MockRequestContext();
    MockExternalContext ec = new MockExternalContext();
    ec.setCurrentUser("Admin");
    ((MockRequestContext) rCtx).setExternalContext(ec);

    // Create two users
    // Add 1st user
    UserBean ub1 = new UserBean();
    ub1.setEmailId("a@b.com");
    ub1.setEnabled(true);/*  w w w.  ja va2s .c o  m*/
    ub1.setFirstName("Test1");
    ub1.setLastName("User1");
    ub1.setMiddleInit("1");
    ub1.setPassword("password");
    ub1.setUsername("reptusr1");
    UserBean userBean1 = userService.addUser(ub1, rCtx);
    Assert.assertNotNull("Failed to create user1.", userBean1);
    //
    // Add 2nd user
    UserBean ub2 = new UserBean();
    ub2.setEmailId("a@b.com");
    ub2.setEnabled(true);
    ub2.setFirstName("Test2");
    ub2.setLastName("User2");
    ub2.setMiddleInit("2");
    ub2.setPassword("password");
    ub2.setUsername("reptusr2");
    UserBean userBean2 = userService.addUser(ub2, rCtx);
    Assert.assertNotNull("Failed to create user2", userBean2);

    // Setup an expense
    ExpenseDetail ed = new ExpenseDetail();
    ed.setAmount(20.0F);
    ed.setCategory("Somecategory");
    ed.setCreatedBy("Admin");
    ed.setDate(new Date());
    ed.setDescription("Some Expense");
    ed.setPaidBy("reptusr1");
    ed.setSettlementId(null);
    // now set shares
    UserShare us1 = new UserShare("reptusr1", 10.0F, 0.0F, true);
    UserShare us2 = new UserShare("reptusr2", 10.0F, 0.0F, true);
    ed.getUserShares().add(us1);
    ed.getUserShares().add(us2);
    //
    expenseDetail = ed;
}

From source file:org.geowebcache.diskquota.ConfigLoaderTest.java

@Override
protected void setUp() throws Exception {
    cacheDir = new File("target" + File.separator + getClass().getSimpleName());
    if (!cacheDir.getParentFile().exists()) {
        throw new IllegalStateException(cacheDir.getParentFile().getAbsolutePath() + " does not exist");
    }//w  ww  .ja  v a 2 s.co  m
    FileUtils.rmFileCacheDir(cacheDir, null);
    cacheDir.mkdirs();
    // copy configuration file to cache directory
    {
        InputStream in = getClass().getResourceAsStream("/geowebcache-diskquota.xml");
        FileOutputStream out = new FileOutputStream(new File(cacheDir, "geowebcache-diskquota.xml"));
        int c;
        while ((c = in.read()) != -1) {
            out.write(c);
        }
        in.close();
        out.close();
    }
    storageFinder = EasyMock.createMock(DefaultStorageFinder.class);
    EasyMock.expect(storageFinder.getDefaultPath()).andReturn(cacheDir.getAbsolutePath()).anyTimes();
    EasyMock.replay(storageFinder);

    ServletContext mockServletCtx = EasyMock.createMock(ServletContext.class);
    String tmpPath = System.getProperty("java.io.tmpdir");
    EasyMock.expect(mockServletCtx.getRealPath(EasyMock.eq(""))).andReturn(tmpPath).anyTimes();
    EasyMock.replay(mockServletCtx);

    WebApplicationContext appContext = EasyMock.createMock(WebApplicationContext.class);
    EasyMock.expect(appContext.getServletContext()).andReturn(mockServletCtx).anyTimes();
    EasyMock.replay(appContext);

    contextProvider = new ApplicationContextProvider();
    contextProvider.setApplicationContext(appContext);

    tld = EasyMock.createMock(TileLayerDispatcher.class);
    TileLayer toppStates = createMockLayer("topp:states");
    TileLayer raster = createMockLayer("raster test layer");
    EasyMock.expect(tld.getTileLayer(EasyMock.eq("topp:states"))).andReturn(toppStates).anyTimes();
    EasyMock.expect(tld.getTileLayer(EasyMock.eq("raster test layer"))).andReturn(raster).anyTimes();

    List<TileLayer> tileLayers = new ArrayList<TileLayer>();
    tileLayers.add(toppStates);
    tileLayers.add(raster);
    EasyMock.expect(tld.getLayerList()).andReturn(tileLayers).anyTimes();
    EasyMock.replay(tld);

    loader = new ConfigLoader(storageFinder, contextProvider, tld);
}

From source file:com.googlecode.psiprobe.model.stats.StatsCollection.java

public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    WebApplicationContext wac = (WebApplicationContext) applicationContext;
    contextTempDir = (File) wac.getServletContext().getAttribute("javax.servlet.context.tempdir");
}

From source file:psiprobe.model.stats.StatsCollection.java

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    WebApplicationContext wac = (WebApplicationContext) applicationContext;
    contextTempDir = (File) wac.getServletContext().getAttribute("javax.servlet.context.tempdir");
}

From source file:com.sinosoft.one.mvc.web.portal.impl.PortalBeanPostProcessor.java

public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

    if (applicationContext instanceof WebApplicationContext) {
        WebApplicationContext webApplicationContext = (WebApplicationContext) applicationContext;
        if (ThreadPoolTaskExecutor.class == bean.getClass()) {
            ThreadPoolTaskExecutor executor = (ThreadPoolTaskExecutor) bean;
            String paramCorePoolSize = webApplicationContext.getServletContext()
                    .getInitParameter(PORTAL_EXECUTOR_CORE_POOL_SIZE);
            if (StringUtils.isNotBlank(paramCorePoolSize)) {
                if (logger.isInfoEnabled()) {
                    logger.info("found param " + PORTAL_EXECUTOR_CORE_POOL_SIZE + "=" + paramCorePoolSize);
                }/* www  .j  a  v a  2s.co m*/
                executor.setCorePoolSize(Integer.parseInt(paramCorePoolSize));
            } else {
                throw new IllegalArgumentException(
                        "please add '<context-param><param-name>portalExecutorCorePoolSize</param-name><param-value>a number here</param-value></context-param>' in your web.xml");
            }
            String paramMaxPoolSize = webApplicationContext.getServletContext()
                    .getInitParameter(PORTAL_EXECUTOR_MAX_POOL_SIZE);
            if (StringUtils.isNotBlank(paramMaxPoolSize)) {
                if (logger.isInfoEnabled()) {
                    logger.info("found param " + PORTAL_EXECUTOR_MAX_POOL_SIZE + "=" + paramMaxPoolSize);
                }
                executor.setMaxPoolSize(Integer.parseInt(paramMaxPoolSize));
            }
            String paramKeepAliveSeconds = webApplicationContext.getServletContext()
                    .getInitParameter(PORTAL_EXECUTOR_KEEP_ALIVE_SECONDS);
            if (StringUtils.isNotBlank(paramKeepAliveSeconds)) {
                if (logger.isInfoEnabled()) {
                    logger.info(
                            "found param " + PORTAL_EXECUTOR_KEEP_ALIVE_SECONDS + "=" + paramKeepAliveSeconds);
                }
                executor.setKeepAliveSeconds(Integer.parseInt(paramKeepAliveSeconds));
            }
        } else if (List.class.isInstance(bean) && "portalListenerList".equals(beanName)) {
            String paramListeners = webApplicationContext.getServletContext()
                    .getInitParameter(PORTAL_LISTENERS);
            @SuppressWarnings("unchecked")
            List<WindowListener> list = (List<WindowListener>) bean;
            if (StringUtils.isNotBlank(paramListeners)) {
                String[] splits = paramListeners.split(",| ");
                if (logger.isInfoEnabled()) {
                    logger.info("found portalListener config: " + Arrays.toString(splits));
                }
                for (String className : splits) {
                    className = className.trim();
                    if (className.length() > 0) {
                        try {
                            Class<?> clazz = Class.forName(className);
                            WindowListener l = (WindowListener) BeanUtils.instantiateClass(clazz);
                            list.add(l);
                            if (logger.isInfoEnabled()) {
                                logger.info("add portalListener: " + l);
                            }
                        } catch (Exception e) {
                            logger.error("", e);
                        }
                    }
                }
            }
        }
    }
    return bean;
}

From source file:com.laxser.blitz.web.portal.impl.PortalBeanPostProcessor.java

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

    if (applicationContext instanceof WebApplicationContext) {
        WebApplicationContext webApplicationContext = (WebApplicationContext) applicationContext;
        if (ThreadPoolTaskExecutor.class == bean.getClass()) {
            ThreadPoolTaskExecutor executor = (ThreadPoolTaskExecutor) bean;
            String paramCorePoolSize = webApplicationContext.getServletContext()
                    .getInitParameter(PORTAL_EXECUTOR_CORE_POOL_SIZE);
            if (StringUtils.isNotBlank(paramCorePoolSize)) {
                if (logger.isInfoEnabled()) {
                    logger.info("found param " + PORTAL_EXECUTOR_CORE_POOL_SIZE + "=" + paramCorePoolSize);
                }//from w  w  w.  ja  va2  s .com
                executor.setCorePoolSize(Integer.parseInt(paramCorePoolSize));
            } else {
                throw new IllegalArgumentException(
                        "please add '<context-param><param-name>portalExecutorCorePoolSize</param-name><param-value>a number here</param-value></context-param>' in your web.xml");
            }
            String paramMaxPoolSize = webApplicationContext.getServletContext()
                    .getInitParameter(PORTAL_EXECUTOR_MAX_POOL_SIZE);
            if (StringUtils.isNotBlank(paramMaxPoolSize)) {
                if (logger.isInfoEnabled()) {
                    logger.info("found param " + PORTAL_EXECUTOR_MAX_POOL_SIZE + "=" + paramMaxPoolSize);
                }
                executor.setMaxPoolSize(Integer.parseInt(paramMaxPoolSize));
            }
            String paramKeepAliveSeconds = webApplicationContext.getServletContext()
                    .getInitParameter(PORTAL_EXECUTOR_KEEP_ALIVE_SECONDS);
            if (StringUtils.isNotBlank(paramKeepAliveSeconds)) {
                if (logger.isInfoEnabled()) {
                    logger.info(
                            "found param " + PORTAL_EXECUTOR_KEEP_ALIVE_SECONDS + "=" + paramKeepAliveSeconds);
                }
                executor.setKeepAliveSeconds(Integer.parseInt(paramKeepAliveSeconds));
            }
        } else if (List.class.isInstance(bean) && "portalListenerList".equals(beanName)) {
            String paramListeners = webApplicationContext.getServletContext()
                    .getInitParameter(PORTAL_LISTENERS);
            @SuppressWarnings("unchecked")
            List<WindowListener> list = (List<WindowListener>) bean;
            if (StringUtils.isNotBlank(paramListeners)) {
                String[] splits = paramListeners.split(",| ");
                if (logger.isInfoEnabled()) {
                    logger.info("found portalListener config: " + Arrays.toString(splits));
                }
                for (String className : splits) {
                    className = className.trim();
                    if (className.length() > 0) {
                        try {
                            Class<?> clazz = Class.forName(className);
                            WindowListener l = (WindowListener) BeanUtils.instantiateClass(clazz);
                            list.add(l);
                            if (logger.isInfoEnabled()) {
                                logger.info("add portalListener: " + l);
                            }
                        } catch (Exception e) {
                            logger.error("", e);
                        }
                    }
                }
            }
        }
    }
    return bean;
}

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

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

    MockControl wmc = MockControl.createControl(WebApplicationContext.class);
    WebApplicationContext wac = (WebApplicationContext) wmc.getMock();
    wac.getBeansOfType(FreeMarkerConfig.class, true, false);
    wmc.setReturnValue(new HashMap());
    wac.getParentBeanFactory();/* w  w w  .ja  v  a2 s  .com*/
    wmc.setReturnValue(null);
    wac.getServletContext();
    wmc.setReturnValue(new MockServletContext());
    wmc.replay();

    fv.setUrl("anythingButNull");
    try {
        fv.setApplicationContext(wac);
        fv.afterPropertiesSet();
        fail("Should have thrown BeanDefinitionStoreException");
    } catch (ApplicationContextException ex) {
        // Check there's a helpful error message
        assertTrue(ex.getMessage().indexOf("FreeMarkerConfig") != -1);
    }

    wmc.verify();
}

From source file:it.geosolutions.geobatch.catalog.file.DataDirHandler.java

/**
 * Try to retrieve the info about where the requested property dir is located.
 *
 * @param propertyName a property name referring to a string containing a path
 *
 * @return a valid dir or null./*w ww  .ja  v  a 2s.c  o m*/
 *
 * @throws NullPointerException
 * @throws IllegalStateException
 */
protected File retrieveConfiguredDir(String propertyName) throws NullPointerException, IllegalStateException {
    File ret = null;

    //        try {
    String prop = System.getProperty(propertyName);
    if (prop != null) {
        ret = new File(prop);
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error(propertyName + " read from property");
        }
    } else {
        prop = System.getenv(propertyName);
        if (prop != null) {
            ret = new File(prop);
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error(propertyName + " read from environment var");
            }
        } else {
            if (this.applicationContext instanceof WebApplicationContext) {
                final WebApplicationContext wContext = (WebApplicationContext) applicationContext;
                final ServletContext servletContext = wContext.getServletContext();
                String rootDir = servletContext.getInitParameter(propertyName);
                if (rootDir != null) {
                    ret = new File(rootDir);
                    if (LOGGER.isErrorEnabled()) {
                        LOGGER.error(propertyName + " read from servlet init param");
                    }
                }
            }
        }
    }
    //        } catch (SecurityException e) {
    //            // gobble exception
    //            if ( LOGGER.isInfoEnabled() ) {
    //                LOGGER.info(e.getLocalizedMessage(), e);
    //            }
    //        }

    if (ret == null) {
        return null;
    }

    if (!ret.exists()) {
        throw new IllegalStateException(
                "Could not initialize " + propertyName + ": The provided path does not exists (" + ret + ")");
    }

    if (!ret.isDirectory() || !ret.canRead()) {
        throw new IllegalStateException("Could not initialize " + propertyName
                + ": The provided path is not a readable directory (" + ret + ")");
    }

    if (!ret.isAbsolute())
        LOGGER.warn("The configured " + propertyName + " is not absolute: " + ret);

    return ret;
}

From source file:org.sakaiproject.login.springframework.SakaiHomeContextLoader.java

/**
 * Initialize the local ApplicationContext, link it to the shared context, and load shared definitions into the shared context.
 *
 * @param servletContext current servlet context
 * @return the new WebApplicationContext
 * @throws org.springframework.beans.BeansException
 *          if the context couldn't be initialized
 *///from  w w w.  j  a  v  a  2 s .  c o  m
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) throws BeansException {

    WebApplicationContext rv = super.initWebApplicationContext(servletContext);
    ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) rv;

    if (configurableApplicationContext != null) {
        String sakaiHomeLocation = servletContext.getInitParameter(SAKAI_HOME_LOCATION_PARAM);
        String servletContextName = rv.getServletContext().getServletContextName();
        if (sakaiHomeLocation == null || sakaiHomeLocation.length() == 0) {
            sakaiHomeLocation = servletContextName + SAKAI_HOME_CONTEXT_SUFFIX;
        }
        if (sakaiHomeLocation != null) {
            final String sakaiHomePath = ServerConfigurationService.getSakaiHomePath();

            String[] locations = StringUtils.tokenizeToStringArray(sakaiHomeLocation,
                    ConfigurableWebApplicationContext.CONFIG_LOCATION_DELIMITERS);
            if (locations != null) {

                XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(
                        (BeanDefinitionRegistry) configurableApplicationContext.getBeanFactory());

                for (int i = 0; i < locations.length; i++) {
                    String resourcePath = sakaiHomePath + locations[i];
                    M_log.debug(
                            servletContextName + " is attempting to load Spring beans from: " + resourcePath);
                    if (new File(resourcePath).exists()) {
                        reader.loadBeanDefinitions(new FileSystemResource(resourcePath));
                    } else {
                        M_log.info(servletContext + " startup is skipping introspection of the resource: "
                                + resourcePath + " because it does not exist.");
                    }
                }
            }
        }
    }

    return rv;
}