com.web.server.SARDeployer.java Source code

Java tutorial

Introduction

Here is the source code for com.web.server.SARDeployer.java

Source

package com.web.server;

/*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.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.management.ManagementFactory;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

import javax.management.Attribute;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.management.ReflectionException;

import org.apache.commons.digester3.Digester;
import org.apache.commons.digester3.binder.DigesterLoader;
import org.apache.commons.digester3.xmlrules.FromXmlRulesModule;
import org.apache.log4j.Logger;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.web.messaging.MessagingClassConstruct;
import com.web.server.util.ClassLoaderUtil;
import com.web.services.ExecutorServicesConstruct;

/**
 * This class is the implementation of the SAR archive deployer which frequently listens
 * in the deploy directory and configures the sar and start the service. 
 * @author arun
 *
 */
public class SARDeployer extends Thread implements Runnable, SARDeployerMBean {
    private String deployDirectory;
    private Logger logger = Logger.getLogger(SARDeployer.class);
    int numberOfSarDeployed = 0;
    private CopyOnWriteArrayList sarsDeployed = new CopyOnWriteArrayList();
    Digester sardigester;
    private static SARDeployer sarDeployer = null;

    private SARDeployer(String deployDirectory) {
        this.deployDirectory = deployDirectory;
    }

    public static SARDeployer newInstance(String deployDirectory) {
        if (sarDeployer == null) {
            sarDeployer = new SARDeployer(deployDirectory);
        }
        return sarDeployer;
    }

    ConcurrentHashMap sarsMap = new ConcurrentHashMap();

    public void startDeployer() {
        if (!super.isAlive()) {
            super.start();
        }
        /*try{
           if(!sarDeployer.isAlive()){
        sarDeployer.start();
           }
           else{
        sarDeployer=new SARDeployer(deployDirectory);
        sarDeployer.start();
           }
        }
        catch(Exception ex){
           ex.printStackTrace();
        }*/
    }

    public void resumeDeployer() {
        super.resume();

    }

    public void stopDeployer() {
        super.suspend();
        /*try{
        sarDeployer.stop();
        sarDeployer.destroy();
        }
        catch(Exception ex){
           ex.printStackTrace();
        }*/
    }

    public void destroyDeployer() {
        super.stop();
        //super.destroy();
        /*try{
        sarDeployer.stop();
        sarDeployer.destroy();
        }
        catch(Exception ex){
           ex.printStackTrace();
        }*/
    }

    /**
     * This method is the implementation of the SAR deployer
     */
    public void run() {
        String filePath;
        FileInfo fileinfoTmp;
        ConcurrentHashMap filePrevMap = new ConcurrentHashMap();
        ConcurrentHashMap fileCurrMap = new ConcurrentHashMap();
        ;

        FileInfo filePrevLastModified;
        FileInfo fileCurrLastModified;
        DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

            protected void loadRules() {
                // TODO Auto-generated method stub
                try {
                    loadXMLRules(new InputSource(new FileInputStream("./config/sar-config.xml")));
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        });
        sardigester = serverdigesterLoader.newDigester();
        while (true) {
            try {
                File file = new File(deployDirectory);
                File[] files = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    if (files[i].isDirectory())
                        continue;
                    //Long lastModified=(Long) fileMap.get(files[i].getName());
                    if (files[i].getName().toLowerCase().endsWith(".sar")) {
                        filePath = files[i].getAbsolutePath();
                        //logger.info("filePath"+filePath);
                        filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".sar"));
                        File sarDirectory = new File(filePath + "sar");
                        fileinfoTmp = new FileInfo();
                        fileinfoTmp.setFile(files[i]);
                        fileinfoTmp.setLastModified(files[i].lastModified());
                        if (!sarDirectory.exists() || fileCurrMap.get(files[i].getName()) == null
                                && filePrevMap.get(files[i].getName()) == null) {
                            if (sarDirectory.exists()) {
                                deleteDir(sarDirectory);
                            }
                            try {
                                extractSar(files[i], sarDirectory.getAbsolutePath());
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            //System.out.println("War Deployed Successfully in path: "+filePath);
                            numberOfSarDeployed++;
                            logger.info(files[i] + " Deployed");
                            sarsDeployed.add(files[i].getName());
                            filePrevMap.put(files[i].getName(), fileinfoTmp);
                        }
                        fileCurrMap.put(files[i].getName(), fileinfoTmp);
                    }
                    /*if(lastModified==null||lastModified!=files[i].lastModified()){
                       fileMap.put(files[i].getName(),files[i].lastModified());
                    }*/
                }
                Set keyset = fileCurrMap.keySet();
                Iterator ite = keyset.iterator();
                String fileName;
                while (ite.hasNext()) {
                    fileName = (String) ite.next();
                    //logger.info("fileName"+fileName);
                    filePrevLastModified = (FileInfo) filePrevMap.get(fileName);
                    fileCurrLastModified = (FileInfo) fileCurrMap.get(fileName);
                    if (filePrevLastModified != null)
                        //logger.info("lastmodified="+filePrevLastModified.getLastModified());
                        //System.out.println("prevmodified"+fileCurrLastModified.getLastModified()+""+filePrevLastModified.getLastModified());
                        if (fileCurrLastModified != null) {
                            //System.out.println("prevmodified"+fileCurrLastModified.getLastModified());
                        }
                    if (filePrevLastModified == null
                            || filePrevLastModified.getLastModified() != fileCurrLastModified.getLastModified()) {
                        filePath = fileCurrLastModified.getFile().getAbsolutePath();
                        //logger.info("filePath"+filePath);
                        filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".sar"));
                        File sarDirectory = new File(filePath + "sar");
                        //logger.info("WARDIRECTORY="+warDirectory.getAbsolutePath());
                        if (sarDirectory.exists() && sarDirectory.isDirectory()) {
                            deleteDir(sarDirectory);
                            sarsDeployed.remove(fileName);
                            numberOfSarDeployed--;
                        }
                        try {
                            extractSar(fileCurrLastModified.getFile(), sarDirectory.getAbsolutePath());
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        //System.out.println("War Deployed Successfully in path: "+fileCurrLastModified.getFile().getAbsolutePath());
                        numberOfSarDeployed++;
                        sarsDeployed.add(fileName);
                        logger.info(filePath + ".sar Deployed");
                    }
                }
                keyset = filePrevMap.keySet();
                ite = keyset.iterator();
                while (ite.hasNext()) {
                    fileName = (String) ite.next();
                    filePrevLastModified = (FileInfo) filePrevMap.get(fileName);
                    fileCurrLastModified = (FileInfo) fileCurrMap.get(fileName);
                    if (fileCurrLastModified == null) {
                        filePath = filePrevLastModified.getFile().getAbsolutePath();
                        filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".sar"));
                        logger.info("filePath" + filePath);
                        File deleteDirectory = new File(filePath + "sar");
                        deleteDir(deleteDirectory);
                        numberOfSarDeployed--;
                        sarsDeployed.remove(fileName);
                        logger.info(filePath + ".sar Undeployed");
                    }
                }
                filePrevMap.keySet().removeAll(filePrevMap.keySet());
                filePrevMap.putAll(fileCurrMap);
                fileCurrMap.keySet().removeAll(fileCurrMap.keySet());
                //System.out.println("filePrevMap="+filePrevMap);
                //System.out.println("fileCurrMap="+fileCurrMap);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                System.out.println("Sar Deployed");
            }
        }
    }

    /**
     * This method adds the url to the classloader.
     * @param warDirectory
     * @param classLoader
     */
    private void AddUrlToClassLoader(File warDirectory, WebClassLoader classLoader) {
        File webInfDirectory = new File(warDirectory.getAbsolutePath() + "/WEB-INF/lib/");
        //logger.info(webInfDirectory.getAbsolutePath());
        if (webInfDirectory.exists()) {
            File[] jarfiles = webInfDirectory.listFiles();
            for (int jarcount = 0; jarcount < jarfiles.length; jarcount++) {
                //logger.info(jarfiles[jarcount]);
                if (jarfiles[jarcount].getName().endsWith(".jar")) {
                    try {
                        //   //System.out.println("Adding absolute path "+jarfiles[jarcount].getAbsolutePath());
                        new WebServer().addURL(new URL("file:" + jarfiles[jarcount].getAbsolutePath()),
                                classLoader);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * This method extracts the SAR archive and configures for the SAR and starts the services
     * @param file
     * @param warDirectoryPath
     * @throws IOException
     */
    public void extractSar(File file, String warDirectoryPath) throws IOException {
        ZipFile zip = new ZipFile(file);
        ZipEntry ze = null;
        String fileName = file.getName();
        fileName = fileName.substring(0, fileName.indexOf('.'));
        fileName += "sar";
        String fileDirectory;
        CopyOnWriteArrayList classPath = new CopyOnWriteArrayList();
        Enumeration<? extends ZipEntry> entries = zip.entries();
        int numBytes;
        while (entries.hasMoreElements()) {
            ze = entries.nextElement();
            // //System.out.println("Unzipping " + ze.getName());
            String filePath = deployDirectory + "/" + fileName + "/" + ze.getName();
            if (!ze.isDirectory()) {
                fileDirectory = filePath.substring(0, filePath.lastIndexOf('/'));
            } else {
                fileDirectory = filePath;
            }
            // //System.out.println(fileDirectory);
            createDirectory(fileDirectory);
            if (!ze.isDirectory()) {
                FileOutputStream fout = new FileOutputStream(filePath);
                byte[] inputbyt = new byte[8192];
                InputStream istream = zip.getInputStream(ze);
                while ((numBytes = istream.read(inputbyt, 0, inputbyt.length)) >= 0) {
                    fout.write(inputbyt, 0, numBytes);
                }
                fout.close();
                istream.close();
                if (ze.getName().endsWith(".jar")) {
                    classPath.add(filePath);
                }
            }
        }
        zip.close();
        URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        URL[] urls = loader.getURLs();
        WebClassLoader sarClassLoader = new WebClassLoader(urls);
        for (int index = 0; index < classPath.size(); index++) {
            System.out.println("file:" + classPath.get(index));
            new WebServer().addURL(new URL("file:" + classPath.get(index)), sarClassLoader);
        }
        new WebServer().addURL(new URL("file:" + deployDirectory + "/" + fileName + "/"), sarClassLoader);
        sarsMap.put(fileName, sarClassLoader);
        System.out.println(sarClassLoader.geturlS());
        try {
            Sar sar = (Sar) sardigester.parse(new InputSource(
                    new FileInputStream(deployDirectory + "/" + fileName + "/META-INF/" + "mbean-service.xml")));
            CopyOnWriteArrayList mbeans = sar.getMbean();
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            System.out.println(mbs);
            ObjectName objName;
            for (int index = 0; index < mbeans.size(); index++) {
                Mbean mbean = (Mbean) mbeans.get(index);
                System.out.println(mbean.getObjectname());
                System.out.println(mbean.getCls());
                objName = new ObjectName(mbean.getObjectname());
                Class helloWorldService = sarClassLoader.loadClass(mbean.getCls());
                Object obj = helloWorldService.newInstance();
                if (mbs.isRegistered(objName)) {
                    mbs.invoke(objName, "stopService", null, null);
                    //mbs.invoke(objName, "destroy", null, null);
                    mbs.unregisterMBean(objName);
                }
                mbs.registerMBean(obj, objName);
                CopyOnWriteArrayList attrlist = mbean.getMbeanAttribute();
                if (attrlist != null) {
                    for (int count = 0; count < attrlist.size(); count++) {
                        MBeanAttribute attr = (MBeanAttribute) attrlist.get(count);
                        Attribute mbeanattribute = new Attribute(attr.getName(), attr.getValue());
                        mbs.setAttribute(objName, mbeanattribute);
                    }
                }
                mbs.invoke(objName, "startService", null, null);
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MalformedObjectNameException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstanceAlreadyExistsException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MBeanRegistrationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NotCompliantMBeanException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstanceNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ReflectionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MBeanException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidAttributeValueException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (AttributeNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * This method creates the directory for SAR
     * @param dir
     */
    public void createDirectory(String dir) {
        String[] dirs = dir.split("/");
        String tmpDirPath = dirs[0];
        for (int i = 1; i < dirs.length; i++) {
            tmpDirPath += "/" + dirs[i];
            File file = new File(tmpDirPath);
            if (!file.exists()) {
                file.mkdir();
            }
        }
    }

    /**
     * This method undeployed the SAR
     * @param dir
     * @return
     */
    public boolean deleteDir(File dir) {
        String fileName = dir.getName();
        System.out.println("Dirname to be deleted" + fileName);
        Sar sar = null;
        try {
            sar = (Sar) sardigester.parse(new InputSource(
                    new FileInputStream(deployDirectory + "/" + fileName + "/META-INF/" + "mbean-service.xml")));
        } catch (IOException | SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        URLClassLoader sarClassLoader = (URLClassLoader) sarsMap.get(fileName);
        if (sarClassLoader != null) {
            ClassLoaderUtil.closeClassLoader(sarClassLoader);
            CopyOnWriteArrayList mbeans = sar.getMbean();
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            System.out.println(mbs);
            ObjectName objName;
            try {
                for (int index = 0; index < mbeans.size(); index++) {
                    Mbean mbean = (Mbean) mbeans.get(index);
                    System.out.println(mbean.getObjectname());
                    System.out.println(mbean.getCls());
                    objName = new ObjectName(mbean.getObjectname());
                    if (mbs.isRegistered(objName)) {
                        mbs.invoke(objName, "stopService", null, null);
                        //mbs.invoke(objName, "destroy", null, null);
                        mbs.unregisterMBean(objName);
                    }
                }
                sarsMap.remove(fileName);
            } catch (MalformedObjectNameException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (MBeanRegistrationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InstanceNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ReflectionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (MBeanException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return recursiveDelete(dir);

    }

    /**
     * This method recursively deletes the SAR directory
     * @param dir
     * @return
     */
    public boolean recursiveDelete(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = recursiveDelete(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // The directory is now empty so delete it
        return dir.delete();
    }

    /**
     * This method returns the number of SAR deployed.
     */
    @Override
    public int getNumberOfSarDeployed() {
        // TODO Auto-generated method stub
        return numberOfSarDeployed;
    }

    /**
     * This methiod returns the SAR deployer names
     */
    @Override
    public String[] getSars() {
        // TODO Auto-generated method stub
        String[] sarDeployed = (String[]) sarsDeployed.toArray(new String[sarsDeployed.size()]);
        return sarDeployed;
    }
}