package org.fouram.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.fouram.core.base.constants.SysConstants;
import org.fouram.core.base.constants.SysConstants.ConstSession;
import org.fouram.core.util.LoggerUtil;
import org.fouram.service.SysDictionaryService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * 加载系统配置文件
 * 
 * @author liup
 * 
 */
public class SystemInitListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		LoggerUtil.info("容器关闭……");
	}

	@Override
	public void contextInitialized(ServletContextEvent config) {
		ServletContext application = config.getServletContext();
		try {
			// 开启log4j2全异步模式
			System.setProperty("Log4jContextSelector", "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");
			WebApplicationContext springContext = WebApplicationContextUtils
					.getWebApplicationContext(config.getServletContext());
			SysDictionaryService sysDictionaryService = (SysDictionaryService) springContext
					.getBean("sysDictionaryService");
			String companyName = sysDictionaryService
					.findOneByTypeAndKey(SysConstants.SysDictionaryTypeIndex, SysConstants.SysDictionaryKeyCompanyName)
					.getValue();
			String cmsName = sysDictionaryService
					.findOneByTypeAndKey(SysConstants.SysDictionaryTypeIndex, SysConstants.SysDictionaryKeyCmsName)
					.getValue();
			application.setAttribute(ConstSession.SESSION_COMPANY_NAME, companyName);
			application.setAttribute(ConstSession.SESSION_CMS_NAME, cmsName);
		} catch (Exception e) {
			LoggerUtil.error(e);
		}
	}
}