com.app.server.util.ClassLoaderUtil.java Source code

Java tutorial

Introduction

Here is the source code for com.app.server.util.ClassLoaderUtil.java

Source

package com.app.server.util;

/*Copyright 2013 - 2015, Arun_Soundararajan (arun_srajan_2007@yahoo.com).and/or its affiliates.
    
All files in this repository or distribution are licensed under the
Apache License, Version 2.0 (the "License");
you may not use any files in this repository or distribution 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.*/

import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.jar.JarFile;

import org.apache.commons.vfs2.impl.VFSClassLoader;
import org.apache.log4j.Logger;

import com.app.server.WebClassLoader;

/**
 * This class is the classloader util
 * 
 * @author arun
 * 
 */
public class ClassLoaderUtil {
    /**
     * This method unlocks the jar file and closes the jar file in the
     * classloader
     * 
     * @param cl
     * @return
     */
    static Logger log = Logger.getLogger(ClassLoaderUtil.class);

    public static CopyOnWriteArrayList closeClassLoader(ClassLoader cl) {
        CopyOnWriteArrayList jars = new CopyOnWriteArrayList();
        boolean res = false;
        Class classURLClassLoader = null;
        if (cl instanceof URLClassLoader) {
            classURLClassLoader = URLClassLoader.class;
            if (cl instanceof WebClassLoader) {
                String url = "";
                CopyOnWriteArrayList webCLUrl = ((WebClassLoader) cl).geturlS();
                for (int index = 0; index < webCLUrl.size(); index++) {

                    try {
                        url = ((URL) webCLUrl.get(index)).toURI().toString();
                    } catch (URISyntaxException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    jars.add(url.replace("file:", "").replace("/", "\\").toUpperCase());
                }
            }
        } else if (cl instanceof VFSClassLoader) {
            classURLClassLoader = VFSClassLoader.class;
        }
        Field f = null;
        try {
            f = classURLClassLoader.getDeclaredField("ucp");
            //log.info(f);
        } catch (NoSuchFieldException e1) {
            // e1.printStackTrace();
            // log.info(e1.getMessage(), e1);

        }
        if (f != null) {
            f.setAccessible(true);
            Object obj = null;
            try {
                obj = f.get(cl);
            } catch (IllegalAccessException e1) {
                // e1.printStackTrace();
                // log.info(e1.getMessage(), e1);
            }
            if (obj != null) {
                final Object ucp = obj;
                f = null;
                try {
                    f = ucp.getClass().getDeclaredField("loaders");
                    //log.info(f);
                } catch (NoSuchFieldException e1) {
                    // e1.printStackTrace();
                    // log.info(e1.getMessage(), e1);
                }
                if (f != null) {
                    f.setAccessible(true);
                    ArrayList loaders = null;
                    try {
                        loaders = (ArrayList) f.get(ucp);
                        res = true;
                    } catch (IllegalAccessException e1) {
                        // e1.printStackTrace();
                    }
                    for (int i = 0; loaders != null && i < loaders.size(); i++) {
                        obj = loaders.get(i);
                        f = null;
                        try {
                            f = obj.getClass().getDeclaredField("jar");
                            // log.info(f);
                        } catch (NoSuchFieldException e) {
                            // e.printStackTrace();
                            // log.info(e.getMessage(), e);
                        }
                        if (f != null) {
                            f.setAccessible(true);
                            try {
                                obj = f.get(obj);
                            } catch (IllegalAccessException e1) {
                                // e1.printStackTrace();
                                // log.info(e1.getMessage(), e1);
                            }
                            if (obj instanceof JarFile) {
                                final JarFile jarFile = (JarFile) obj;
                                //log.info(jarFile.getName());
                                jars.add(jarFile.getName().replace("/", "\\").trim().toUpperCase());
                                // try {
                                // jarFile.getManifest().clear();
                                // } catch (IOException e) {
                                // // ignore
                                // }
                                try {
                                    jarFile.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    // ignore
                                    // log.info(e.getMessage(), e);
                                }
                            }
                        }
                    }
                }
            }
        }
        return jars;
    }

    public static boolean cleanupJarFileFactory(CopyOnWriteArrayList setJarFileNames2Close) {
        boolean res = false;
        Class classJarURLConnection = null;
        try {
            classJarURLConnection = Class.forName("sun.net.www.protocol.jar.JarURLConnection");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        if (classJarURLConnection == null) {
            return res;
        }
        Field f = null;
        try {
            f = classJarURLConnection.getDeclaredField("factory");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        if (f == null) {
            return res;
        }
        f.setAccessible(true);
        Object obj = null;
        try {
            obj = f.get(null);
        } catch (IllegalAccessException e) {
            // ignore
        }
        if (obj == null) {
            return res;
        }
        Class classJarFileFactory = obj.getClass();
        //
        HashMap fileCache = null;
        try {
            f = classJarFileFactory.getDeclaredField("fileCache");
            f.setAccessible(true);
            obj = f.get(null);
            if (obj instanceof HashMap) {
                fileCache = (HashMap) obj;
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        HashMap urlCache = null;
        try {
            f = classJarFileFactory.getDeclaredField("urlCache");
            f.setAccessible(true);
            obj = f.get(null);
            if (obj instanceof HashMap) {
                urlCache = (HashMap) obj;
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        if (urlCache != null) {
            HashMap urlCacheTmp = (HashMap) urlCache.clone();
            Iterator it = urlCacheTmp.keySet().iterator();
            while (it.hasNext()) {
                obj = it.next();
                if (!(obj instanceof JarFile)) {
                    continue;
                }
                JarFile jarFile = (JarFile) obj;
                if (setJarFileNames2Close.contains(jarFile.getName().trim().toUpperCase())) {
                    try {
                        jarFile.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (fileCache != null) {
                        fileCache.remove(jarFile);
                    }
                    urlCache.remove(jarFile);
                }
            }
            res = true;
        } else if (fileCache != null) {
            // urlCache := null
            HashMap fileCacheTmp = (HashMap) fileCache.clone();
            Iterator it = fileCacheTmp.keySet().iterator();
            while (it.hasNext()) {
                Object key = it.next();
                obj = fileCache.get(key);
                if (!(obj instanceof JarFile)) {
                    continue;
                }
                JarFile jarFile = (JarFile) obj;

                try {
                    jarFile.close();
                } catch (IOException e) {
                    // ignore
                }
                fileCache.remove(key);

            }
            res = true;
        }
        setJarFileNames2Close.clear();
        return res;
    }

}