/** * Reads lang_xx.properties into field {@link #langs langs}. */ public void readLangs() { final ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext(); final Set<String> resourcePaths = servletContext.getResourcePaths("/plugins/" + dirName); for (final String resourcePath : resourcePaths) { if (resourcePath.contains("lang_") && resourcePath.endsWith(".properties")) { final String langFileName = StringUtils.substringAfter(resourcePath, "/plugins/" + dirName + "/"); final String key = langFileName.substring("lang_".length(), langFileName.lastIndexOf(".")); final Properties props = new Properties(); try { final File file = Latkes.getWebFile(resourcePath); props.load(new FileInputStream(file)); langs.put(key.toLowerCase(), props); } catch (final Exception e) { logger.error("Get plugin[name=" + name + "]'s language configuration failed", e); } } } }
/** * Gets all skin directory names. Scans the /skins/ directory, using the * subdirectory of it as the skin directory name, for example, * * <pre> * ${Web root}/skins/ * <b>default</b>/ * <b>mobile</b>/ * <b>classic</b>/ * </pre> * * . * * @return a set of skin name, returns an empty set if not found */ public static Set<String> getSkinDirNames() { final ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext(); final Set<String> ret = new HashSet<>(); final Set<String> resourcePaths = servletContext.getResourcePaths("/skins"); for (final String path : resourcePaths) { final String dirName = path.substring("/skins".length() + 1, path.length() - 1); if (dirName.startsWith(".")) { continue; } ret.add(dirName); } return ret; }
/** * Process {@code @Autowired} injection for the given target object, * based on the current web application context. * <p>Intended for use as a delegate. * @param target the target object to process * @see org.springframework.web.context.ContextLoader#getCurrentWebApplicationContext() */ public static void processInjectionBasedOnCurrentContext(Object target) { Assert.notNull(target, "Target object must not be null"); WebApplicationContext cc = ContextLoader.getCurrentWebApplicationContext(); if (cc != null) { AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setBeanFactory(cc.getAutowireCapableBeanFactory()); bpp.processInjection(target); } else { if (logger.isDebugEnabled()) { logger.debug("Current WebApplicationContext is not available for processing of " + ClassUtils.getShortName(target.getClass()) + ": " + "Make sure this class gets constructed in a Spring web application. Proceeding without injection."); } } }
/** * If a contextConfigLocation init-param has been specified for the ContextLoaderListener, * then it should take precedence. This is generally not a recommended practice, but * when it does happen, the init-param should be considered more specific than the * programmatic configuration, given that it still quite possibly externalized in * hybrid web.xml + WebApplicationInitializer cases. */ @Test public void abstractRefreshableWAC_respectsInitParam_overProgrammaticConfigLocations() { XmlWebApplicationContext ctx = new XmlWebApplicationContext(); ctx.setConfigLocation("programmatic.xml"); ContextLoaderListener cll = new ContextLoaderListener(ctx); MockServletContext sc = new MockServletContext(); sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml"); try { cll.contextInitialized(new ServletContextEvent(sc)); fail("expected exception"); } catch (Throwable t) { // assert that an attempt was made to load the correct XML assertTrue(t.getMessage(), t.getMessage().endsWith( "Could not open ServletContext resource [/from-init-param.xml]")); } }
/** * If setConfigLocation has not been called explicitly against the application context, * then fall back to the ContextLoaderListener init-param if present. */ @Test public void abstractRefreshableWAC_fallsBackToInitParam() { XmlWebApplicationContext ctx = new XmlWebApplicationContext(); //ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically ContextLoaderListener cll = new ContextLoaderListener(ctx); MockServletContext sc = new MockServletContext(); sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml"); try { cll.contextInitialized(new ServletContextEvent(sc)); fail("expected exception"); } catch (Throwable t) { // assert that an attempt was made to load the correct XML assertTrue(t.getMessage().endsWith( "Could not open ServletContext resource [/from-init-param.xml]")); } }
/** * Ensure that any custom default locations are still respected. */ @Test public void customAbstractRefreshableWAC_fallsBackToInitParam() { XmlWebApplicationContext ctx = new XmlWebApplicationContext() { @Override protected String[] getDefaultConfigLocations() { return new String[] { "/WEB-INF/custom.xml" }; } }; //ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically ContextLoaderListener cll = new ContextLoaderListener(ctx); MockServletContext sc = new MockServletContext(); sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml"); try { cll.contextInitialized(new ServletContextEvent(sc)); fail("expected exception"); } catch (Throwable t) { // assert that an attempt was made to load the correct XML System.out.println(t.getMessage()); assertTrue(t.getMessage().endsWith( "Could not open ServletContext resource [/from-init-param.xml]")); } }
/** * 销毁一个消费端 * * 该方法 会通过传递的 ConsumerID 从 servletContext 查询 是否有 该对象 * 然后调用 其销毁方法 * * @param ConsumerID 消费者唯一标识 * @return */ @RequestMapping(method = RequestMethod.DELETE) public ResponseEntity<String> destroyMqConsumer(@RequestParam("Consumer") String Consumer) { ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext() .getServletContext(); @SuppressWarnings("unchecked") Enumeration<String> attributeNames = servletContext.getAttributeNames(); List<String> outList = new ArrayList<String>(); Object AttributeConsumer = servletContext.getAttribute(Consumer); if (AttributeConsumer != null) { MqConsumer mqConsumer = (MqConsumer) AttributeConsumer; mqConsumer.destroy(); servletContext.setAttribute(Consumer, null); return ResponseEntity.status(HttpStatus.OK).body(Consumer + " 消费者销毁成功"); } return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Consumer + " 未找到 该消费者 "); }
/** * 获取servletContext 中存放的 所有 消费者对象 唯一标识 * * @return 返回 说有消费者唯一标识 * */ @RequestMapping(method = RequestMethod.GET) public List<AttributeNames> queryMqConsumerList() { ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext() .getServletContext(); List<AttributeNames> list = new ArrayList<AttributeNames>(); Enumeration<String> attributeNames = servletContext.getAttributeNames(); while (attributeNames.hasMoreElements()) { String nameString = (String) attributeNames.nextElement(); if (nameString.contains("@")) { AttributeNames attri = new AttributeNames(); attri.setKid(nameString); list.add(attri); } } return list; }
protected void createAndEnableTenant(final String tenantName) { final WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext(); final TenantAdminService tenantAdminService = context.getBean("TenantAdminService", TenantAdminService.class); if (!tenantAdminService.existsTenant(tenantName)) { tenantAdminService.createTenant(tenantName, "admin".toCharArray()); // eager sync requires "normal" enabling - won't on creation by design tenantAdminService.disableTenant(tenantName); } if (!tenantAdminService.isEnabledTenant(tenantName)) { tenantAdminService.enableTenant(tenantName); } }
@Override public void contextInitialized(ServletContextEvent sce) { ServletContext sc = sce.getServletContext(); // 初始化 Logback sc.setInitParameter(WebLogbackConfigurer.CONFIG_LOCATION_PARAM, findLogbackConfigLocation()); WebLogbackConfigurer.initLogging(sc); // 初始化 Spring 配置 sc.setInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "classpath:spring-setaria-console.xml"); applicationContext = initWebApplicationContext(sc); // 注册 Spring Character Encoding registerCharacterEncoding(sc); // 注册 Spring Servlet registerDispatcherServlet(sc); // 注册 Spring FreeMarker Servlet 处理 FTL 请求 registerSpringFreeMarkerServlet(sc); }
@Override public void onStartup(ServletContext webappContext) throws ServletException { ModuleDataExtractor extractor = new ModuleDataExtractor(module); environment.assureModule(module); String fullRestResource = "/" + module.getContext() + "/*"; ServerData serverData = new ServerData(environment.getModuleBean(module).getPort(), Arrays.asList(), rootContext, fullRestResource, module); List<FilterData> filterDataList = extractor.createFilteredDataList(serverData); List<ServletData> servletDataList = extractor.createServletDataList(serverData); new ServletConfigurer(serverData, LinkedListX.fromIterable(servletDataList)).addServlets(webappContext); new FilterConfigurer(serverData, LinkedListX.fromIterable(filterDataList)).addFilters(webappContext); PersistentList<ServletContextListener> servletContextListenerData = LinkedListX.fromIterable(module.getListeners(serverData)).filter(i->!(i instanceof ContextLoader)); PersistentList<ServletRequestListener> servletRequestListenerData = LinkedListX.fromIterable(module.getRequestListeners(serverData)); new ServletContextListenerConfigurer(serverData, servletContextListenerData, servletRequestListenerData).addListeners(webappContext); }
/** * Instantiate the rootId WebApplicationContext for this loader, either the * default context class or a custom context class if specified. * <p>This implementation expects custom contexts to implement the * {@link ConfigurableWebApplicationContext} interface. * Can be overridden in subclasses. * <p>In addition, {@link #customizeContext} gets called prior to refreshing the * context, allowing subclasses to perform custom modifications to the context. * @param servletContext current servlet context * @param parent the parent ApplicationContext to use, or <code>null</code> if none * @return the rootId WebApplicationContext * @throws BeansException if the context couldn't be initialized * @see ConfigurableWebApplicationContext */ @Override @Deprecated protected WebApplicationContext createWebApplicationContext(ServletContext servletContext, ApplicationContext parent) throws BeansException { MergeXmlWebApplicationContext wac = new MergeXmlWebApplicationContext(); wac.setParent(parent); wac.setServletContext(servletContext); wac.setConfigLocation(servletContext.getInitParameter(ContextLoader.CONFIG_LOCATION_PARAM)); wac.setPatchLocation(servletContext.getInitParameter(PATCH_LOCATION_PARAM)); wac.setShutdownBean(servletContext.getInitParameter(SHUTDOWN_HOOK_BEAN)); wac.setShutdownMethod(servletContext.getInitParameter(SHUTDOWN_HOOK_METHOD)); customizeContext(servletContext, wac); wac.refresh(); return wac; }
@Override public void contextInitialized(ServletContextEvent sce) { try { AbstractRefreshableWebApplicationContext wac = (AbstractRefreshableWebApplicationContext) WebApplicationContextUtils .getWebApplicationContext(sce.getServletContext()); if (wac == null) { contextLoader = new ContextLoader(); createSpringApplicationContext(sce.getServletContext()); } else { WebApplicationContextHolder.set(wac); enhanceExistingSpringWebApplicationContext(sce, wac); } } catch (Exception t) { LOGGER.error("Exception occured", t); } }
@Override public Object handle(RestRequest request, RestResponse response, RestHandlerMethod handlerMethod) throws Exception { if(StringUtils.isNotEmpty(handlerMethod.getTable())){ request.setTable(handlerMethod.getTable()); } Object bean = ContextLoader.getCurrentWebApplicationContext().getBean(handlerMethod.getBeanName()); Method method = ReflectionUtils.findMethod(bean.getClass(), handlerMethod.getMethodName(), type1); Object[] params = new Object[]{request, response}; if(null == method){ method = ReflectionUtils.findMethod(bean.getClass(), handlerMethod.getMethodName(), type2); params = new Object[]{response, request}; } Object result = null; if(null != method.getReturnType()){ result = ReflectionUtils.invokeMethod(method, bean, params); }else{ ReflectionUtils.invokeMethod(method, bean, new Object[]{request, response}); } return result; }
@SuppressWarnings("unchecked") protected <T> T registerComponent(T bean, String name) { DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) ContextLoader.getCurrentWebApplicationContext() .getAutowireCapableBeanFactory(); Class<T> clazz = (Class<T>) bean.getClass(); String className = clazz.getCanonicalName(); BeanDefinition beanDefinition = null; try { beanDefinition = BeanDefinitionReaderUtils.createBeanDefinition(null, className, clazz.getClassLoader()); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } beanDefinition.setScope(BeanDefinition.SCOPE_SINGLETON); beanDefinition.setAutowireCandidate(true); beanFactory.registerBeanDefinition(name, beanDefinition); beanFactory.registerSingleton(name, bean); beanFactory.configureBean(bean, name); return bean; }
/** * Initializes template engine configuration. */ private void initTemplateEngineCfg() { configuration = new Configuration(); configuration.setDefaultEncoding("UTF-8"); final ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext(); configuration.setServletContextForTemplateLoading(servletContext, "/plugins/" + dirName); logger.debug("Initialized template configuration:{}", dirName); readLangs(); }
/** * Sets the directory for template loading with the specified skin directory * name, and sets the directory for mobile request template loading. * * @param skinDirName * the specified skin directory name */ public static void setDirectoryForTemplateLoading(final String skinDirName) { final ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext(); Templates.MAIN_CFG.setServletContextForTemplateLoading(servletContext, "/skins/" + skinDirName); Templates.MAIN_CFG.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); Templates.MAIN_CFG.setLogTemplateExceptions(false); Templates.MOBILE_CFG.setServletContextForTemplateLoading(servletContext, "/skins/mobile"); Templates.MOBILE_CFG.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); Templates.MOBILE_CFG.setLogTemplateExceptions(false); }
public void contextInitialized(ServletContextEvent contextEvent) { WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext(); context.getBean(SysCacheService.class).flush(); context.getBean(SysUserService.class).init(); SysDicService sysDicService = context.getBean(SysDicService.class); sysDicService.getAllDic(); super.contextInitialized(contextEvent); }
private static ShardedJedis getJedis() { if (shardedJedisPool == null) { synchronized (EXPIRE) { if (shardedJedisPool == null) { WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext(); shardedJedisPool = wac.getBean(ShardedJedisPool.class); } } } return shardedJedisPool.getResource(); }
@SuppressWarnings("unchecked") private RedisTemplate<Serializable, Serializable> getRedis() { if (redisTemplate == null) { synchronized (RedisHelper.class) { if (redisTemplate == null) { WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext(); redisTemplate = (RedisTemplate<Serializable, Serializable>) wac.getBean("redisTemplate"); } } } return redisTemplate; }
private RedissonClient getRedis() { if (redisTemplate == null) { synchronized (RedissonHelper.class) { if (redisTemplate == null) { WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext(); redisTemplate = wac.getBean(Redisson.class); } } } return redisTemplate; }
public void contextInitialized(ServletContextEvent contextEvent) { WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext(); context.getBean(SysCacheService.class).flush(); context.getBean(SysUserService.class).init(); SysDicService sysDicService = context.getBean(SysDicService.class); sysDicService.getAllDic(); MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true); super.contextInitialized(contextEvent); }
private ApplicationContext loadRootApplicationContext(ServletContext servletContext, Class<?>... configClasses) { AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.setAllowBeanDefinitionOverriding(true); rootContext.register(configClasses); servletContext.addListener(new ContextLoaderListener(rootContext)); servletContext.setInitParameter(ContextLoader.CONTEXT_INITIALIZER_CLASSES_PARAM, APPLICATION_CONTEXT_INITIALIZER_CLASS.getName()); return rootContext; }
@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); } }
@Test public void globalInitializerClasses() throws Exception { DispatcherServlet servlet = new DispatcherServlet(); servlet.setContextClass(SimpleWebApplicationContext.class); getServletContext().setInitParameter(ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM, TestWebContextInitializer.class.getName() + "," + OtherWebContextInitializer.class.getName()); servlet.init(servletConfig); assertEquals("true", getServletContext().getAttribute("initialized")); assertEquals("true", getServletContext().getAttribute("otherInitialized")); }
@Test public void mixedInitializerClasses() throws Exception { DispatcherServlet servlet = new DispatcherServlet(); servlet.setContextClass(SimpleWebApplicationContext.class); getServletContext().setInitParameter(ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM, TestWebContextInitializer.class.getName()); servlet.setContextInitializerClasses(OtherWebContextInitializer.class.getName()); servlet.init(servletConfig); assertEquals("true", getServletContext().getAttribute("initialized")); assertEquals("true", getServletContext().getAttribute("otherInitialized")); }
@Before public void setup() { this.servletContext = new MockServletContext(); this.webAppContext = new AnnotationConfigWebApplicationContext(); this.webAppContext.register(Config.class); this.contextLoader = new ContextLoader(this.webAppContext); this.contextLoader.initWebApplicationContext(this.servletContext); this.configurator = new SpringConfigurator(); }
@SuppressWarnings("unchecked") private static Map<ClassLoader, WebApplicationContext> getCurrentContextPerThreadFromContextLoader() { try { Field field = ContextLoader.class.getDeclaredField("currentContextPerThread"); field.setAccessible(true); return (Map<ClassLoader, WebApplicationContext>) field.get(null); } catch (Exception ex) { throw new IllegalStateException(ex); } }
/** * Retrieve the Spring {@link WebApplicationContext} to use. * The default implementation returns the current {@link WebApplicationContext} * as registered for the thread context class loader. * @return the current WebApplicationContext (never {@code null}) * @see ContextLoader#getCurrentWebApplicationContext() */ protected WebApplicationContext getWebApplicationContext() { WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext(); if (wac == null) { throw new IllegalStateException("No WebApplicationContext registered for current thread - " + "consider overriding SpringWebConstraintValidatorFactory.getWebApplicationContext()"); } return wac; }
public FtlView(String folder, String viewName) { try { ApplicationContext applicationContext = ContextLoader.getCurrentWebApplicationContext(); this.setApplicationContext(applicationContext); } catch (Exception e) { // 兼容普通java环境 } this.setUrl(viewName + ".ftl"); this.folder = folder; }
@SuppressWarnings("rawtypes") @Override public TypeConverter getInstance(Class<? extends TypeConverter> clazz, Locale locale) throws Exception { TypeConverter converter = super.getInstance(clazz, locale); SpringHelper.injectBeans(converter, ContextLoader.getCurrentWebApplicationContext()); return converter; }
@Override protected ContextLoader createContextLoader() { try { logger.info("Creating OscarContextLoader"); return new OscarSpringContextLoader(); } catch (Exception t) { logger.error("Unexpected error.", t); throw (new RuntimeException(t)); } }