/** * Checks to see that a valid report file URL is supplied in the * configuration. Compiles the report file is necessary. * <p>Subclasses can add custom initialization logic by overriding * the {@link #onInit} method. */ @Override protected final void initApplicationContext() throws ApplicationContextException { this.report = loadReport(); // Load sub reports if required, and check data source parameters. if (this.subReportUrls != null) { if (this.subReportDataKeys != null && this.subReportDataKeys.length > 0 && this.reportDataKey == null) { throw new ApplicationContextException( "'reportDataKey' for main report is required when specifying a value for 'subReportDataKeys'"); } this.subReports = new HashMap<String, JasperReport>(this.subReportUrls.size()); for (Enumeration<?> urls = this.subReportUrls.propertyNames(); urls.hasMoreElements();) { String key = (String) urls.nextElement(); String path = this.subReportUrls.getProperty(key); Resource resource = getApplicationContext().getResource(path); this.subReports.put(key, loadReport(resource)); } } // Convert user-supplied exporterParameters. convertExporterParameters(); if (this.headers == null) { this.headers = new Properties(); } if (!this.headers.containsKey(HEADER_CONTENT_DISPOSITION)) { this.headers.setProperty(HEADER_CONTENT_DISPOSITION, CONTENT_DISPOSITION_INLINE); } onInit(); }
/** * {@inheritDoc} * @throws ApplicationContextException if the DispatcherServlet does not * initialize properly, but the servlet attempts to process a request. */ @Override public void service(final ServletRequest req, final ServletResponse resp) throws ServletException, IOException { /* * Since our container calls only this method and not any of the other * HttpServlet runtime methods, such as doDelete(), etc., delegating * this method is sufficient to delegate all of the methods in the * HttpServlet API. */ if (this.initSuccess) { this.delegate.service(req, resp); } else { throw new ApplicationContextException("Unable to initialize application context."); } }
@Test public void testService() throws ServletException, IOException { this.safeServlet.init(this.mockConfig); ServletRequest mockRequest = new MockHttpServletRequest(); ServletResponse mockResponse = new MockHttpServletResponse(); try { this.safeServlet.service(mockRequest, mockResponse); } catch (final ApplicationContextException ace) { // good, threw the exception we expected. return; } fail("Should have thrown ApplicationContextException since init() failed."); }
/** * Takes care of enforcing the relationship between exporter and importers. * * @param beanFactory */ private void enforceExporterImporterDependency(ConfigurableListableBeanFactory beanFactory) { Object instance = null; instance = AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { // create the service manager ClassLoader loader = AbstractOsgiBundleApplicationContext.class.getClassLoader(); try { Class<?> managerClass = loader.loadClass(EXPORTER_IMPORTER_DEPENDENCY_MANAGER); return BeanUtils.instantiateClass(managerClass); } catch (ClassNotFoundException cnfe) { throw new ApplicationContextException("Cannot load class " + EXPORTER_IMPORTER_DEPENDENCY_MANAGER, cnfe); } } }); // sanity check Assert.isInstanceOf(BeanFactoryAware.class, instance); Assert.isInstanceOf(BeanPostProcessor.class, instance); ((BeanFactoryAware) instance).setBeanFactory(beanFactory); beanFactory.addBeanPostProcessor((BeanPostProcessor) instance); }
static void registerApplicationContext(ConfigurableApplicationContext applicationContext) { String mbeanDomain = applicationContext.getEnvironment().getProperty(MBEAN_DOMAIN_PROPERTY_NAME); if (mbeanDomain != null) { synchronized (applicationContexts) { if (applicationContexts.isEmpty()) { try { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); server.registerMBean(new LiveBeansView(), new ObjectName(mbeanDomain, MBEAN_APPLICATION_KEY, applicationContext.getApplicationName())); } catch (Exception ex) { throw new ApplicationContextException("Failed to register LiveBeansView MBean", ex); } } applicationContexts.add(applicationContext); } } }
/** * Start the specified bean as part of the given set of Lifecycle beans, * making sure that any beans that it depends on are started first. * @param lifecycleBeans Map with bean name as key and Lifecycle instance as value * @param beanName the name of the bean to start */ private void doStart(Map<String, ? extends Lifecycle> lifecycleBeans, String beanName, boolean autoStartupOnly) { Lifecycle bean = lifecycleBeans.remove(beanName); if (bean != null && !this.equals(bean)) { String[] dependenciesForBean = this.beanFactory.getDependenciesForBean(beanName); for (String dependency : dependenciesForBean) { doStart(lifecycleBeans, dependency, autoStartupOnly); } if (!bean.isRunning() && (!autoStartupOnly || !(bean instanceof SmartLifecycle) || ((SmartLifecycle) bean).isAutoStartup())) { if (logger.isDebugEnabled()) { logger.debug("Starting bean '" + beanName + "' of type [" + bean.getClass() + "]"); } try { bean.start(); } catch (Throwable ex) { throw new ApplicationContextException("Failed to start bean '" + beanName + "'", ex); } if (logger.isDebugEnabled()) { logger.debug("Successfully started bean '" + beanName + "'"); } } } }
/** * This implementation performs an actual refresh of this context's underlying * bean factory, shutting down the previous bean factory (if any) and * initializing a fresh bean factory for the next phase of the context's lifecycle. */ @Override protected final void refreshBeanFactory() throws BeansException { if (hasBeanFactory()) { destroyBeans(); closeBeanFactory(); } try { DefaultListableBeanFactory beanFactory = createBeanFactory(); beanFactory.setSerializationId(getId()); customizeBeanFactory(beanFactory); loadBeanDefinitions(beanFactory); synchronized (this.beanFactoryMonitor) { this.beanFactory = beanFactory; } } catch (IOException ex) { throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex); } }
@Override public final void setApplicationContext(ApplicationContext context) throws BeansException { if (context == null && !isContextRequired()) { // Reset internal context state. this.applicationContext = null; this.messageSourceAccessor = null; } else if (this.applicationContext == null) { // Initialize with passed-in context. if (!requiredContextClass().isInstance(context)) { throw new ApplicationContextException( "Invalid application context: needs to be of type [" + requiredContextClass().getName() + "]"); } this.applicationContext = context; this.messageSourceAccessor = new MessageSourceAccessor(context); initApplicationContext(context); } else { // Ignore reinitialization if same context passed in. if (this.applicationContext != context) { throw new ApplicationContextException( "Cannot reinitialize with different application context: current one is [" + this.applicationContext + "], passed-in one is [" + context + "]"); } } }
/**��ʵ��ִ�д������ĵĵײ�bean factory��ʵ��ˢ�¡� * �ر���ǰ��bean����������еĻ����ͳ�ʼ���������ĵ��������ڵ���һ�ε�����bean���� * <p> * This implementation performs an actual refresh of this context's underlying * bean factory, shutting down the previous bean factory (if any) and * initializing a fresh bean factory for the next phase of the context's lifecycle. */ @Override protected final void refreshBeanFactory() throws BeansException { if (hasBeanFactory()) { destroyBeans(); closeBeanFactory(); } try { DefaultListableBeanFactory beanFactory = createBeanFactory(); beanFactory.setSerializationId(getId()); customizeBeanFactory(beanFactory); loadBeanDefinitions(beanFactory); synchronized (this.beanFactoryMonitor) { this.beanFactory = beanFactory; } } catch (IOException ex) { throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex); } }
@Test public void testExceptionHandling() { ExceptionThrower bean = new ExceptionThrower(); mockTargetSource.setTarget(bean); AdvisedSupport as = new AdvisedSupport(new Class<?>[]{}); as.setTargetSource(mockTargetSource); as.addAdvice(new NopInterceptor()); AopProxy aop = new CglibAopProxy(as); ExceptionThrower proxy = (ExceptionThrower) aop.getProxy(); try { proxy.doTest(); } catch (Exception ex) { assertTrue("Invalid exception class", ex instanceof ApplicationContextException); } assertTrue("Catch was not invoked", proxy.isCatchInvoked()); assertTrue("Finally was not invoked", proxy.isFinallyInvoked()); }
protected ScriptTemplateConfig autodetectViewConfig() throws BeansException { try { return BeanFactoryUtils.beanOfTypeIncludingAncestors( getApplicationContext(), ScriptTemplateConfig.class, true, false); } catch (NoSuchBeanDefinitionException ex) { throw new ApplicationContextException("Expected a single ScriptTemplateConfig bean in the current " + "Servlet web application context or the parent root context: ScriptTemplateConfigurer is " + "the usual implementation. This bean may have any name.", ex); } }
/** * Load the {@link Templates} instance for the stylesheet at the configured location. */ private Templates loadTemplates() throws ApplicationContextException { Source stylesheetSource = getStylesheetSource(); try { Templates templates = this.transformerFactory.newTemplates(stylesheetSource); if (logger.isDebugEnabled()) { logger.debug("Loading templates '" + templates + "'"); } return templates; } catch (TransformerConfigurationException ex) { throw new ApplicationContextException("Can't load stylesheet from '" + getUrl() + "'", ex); } finally { closeSourceIfNecessary(stylesheetSource); } }
/** * Instantiate the WebApplicationContext for this servlet, either a default * {@link org.springframework.web.context.support.XmlWebApplicationContext} * or a {@link #setContextClass custom context class}, if set. * <p>This implementation expects custom contexts to implement the * {@link org.springframework.web.context.ConfigurableWebApplicationContext} * interface. Can be overridden in subclasses. * <p>Do not forget to register this servlet instance as application listener on the * created context (for triggering its {@link #onRefresh callback}, and to call * {@link org.springframework.context.ConfigurableApplicationContext#refresh()} * before returning the context instance. * @param parent the parent ApplicationContext to use, or {@code null} if none * @return the WebApplicationContext for this servlet * @see org.springframework.web.context.support.XmlWebApplicationContext */ protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) { Class<?> contextClass = getContextClass(); if (this.logger.isDebugEnabled()) { this.logger.debug("Servlet with name '" + getServletName() + "' will try to create custom WebApplicationContext context of class '" + contextClass.getName() + "'" + ", using parent context [" + parent + "]"); } if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) { throw new ApplicationContextException( "Fatal initialization error in servlet with name '" + getServletName() + "': custom WebApplicationContext class [" + contextClass.getName() + "] is not of type ConfigurableWebApplicationContext"); } ConfigurableWebApplicationContext wac = (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass); wac.setEnvironment(getEnvironment()); wac.setParent(parent); wac.setConfigLocation(getContextConfigLocation()); configureAndRefreshWebApplicationContext(wac); return wac; }
@Test public void withNonExistentSubReport() throws Exception { assumeTrue(canCompileReport); Map<String, Object> model = getModel(); model.put("SubReportData", getProductData()); Properties subReports = new Properties(); subReports.put("ProductsSubReport", "org/springframework/ui/jasperreports/subReportChildFalse.jrxml"); AbstractJasperReportsView view = getView(SUB_REPORT_PARENT); view.setReportDataKey("dataSource"); view.setSubReportUrls(subReports); view.setSubReportDataKeys(new String[]{"SubReportData"}); // Invalid report URL should throw ApplicationContextException exception.expect(ApplicationContextException.class); view.initApplicationContext(); }
@Test public void subReportWithUnspecifiedParentDataSource() throws Exception { assumeTrue(canCompileReport); Map<String, Object> model = getModel(); model.put("SubReportData", getProductData()); Properties subReports = new Properties(); subReports.put("ProductsSubReport", "org/springframework/ui/jasperreports/subReportChildFalse.jrxml"); AbstractJasperReportsView view = getView(SUB_REPORT_PARENT); view.setSubReportUrls(subReports); view.setSubReportDataKeys(new String[]{"SubReportData"}); // Unspecified reportDataKey should throw exception when subReportDataSources is specified exception.expect(ApplicationContextException.class); view.initApplicationContext(); }
@Test public void testNoVelocityConfig() throws Exception { VelocityView vv = new VelocityView(); WebApplicationContext wac = mock(WebApplicationContext.class); given(wac.getBeansOfType(VelocityConfig.class, true, false)).willReturn(new HashMap<String, VelocityConfig>()); vv.setUrl("anythingButNull"); try { vv.setApplicationContext(wac); fail(); } catch (ApplicationContextException ex) { // Check there's a helpful error message assertTrue(ex.getMessage().contains("VelocityConfig")); } }
@Test public void testContextLoaderWithInvalidContext() throws Exception { MockServletContext sc = new MockServletContext(""); sc.addInitParameter(ContextLoader.CONTEXT_CLASS_PARAM, "org.springframework.web.context.support.InvalidWebApplicationContext"); ServletContextListener listener = new ContextLoaderListener(); ServletContextEvent event = new ServletContextEvent(sc); try { listener.contextInitialized(event); fail("Should have thrown ApplicationContextException"); } catch (ApplicationContextException ex) { // expected assertTrue(ex.getCause() instanceof ClassNotFoundException); } }
@Override public void initialize( XmlWebApplicationContext applicationContext ) { ConfigurableEnvironment env = applicationContext.getEnvironment(); WorkDir workDir; try { workDir = new WorkDir( applicationContext.getServletContext() ); } catch ( IOException e ) { throw new ApplicationContextException( "Error obtaining QuartzDesk Executor work directory.", e ); } String databaseProfile = getDatabaseProfile( workDir ); String[] activeProfiles = new String[] { databaseProfile }; log.info( "Activating Spring profiles: {}", Arrays.toString( activeProfiles ) ); env.setActiveProfiles( activeProfiles ); }
@Bean(destroyMethod = "close") @ConditionalOnExpression("#{!environment.acceptsProfiles('" + Constants.SPRING_PROFILE_CLOUD + "') && !environment.acceptsProfiles('" + Constants.SPRING_PROFILE_HEROKU + "')}") @ConfigurationProperties(prefix = "spring.datasource.hikari") public DataSource dataSource(DataSourceProperties dataSourceProperties) { log.debug("Configuring Datasource"); if (dataSourceProperties.getUrl() == null) { log.error("Your database connection pool configuration is incorrect! The application" + " cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(env.getActiveProfiles())); throw new ApplicationContextException("Database connection pool is not configured correctly"); } HikariDataSource hikariDataSource = (HikariDataSource) DataSourceBuilder .create(dataSourceProperties.getClassLoader()) .type(HikariDataSource.class) .driverClassName(dataSourceProperties.getDriverClassName()) .url(dataSourceProperties.getUrl()) .username(dataSourceProperties.getUsername()) .password(dataSourceProperties.getPassword()) .build(); if (metricRegistry != null) { hikariDataSource.setMetricRegistry(metricRegistry); } return hikariDataSource; }
private void createEmbeddedServletContainer() { EmbeddedServletContainer localContainer = this.embeddedServletContainer; ServletContext localServletContext = getServletContext(); if (localContainer == null && localServletContext == null) { EmbeddedServletContainerFactory containerFactory = getEmbeddedServletContainerFactory(); this.embeddedServletContainer = containerFactory .getEmbeddedServletContainer(getSelfInitializer()); } else if (localServletContext != null) { try { getSelfInitializer().onStartup(localServletContext); } catch (ServletException ex) { throw new ApplicationContextException("Cannot initialize servlet context", ex); } } initPropertySources(); }
/** * Returns the {@link EmbeddedServletContainerFactory} that should be used to create * the embedded servlet container. By default this method searches for a suitable bean * in the context itself. * @return a {@link EmbeddedServletContainerFactory} (never {@code null}) */ protected EmbeddedServletContainerFactory getEmbeddedServletContainerFactory() { // Use bean names so that we don't consider the hierarchy String[] beanNames = getBeanFactory() .getBeanNamesForType(EmbeddedServletContainerFactory.class); if (beanNames.length == 0) { throw new ApplicationContextException( "Unable to start EmbeddedWebApplicationContext due to missing " + "EmbeddedServletContainerFactory bean."); } if (beanNames.length > 1) { throw new ApplicationContextException( "Unable to start EmbeddedWebApplicationContext due to multiple " + "EmbeddedServletContainerFactory beans : " + StringUtils.arrayToCommaDelimitedString(beanNames)); } return getBeanFactory().getBean(beanNames[0], EmbeddedServletContainerFactory.class); }
@SuppressWarnings("unchecked") private List<ApplicationListener<ApplicationEvent>> getListeners( ConfigurableEnvironment env) { String classNames = env.getProperty(PROPERTY_NAME); List<ApplicationListener<ApplicationEvent>> listeners = new ArrayList<ApplicationListener<ApplicationEvent>>(); if (StringUtils.hasLength(classNames)) { for (String className : StringUtils.commaDelimitedListToSet(classNames)) { try { Class<?> clazz = ClassUtils.forName(className, ClassUtils.getDefaultClassLoader()); Assert.isAssignable(ApplicationListener.class, clazz, "class [" + className + "] must implement ApplicationListener"); listeners.add((ApplicationListener<ApplicationEvent>) BeanUtils .instantiateClass(clazz)); } catch (Exception ex) { throw new ApplicationContextException( "Failed to load context listener class [" + className + "]", ex); } } } AnnotationAwareOrderComparator.sort(listeners); return listeners; }
/** * This implementation performs an actual refresh of this context's underlying * bean factory, shutting down the previous bean factory (if any) and * initializing a fresh bean factory for the next phase of the context's lifecycle. */ @Override protected final void refreshBeanFactory() throws BeansException { // 已经创建了BeanFactory, 先销毁并关闭该BeanFactory if (hasBeanFactory()) { destroyBeans(); closeBeanFactory(); } try { DefaultListableBeanFactory beanFactory = createBeanFactory(); // 创建BeanFactory beanFactory.setSerializationId(getId()); customizeBeanFactory(beanFactory); loadBeanDefinitions(beanFactory); // 加载BeanDefinition synchronized (this.beanFactoryMonitor) { this.beanFactory = beanFactory; } } catch (IOException ex) { throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex); } }
@Bean public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipsterProperties jHipsterProperties) { log.debug("Configuring Heroku Datasource"); String herokuUrl = System.getenv("JDBC_DATABASE_URL"); if (herokuUrl != null) { HikariConfig config = new HikariConfig(); //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(dataSourceProperties.getDriverClassName())) { config.addDataSourceProperty("cachePrepStmts", jHipsterProperties.getDatasource().isCachePrepStmts()); config.addDataSourceProperty("prepStmtCacheSize", jHipsterProperties.getDatasource().getPrepStmtCacheSize()); config.addDataSourceProperty("prepStmtCacheSqlLimit", jHipsterProperties.getDatasource().getPrepStmtCacheSqlLimit()); } config.setDataSourceClassName(dataSourceProperties.getDriverClassName()); config.addDataSourceProperty("url", herokuUrl); return new HikariDataSource(config); } else { throw new ApplicationContextException("Heroku database URL is not configured, you must set $JDBC_DATABASE_URL"); } }
@Bean(destroyMethod = "close") public DataSource dataSource() { log.debug("Configuring Datasource"); if (dataSourcePropertyResolver.getProperty("url") == null) { log.error("Your database connection pool configuration is incorrect! The application" + " cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(env.getActiveProfiles())); throw new ApplicationContextException("Database connection pool is not configured correctly"); } HikariConfig hikariConfig = new HikariConfig(); hikariConfig.setDriverClassName(dataSourcePropertyResolver.getProperty("dataSourceClassName")); hikariConfig.setJdbcUrl(dataSourcePropertyResolver.getProperty("url")); hikariConfig.setUsername(dataSourcePropertyResolver.getProperty("username")); hikariConfig.setPassword(dataSourcePropertyResolver.getProperty("password")); return new HikariDataSource(hikariConfig); }