com.app.server.XMLDeploymentScanner.java Source code

Java tutorial

Introduction

Here is the source code for com.app.server.XMLDeploymentScanner.java

Source

package com.app.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.beans.PropertyVetoException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.naming.InitialContext;
import javax.naming.NamingException;

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.mchange.v2.c3p0.ComboPooledDataSource;
import com.app.server.util.DirectoryWatcher;

public class XMLDeploymentScanner implements XMLDeploymentScannerMBean {

    Digester xmlDigester;
    InitialContext ic;
    HashMap<String, XMLDataSources> xmlmap = new HashMap<String, XMLDataSources>();
    WebClassLoader userLibJarLoader;
    String userLibDir;
    ObjectName objName;
    Vector serviceList = null;
    ServerConfig serverConfig = null;
    MBeanServer mbeanServer = null;
    String isdeployer;
    Vector deployerlist;
    Logger log = Logger.getLogger(XMLDeploymentScanner.class);
    CopyOnWriteArrayList<String> datasources = new CopyOnWriteArrayList<String>();

    public void init(Vector deployerlist) {
        this.deployerlist = deployerlist;
    }

    public void init(Vector serviceList, ServerConfig serverConfig, MBeanServer mbeanServer) {
        this.serviceList = serviceList;
        this.serverConfig = serverConfig;
        this.mbeanServer = mbeanServer;
        this.userLibDir = serverConfig.getServiceslibdirectory();
        File userLibJars = new File(userLibDir);
        CopyOnWriteArrayList<String> jarList = new CopyOnWriteArrayList();
        getUsersJars(userLibJars, jarList);
        URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        userLibJarLoader = new WebClassLoader(loader.getURLs());
        for (String jarFilePath : jarList) {
            try {
                userLibJarLoader.addURL(new URL("file:/" + jarFilePath.replace("\\", "/")));
            } catch (Exception e) {
                log.error("Error in url " + "file:/" + jarFilePath.replace("\\", "/"), e);
                //e2.printStackTrace();            
            }
        }

        DigesterLoader xmlDigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

            protected void loadRules() {

                try {
                    loadXMLRules(new InputSource(new FileInputStream("./config/datasource-rules.xml")));
                } catch (Exception e) {
                    log.error("Error in loading config rules ./config/datasource-rules.xml", e);
                    //e.printStackTrace();
                }

            }
        });
        xmlDigester = xmlDigesterLoader.newDigester();
        try {
            ic = new InitialContext();
            ic.createSubcontext("java:");
        } catch (Exception e) {
            log.error("Error in creating subcontext", e);
        }
        log.info("initialized");
        // TODO Auto-generated constructor stub
    }

    public void getUsersJars(File dir, CopyOnWriteArrayList jarList) {
        if (dir.isDirectory()) {
            File[] children = dir.listFiles();
            for (int i = 0; i < children.length; i++) {
                log.info(children[i]);
                getUsersJars(children[i], jarList);
                if (children[i].isFile() && children[i].getName().endsWith(".jar"))
                    jarList.add(children[i].getAbsolutePath());
            }
        }

    }

    public void installDataSource(File file) {
        ClassLoader ctxCLassLoader = null;
        try {
            XMLDataSources xmlDataSources = (XMLDataSources) xmlDigester.parse("file:///" + file.getAbsolutePath());
            ctxCLassLoader = Thread.currentThread().getContextClassLoader();
            Thread.currentThread().setContextClassLoader(userLibJarLoader);
            CopyOnWriteArrayList<XMLDataSource> xmlDataSourceList = xmlDataSources.xmlDataSources;
            xmlmap.put(file.getAbsolutePath(), xmlDataSources);
            for (XMLDataSource xmlDataSource : xmlDataSourceList) {
                ComboPooledDataSource cpds = new ComboPooledDataSource();
                cpds.setDriverClass(xmlDataSource.getDriverclass());
                cpds.setJdbcUrl(xmlDataSource.getJdbcurl());
                cpds.setUser(xmlDataSource.getUsername());
                cpds.setPassword(xmlDataSource.getPassword());

                if (xmlDataSource.getMinpoolsize() != null) {
                    cpds.setMinPoolSize(new Integer(xmlDataSource.getMinpoolsize()));
                }
                if (xmlDataSource.getAcquireincrement() != null) {
                    cpds.setAcquireIncrement(new Integer(xmlDataSource.getAcquireincrement()));
                }
                if (xmlDataSource.getAcquireincrement() != null) {
                    cpds.setMaxPoolSize(new Integer(xmlDataSource.getMaxpoolsize()));
                }
                if (xmlDataSource.getMaxstatements() != null) {
                    cpds.setMaxStatements(new Integer(xmlDataSource.getMaxstatements()));
                }
                if (xmlmap.get(file.getAbsolutePath()) == null) {
                    ic.bind("java:/" + xmlDataSource.getJndi(), cpds);
                } else {
                    ic.rebind("java:/" + xmlDataSource.getJndi(), cpds);
                }
            }
        } catch (Exception ex) {
            log.error("Error in installing the data source", ex);
            //ex.printStackTrace();
        } finally {
            if (ctxCLassLoader != null) {
                Thread.currentThread().setContextClassLoader(ctxCLassLoader);
            }
        }
    }

    public boolean accept(URL url) {

        File file;
        try {
            file = new File(url.toURI());
            return file.getName().toLowerCase().endsWith("-datasource.xml");
        } catch (Exception e) {
            log.error("Syntax of the uri is incorrect", e);
            //e.printStackTrace();
        }
        return false;
    }

    public void deploy(URL url) {
        try {
            File file = new File(url.toURI());
            installDataSource(file);
            datasources.add(url.toURI().toString());
            log.info(url.toURI() + " deployed");
        } catch (Exception ex) {
            log.error("Error in deploying the datasource " + url, ex);
            //ex.printStackTrace();
        }

    }

    public void undeploy(URL url) {
        try {
            File file = new File(url.toURI());
            XMLDataSources xmlDataSources = xmlmap.get(file.getAbsolutePath());
            for (XMLDataSource xmlDataSource : xmlDataSources.xmlDataSources) {
                if (xmlDataSource != null)
                    ic.unbind("java:/" + xmlDataSource.getJndi());
            }
            datasources.remove(url.toURI().toString());
            log.info(url.toURI() + " undeployed");
        } catch (Exception e) {
            log.error("Could not undeploy the datasource " + url, e);
            //e.printStackTrace();
        }
    }

    public String getDeployer() {

        return this.isdeployer;
    }

    public void setDeployer(String isdeployer) {
        this.isdeployer = isdeployer;
    }

    public void setObjectName(ObjectName objName) {
        this.objName = objName;

    }

    public ObjectName getObjectName() {

        return this.objName;
    }

    public void start() {
        this.deployerlist.add(objName.getCanonicalName());
        log.info("started");
    }

    public void stop() {
        log.info("stopped");
    }

    public void destroy() {
        this.deployerlist.remove(objName.getCanonicalName());
        log.info("destroyed");
    }

    @Override
    public CopyOnWriteArrayList<String> getDssDeployed() {
        // TODO Auto-generated method stub
        return datasources;
    }

}