手写mvc之ClassLoadlistener

package com.xuchen.demo.listener;

import java.io.File;
import java.io.FileFilter;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

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

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.alibaba.fastjson.JSON;
import com.xuchen.demo.annotation.Service;
import com.xuchen.demo.util.StringUtils;

public class ClassLoadlistener implements ServletContextListener{
    
    private static final String INITPARAMETER = "contextConfigLocation";
    private List<String> classNames = new ArrayList<String>();
    private Map<String, Object> beanContries = new HashMap<String, Object>();
    @Override
    public void contextInitialized(ServletContextEvent event) {
        System.out.println("********** init ContextListener start *************");
        try {
            ServletContext servletContext = event.getServletContext();
            String webContextXml = servletContext.getInitParameter(INITPARAMETER).trim();
            String[] parameters = webContextXml.split(",");
            if (null != parameters) {
                for (String path : parameters) {
                    System.out.println(this.getClass().getName() + "{}" + StringUtils.trim(path));
                    String servletXmlPath = path.substring(path.lastIndexOf(":") + 1);
                    Document document = null;
                    SAXReader render = new SAXReader();
                    InputStream inputStream = this.getClassLoader().getResourceAsStream(servletXmlPath);
                    if (null == inputStream) {
                        System.out.println(this.getClass().getName() + " not find " + servletXmlPath);
                        return;
                    }
                    document = render.read(inputStream);
                    String xmlPacakScanPath = "//context-package-scan";
                    @SuppressWarnings("unchecked")
                    List<Element> nodelist = document.selectNodes(xmlPacakScanPath);
                    for (Element element : nodelist) {
                        Object packageName = element.getData();
                        contextScanPackage(String.valueOf(packageName));
                    }
                }
            }
            if (null != classNames && !classNames.isEmpty()) {
                servletContext.setAttribute("classNames", classNames);
                servletContext.setAttribute("beanContries", beanContries);
            }
            System.out.println("beanContries {} " + beanContries);
            System.out.println(this.getClass().getName() + " classNames " + JSON.toJSONString(classNames));
        } catch (Exception e) {
            System.out.println(this.getClass().getName() + " init ContextListener excetion " + e);
        }
        System.out.println("********** init ContextListener end   *************");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        
        
    }
    
    public ClassLoader getClassLoader() {
        return Thread.currentThread().getContextClassLoader();
    }
    
    private void contextScanPackage (String packageName) {
        try {
            Enumeration<URL> urlEnum = getClassLoader().getResources(packageName.replace(".", "/"));
            while(urlEnum.hasMoreElements()) {
                URL url = urlEnum.nextElement();
                String protocol = url.getProtocol();
                if ("file".equals(protocol)) {
                    String clazz = url.getPath().replaceAll("%20", "");
                    File[] files = new File(clazz).listFiles(new FileFilter() {
                        @Override
                        public boolean accept(File file) {
                            return (file.isFile() && file.getName().endsWith(".class") || file.isDirectory());
                        }
                    });
                    for (File file : files) {
                        String fileName = file.getName();
                        if (file.isDirectory()) {
                            contextScanPackage(packageName + "." + fileName);
                        } else {
                            String className = packageName + "." + fileName.substring(0, fileName.lastIndexOf("."));
                            if (!"".equals(className)) {
                                Class<?> claxx = Class.forName(className, false, getClassLoader());
                                if (claxx.isAnnotationPresent(Service.class)) {
                                    String aliasValue = claxx.getAnnotation(Service.class).value();
                                    System.out.println("aliasValue " + aliasValue);
                                    classNames.add(className);
                                }
                            }
                        }
                    }
                } else {
                    System.out.println("---------- now package is in a jar file.");
                    Map<String, Object> paraMap = new HashMap<String, Object>();
                    JarURLConnection jarConnect = (JarURLConnection) url.openConnection();
                    if (null != jarConnect) {
                        JarFile jarFile = jarConnect.getJarFile();
                        if (null != jarFile) {
                            Enumeration<JarEntry> entries = jarFile.entries();
                            if (null != entries) {
                                while (entries.hasMoreElements()) {
                                    JarEntry jarEntry = (JarEntry) entries.nextElement();
                                    String fileName = jarEntry.getName();
                                    if (fileName.endsWith(".class")) {
                                        fileName = jarEntry.getName().replace("/", ".");
                                        String claxxName = fileName.substring(0, fileName.lastIndexOf(".class"));
                                        Class<?> claxx = Class.forName(claxxName);
                                        if (claxx.isAnnotationPresent(Service.class)) {
                                            System.out.println("class 【" + claxxName + "】 has service @interface");
                                            String aliasValue = claxx.getAnnotation(Service.class).value();
                                            System.out.println("aliasValue " + aliasValue);
                                            classNames.add(claxxName);
                                            beanContries.put(claxxName, claxx.newInstance());
                                        }
                                    } else if (fileName.endsWith(".xml")) {
                                        System.out.println(getClass().getName() + " 我是xml文件" + fileName);
                                    }
                                }
                            }
                            
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.out.println(this.getClass().getName() + " analasis object instance package exception "  + e);
            throw new RuntimeException("analasis object instance package exception", e);
        }
    }
    
    /**
     * 首字母小写
     * @param name
     * @return
     */
    private String firstLowerName(String name) {
        name = name.substring(0, 1).toLowerCase() + name.substring(1);
       return  name;
    }
}
 

猜你喜欢

转载自my.oschina.net/u/2510361/blog/1794042