net.kamhon.ieagle.application.Application.java Source code

Java tutorial

Introduction

Here is the source code for net.kamhon.ieagle.application.Application.java

Source

/*
 * Copyright 2012 Eng Kam Hon (kamhon@gmail.com)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.kamhon.ieagle.application;

import java.io.InputStream;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletContext;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class Application {
    private static Log log = LogFactory.getLog(Application.class);

    public static enum MsgResource {
        DATETIME_FORMAT("dateTimeFormat"), DATE_FORMAT("dateFormat");
        private String key;

        private MsgResource(String key) {
            this.key = key;
        }
    }

    private static Map<String, Object> beans;

    private static String contextPath;
    private static String clazzPath;

    private static ApplicationContext appContext;

    private Application() {
    }

    protected static synchronized ApplicationContext initialize(final ServletContext servletContext) {
        try {
            if (appContext == null) {
                appContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
            }
        } catch (Exception ex) {
            log.info("WebApplicationContext not found!!! Using ClassPathXmlApplicationContext");

            if (StringUtils.isBlank(contextPath)) {
                initContextPath();
            }

            try {
                if (appContext == null && contextPath.endsWith(".class")) {
                    appContext = new AnnotationConfigApplicationContext(
                            Class.forName(contextPath.substring(0, contextPath.length() - ".class".length())));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                if (appContext == null)
                    appContext = new FileSystemXmlApplicationContext(contextPath);
            } catch (Exception e) {
            }

            try {
                if (appContext == null)
                    appContext = new ClassPathXmlApplicationContext(contextPath);
            } catch (Exception e) {
            }

            createGenericApplicationContext();
        }

        return appContext;
    }

    private static void createGenericApplicationContext() {
        if (appContext == null) {
            appContext = new GenericApplicationContext();

            Class<?> clazz = null;
            if (StringUtils.isNotBlank(clazzPath)) {
                try {
                    clazz = Class.forName(clazzPath);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }

            ClassPathResource resource = null;
            if (contextPath.startsWith("classpath:")) {
                if (clazz == null) {
                    resource = new ClassPathResource(contextPath.substring("classpath:".length()));
                } else {
                    resource = new ClassPathResource(contextPath.substring("classpath:".length()), clazz);
                }
            } else {
                if (clazz == null) {
                    resource = new ClassPathResource(contextPath);
                } else {
                    resource = new ClassPathResource(contextPath, clazz);
                }
            }
            BeanDefinitionReader reader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) appContext);
            reader.loadBeanDefinitions(resource);
            ((GenericApplicationContext) appContext).refresh();
        }
    }

    public static ApplicationContext getApplicationContext() {
        if (appContext == null) {
            if (initialize(null) == null)
                throw new IllegalStateException("SpringContext has not been initialized.");
        }
        return appContext;
    }

    private static void initContextPath() {
        Properties p = new Properties();
        InputStream is = null;
        try {
            is = Application.class.getResourceAsStream("/spring-setup.properties");
            p.load(is);

            contextPath = p.getProperty("contextPath");
            clazzPath = p.getProperty("clazz");
        } catch (Exception ex) {
            log.fatal("Can not find spring-setup.properties at classpath");
            log.fatal("Can not initial ClassPathXmlApplicationContext");
            ex.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (Exception e) {
            }
        }
    }

    public static Object lookupBean(String beanName) {
        if (beans != null) {
            return beans.get(beanName);
        }

        if (appContext == null) {
            if (initialize(null) == null)
                throw new IllegalStateException("SpringContext has not been initialized.");
        }
        return appContext.getBean(beanName);
    }

    @SuppressWarnings("unchecked")
    public static <T> T lookupBean(String beanName, Class<T> t) {
        Object bean = lookupBean(beanName);

        return (T) bean;
    }

    public static String getMessage(String code, Object... param) {
        return getMessage(code, param, Locale.getDefault());
    }

    public static String getMessage(MsgResource msgResource) {
        return getMessage(msgResource.key);
    }

    private static String getMessage(String code, Object[] args, String defaultMsg, Locale loc) {
        return appContext.getMessage(code, args, defaultMsg, loc);
    }

    private static String getMessage(String code, Object[] args, Locale loc) {
        return getMessage(code, args, "?? key " + code + " not found??", loc);
    }

    /**
     * <p>
     * this function used to set context path for applicationContext.xml. It useful for doing testing. The String format
     * is exactly same as spring-setup.properties <br/>
     * <br/>
     * e.g. classpath:net/kamhon/xxx/resources/applicationContext.xml
     * </p>
     * 
     * @param contextPath
     */
    public static void setContextPath(String contextPath) {
        Application.contextPath = contextPath;
    }

    public static void setClazzPath(String clazzPath) {
        Application.clazzPath = clazzPath;
    }

    /**
     * this function used to replace the appContext. It useful for doing testing.
     * 
     * @param applicationContext
     */
    public static void setApplicationContext(ApplicationContext applicationContext) {
        Application.appContext = applicationContext;
    }

    public static void setApplicationContextByAppConfig(Class<?> appConfigClass) {
        Application.appContext = new AnnotationConfigApplicationContext(appConfigClass);
    }

    /**
     * reset for doing testing
     */
    public static void reset() {
        appContext = null;
        contextPath = null;
        clazzPath = null;
        if (beans != null)
            beans.clear();
        beans = null;
    }

    public static void setBeans(Map<String, Object> _beans) {
        beans = _beans;
    }
}