org.springframework.context.ApplicationContextException Java Examples

The following examples show how to use org.springframework.context.ApplicationContextException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractRefreshableApplicationContext.java    From spring-analysis-note with MIT License 7 votes vote down vote up
/**
 * 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 {
	// 在更新时,如果发现已经存在,将会把之前的 bean 清理掉,并且关闭老 bean 容器
	if (hasBeanFactory()) {
		destroyBeans();
		closeBeanFactory();
	}
	try {
		DefaultListableBeanFactory beanFactory = createBeanFactory();
		beanFactory.setSerializationId(getId());
		customizeBeanFactory(beanFactory);
		// 注释 1.3 开始加载 (bean 注册)
		loadBeanDefinitions(beanFactory);
		// 由于 beanFactory 是公共变量,存在多线程操作,所以加锁操作,避免混乱修改
		synchronized (this.beanFactoryMonitor) {
			this.beanFactory = beanFactory;
		}
	}
	catch (IOException ex) {
		throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
	}
}
 
Example #2
Source File: ApplicationObjectSupport.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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 + "]");
		}
	}
}
 
Example #3
Source File: DatabaseConfiguration.java    From todo-spring-angular with MIT License 6 votes vote down vote up
@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);
}
 
Example #4
Source File: DefaultLifecycleProcessor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * 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 a 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 && bean != this) {
		String[] dependenciesForBean = getBeanFactory().getDependenciesForBean(beanName);
		for (String dependency : dependenciesForBean) {
			doStart(lifecycleBeans, dependency, autoStartupOnly);
		}
		if (!bean.isRunning() &&
				(!autoStartupOnly || !(bean instanceof SmartLifecycle) || ((SmartLifecycle) bean).isAutoStartup())) {
			if (logger.isTraceEnabled()) {
				logger.trace("Starting bean '" + beanName + "' of type [" + bean.getClass().getName() + "]");
			}
			try {
				bean.start();
			}
			catch (Throwable ex) {
				throw new ApplicationContextException("Failed to start bean '" + beanName + "'", ex);
			}
			if (logger.isDebugEnabled()) {
				logger.debug("Successfully started bean '" + beanName + "'");
			}
		}
	}
}
 
Example #5
Source File: CglibProxyTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testExceptionHandling() {
	ExceptionThrower bean = new ExceptionThrower();
	mockTargetSource.setTarget(bean);

	AdvisedSupport as = new AdvisedSupport();
	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());
}
 
Example #6
Source File: XsltView.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example #7
Source File: AbstractJasperReportsViewTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #8
Source File: LiveBeansView.java    From spring-analysis-note with MIT License 6 votes vote down vote up
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();
					applicationName = applicationContext.getApplicationName();
					server.registerMBean(new LiveBeansView(),
							new ObjectName(mbeanDomain, MBEAN_APPLICATION_KEY, applicationName));
				}
				catch (Throwable ex) {
					throw new ApplicationContextException("Failed to register LiveBeansView MBean", ex);
				}
			}
			applicationContexts.add(applicationContext);
		}
	}
}
 
Example #9
Source File: ContextLoaderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testContextLoaderListenerWithUnknownContextInitializer() {
	MockServletContext sc = new MockServletContext("");
	// config file doesn't matter.  just a placeholder
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
			"/org/springframework/web/context/WEB-INF/empty-context.xml");
	sc.addInitParameter(ContextLoader.CONTEXT_INITIALIZER_CLASSES_PARAM,
			StringUtils.arrayToCommaDelimitedString(new Object[] {UnknownContextInitializer.class.getName()}));
	ContextLoaderListener listener = new ContextLoaderListener();
	try {
		listener.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	}
	catch (ApplicationContextException ex) {
		assertTrue(ex.getMessage().contains("not assignable"));
	}
}
 
Example #10
Source File: ContextLoaderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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);
	}
}
 
Example #11
Source File: ContextLoader.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Customize the {@link ConfigurableWebApplicationContext} created by this
 * ContextLoader after config locations have been supplied to the context
 * but before the context is <em>refreshed</em>.
 * <p>The default implementation {@linkplain #determineContextInitializerClasses(ServletContext)
 * determines} what (if any) context initializer classes have been specified through
 * {@linkplain #CONTEXT_INITIALIZER_CLASSES_PARAM context init parameters} and
 * {@linkplain ApplicationContextInitializer#initialize invokes each} with the
 * given web application context.
 * <p>Any {@code ApplicationContextInitializers} implementing
 * {@link org.springframework.core.Ordered Ordered} or marked with @{@link
 * org.springframework.core.annotation.Order Order} will be sorted appropriately.
 * @param sc the current servlet context
 * @param wac the newly created application context
 * @see #CONTEXT_INITIALIZER_CLASSES_PARAM
 * @see ApplicationContextInitializer#initialize(ConfigurableApplicationContext)
 */
protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) {
	List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> initializerClasses =
			determineContextInitializerClasses(sc);

	for (Class<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerClass : initializerClasses) {
		Class<?> initializerContextClass =
				GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
		if (initializerContextClass != null && !initializerContextClass.isInstance(wac)) {
			throw new ApplicationContextException(String.format(
					"Could not apply context initializer [%s] since its generic parameter [%s] " +
					"is not assignable from the type of application context used by this " +
					"context loader: [%s]", initializerClass.getName(), initializerContextClass.getName(),
					wac.getClass().getName()));
		}
		this.contextInitializers.add(BeanUtils.instantiateClass(initializerClass));
	}

	AnnotationAwareOrderComparator.sort(this.contextInitializers);
	for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : this.contextInitializers) {
		initializer.initialize(wac);
	}
}
 
Example #12
Source File: LiveBeansView.java    From java-technology-stack with MIT License 6 votes vote down vote up
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();
					applicationName = applicationContext.getApplicationName();
					server.registerMBean(new LiveBeansView(),
							new ObjectName(mbeanDomain, MBEAN_APPLICATION_KEY, applicationName));
				}
				catch (Throwable ex) {
					throw new ApplicationContextException("Failed to register LiveBeansView MBean", ex);
				}
			}
			applicationContexts.add(applicationContext);
		}
	}
}
 
Example #13
Source File: LiveBeansView.java    From java-technology-stack with MIT License 6 votes vote down vote up
static void unregisterApplicationContext(ConfigurableApplicationContext applicationContext) {
	synchronized (applicationContexts) {
		if (applicationContexts.remove(applicationContext) && applicationContexts.isEmpty()) {
			try {
				MBeanServer server = ManagementFactory.getPlatformMBeanServer();
				String mbeanDomain = applicationContext.getEnvironment().getProperty(MBEAN_DOMAIN_PROPERTY_NAME);
				if (mbeanDomain != null) {
					server.unregisterMBean(new ObjectName(mbeanDomain, MBEAN_APPLICATION_KEY, applicationName));
				}
			}
			catch (Throwable ex) {
				throw new ApplicationContextException("Failed to unregister LiveBeansView MBean", ex);
			}
			finally {
				applicationName = null;
			}
		}
	}
}
 
Example #14
Source File: DefaultLifecycleProcessor.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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 + "'");
			}
		}
	}
}
 
Example #15
Source File: AbstractRefreshableApplicationContext.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example #16
Source File: XsltView.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Get the XSLT {@link Source} for the XSLT template under the {@link #setUrl configured URL}.
 * @return the Source object
 */
protected Source getStylesheetSource() {
	String url = getUrl();
	Assert.state(url != null, "'url' not set");

	if (logger.isDebugEnabled()) {
		logger.debug("Applying stylesheet [" + url + "]");
	}
	try {
		Resource resource = obtainApplicationContext().getResource(url);
		return new StreamSource(resource.getInputStream(), resource.getURI().toASCIIString());
	}
	catch (IOException ex) {
		throw new ApplicationContextException("Can't load XSLT stylesheet from '" + url + "'", ex);
	}
}
 
Example #17
Source File: FrameworkServlet.java    From java-technology-stack with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private ApplicationContextInitializer<ConfigurableApplicationContext> loadInitializer(
		String className, ConfigurableApplicationContext wac) {
	try {
		Class<?> initializerClass = ClassUtils.forName(className, wac.getClassLoader());
		Class<?> initializerContextClass =
				GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
		if (initializerContextClass != null && !initializerContextClass.isInstance(wac)) {
			throw new ApplicationContextException(String.format(
					"Could not apply context initializer [%s] since its generic parameter [%s] " +
					"is not assignable from the type of application context used by this " +
					"framework servlet: [%s]", initializerClass.getName(), initializerContextClass.getName(),
					wac.getClass().getName()));
		}
		return BeanUtils.instantiateClass(initializerClass, ApplicationContextInitializer.class);
	}
	catch (ClassNotFoundException ex) {
		throw new ApplicationContextException(String.format("Could not load class [%s] specified " +
				"via 'contextInitializerClasses' init-param", className), ex);
	}
}
 
Example #18
Source File: DatabaseConfiguration.java    From ServiceCutter with Apache License 2.0 6 votes vote down vote up
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}")
public DataSource dataSource() {
	log.debug("Configuring Datasource");
	if (dataSourcePropertyResolver.getProperty("url") == null && dataSourcePropertyResolver.getProperty("databaseName") == 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 config = new HikariConfig();
	config.setDataSourceClassName(dataSourcePropertyResolver.getProperty("dataSourceClassName"));
	if (StringUtils.isEmpty(dataSourcePropertyResolver.getProperty("url"))) {
		config.addDataSourceProperty("databaseName", dataSourcePropertyResolver.getProperty("databaseName"));
		config.addDataSourceProperty("serverName", dataSourcePropertyResolver.getProperty("serverName"));
	} else {
		config.addDataSourceProperty("url", dataSourcePropertyResolver.getProperty("url"));
	}
	config.addDataSourceProperty("user", dataSourcePropertyResolver.getProperty("username"));
	config.addDataSourceProperty("password", dataSourcePropertyResolver.getProperty("password"));

	if (metricRegistry != null) {
		config.setMetricRegistry(metricRegistry);
	}
	return new HikariDataSource(config);
}
 
Example #19
Source File: ApplicationObjectSupport.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 + "]");
		}
	}
}
 
Example #20
Source File: ContextLoaderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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);
	}
}
 
Example #21
Source File: ContextLoader.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Customize the {@link ConfigurableWebApplicationContext} created by this
 * ContextLoader after config locations have been supplied to the context
 * but before the context is <em>refreshed</em>.
 * <p>The default implementation {@linkplain #determineContextInitializerClasses(ServletContext)
 * determines} what (if any) context initializer classes have been specified through
 * {@linkplain #CONTEXT_INITIALIZER_CLASSES_PARAM context init parameters} and
 * {@linkplain ApplicationContextInitializer#initialize invokes each} with the
 * given web application context.
 * <p>Any {@code ApplicationContextInitializers} implementing
 * {@link org.springframework.core.Ordered Ordered} or marked with @{@link
 * org.springframework.core.annotation.Order Order} will be sorted appropriately.
 * @param sc the current servlet context
 * @param wac the newly created application context
 * @see #CONTEXT_INITIALIZER_CLASSES_PARAM
 * @see ApplicationContextInitializer#initialize(ConfigurableApplicationContext)
 */
protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) {
	List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> initializerClasses =
			determineContextInitializerClasses(sc);

	for (Class<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerClass : initializerClasses) {
		Class<?> initializerContextClass =
				GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
		if (initializerContextClass != null && !initializerContextClass.isInstance(wac)) {
			throw new ApplicationContextException(String.format(
					"Could not apply context initializer [%s] since its generic parameter [%s] " +
					"is not assignable from the type of application context used by this " +
					"context loader: [%s]", initializerClass.getName(), initializerContextClass.getName(),
					wac.getClass().getName()));
		}
		this.contextInitializers.add(BeanUtils.instantiateClass(initializerClass));
	}

	AnnotationAwareOrderComparator.sort(this.contextInitializers);
	for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : this.contextInitializers) {
		initializer.initialize(wac);
	}
}
 
Example #22
Source File: SafeDispatcherServlet.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
/**
 * {@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.");
    }
}
 
Example #23
Source File: SafeDispatcherServletTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@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.");
}
 
Example #24
Source File: XsltView.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example #25
Source File: FrameworkServlet.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #26
Source File: LiveBeansView.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
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();
					applicationName = applicationContext.getApplicationName();
					server.registerMBean(new LiveBeansView(),
							new ObjectName(mbeanDomain, MBEAN_APPLICATION_KEY, applicationName));
				}
				catch (Throwable ex) {
					throw new ApplicationContextException("Failed to register LiveBeansView MBean", ex);
				}
			}
			applicationContexts.add(applicationContext);
		}
	}
}
 
Example #27
Source File: LiveBeansView.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
static void unregisterApplicationContext(ConfigurableApplicationContext applicationContext) {
	synchronized (applicationContexts) {
		if (applicationContexts.remove(applicationContext) && applicationContexts.isEmpty()) {
			try {
				MBeanServer server = ManagementFactory.getPlatformMBeanServer();
				String mbeanDomain = applicationContext.getEnvironment().getProperty(MBEAN_DOMAIN_PROPERTY_NAME);
				server.unregisterMBean(new ObjectName(mbeanDomain, MBEAN_APPLICATION_KEY, applicationName));
			}
			catch (Throwable ex) {
				throw new ApplicationContextException("Failed to unregister LiveBeansView MBean", ex);
			}
			finally {
				applicationName = null;
			}
		}
	}
}
 
Example #28
Source File: DefaultLifecycleProcessor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 + "'");
			}
		}
	}
}
 
Example #29
Source File: LiveBeansView.java    From spring-analysis-note with MIT License 6 votes vote down vote up
static void unregisterApplicationContext(ConfigurableApplicationContext applicationContext) {
	synchronized (applicationContexts) {
		if (applicationContexts.remove(applicationContext) && applicationContexts.isEmpty()) {
			try {
				MBeanServer server = ManagementFactory.getPlatformMBeanServer();
				String mbeanDomain = applicationContext.getEnvironment().getProperty(MBEAN_DOMAIN_PROPERTY_NAME);
				if (mbeanDomain != null) {
					server.unregisterMBean(new ObjectName(mbeanDomain, MBEAN_APPLICATION_KEY, applicationName));
				}
			}
			catch (Throwable ex) {
				throw new ApplicationContextException("Failed to unregister LiveBeansView MBean", ex);
			}
			finally {
				applicationName = null;
			}
		}
	}
}
 
Example #30
Source File: SummerXSLTView.java    From GreenSummer with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Copied due to private access so no reusing from children class :(. Load
 * the {@link Templates} instance for the stylesheet at the configured
 * location.
 */
private Templates loadTemplates(boolean useCached) throws ApplicationContextException {
    if (cachedTemplates == null || !useCached) {
        Source stylesheetSource = getStylesheetSource();
        try {
            log.debug("Loading templates from source {}", stylesheetSource.getSystemId());
            cachedTemplates = getTransformerFactory().newTemplates(stylesheetSource);
        } catch (TransformerConfigurationException ex) {
            throw new ApplicationContextException("Can't load stylesheet from '" + getUrl() + "'", ex);
        } finally {
            customCloseSourceIfNecessary(stylesheetSource);
        }
    }
    return cachedTemplates;
}