Java tutorial
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.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.reflect.Field; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Set; import java.util.Vector; import org.apache.commons.digester3.Digester; import org.apache.commons.digester3.binder.*; import org.apache.commons.digester3.xmlrules.FromXmlRulesModule; import org.apache.commons.vfs2.AllFileSelector; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.FileSelectInfo; import org.apache.commons.vfs2.FileSelector; import org.apache.commons.vfs2.FileType; import org.apache.commons.vfs2.impl.StandardFileSystemManager; import org.apache.commons.vfs2.impl.VFSClassLoader; import org.apache.jasper.JspC; import org.apache.log4j.Logger; import org.jgroups.JChannel; import org.jgroups.Message; import org.jgroups.Message.Flag; import org.omg.CORBA.portable.CustomValue; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import com.app.messaging.MessagingClassConstruct; import com.app.messaging.MessagingElem; import com.app.messaging.Queue; import com.app.messaging.Topic; import com.app.server.servlet.ServletMapping; import com.app.server.servlet.Servlets; import com.app.server.servlet.WebAppConfig; import com.app.server.util.ClassLoaderUtil; import com.app.server.util.FarmWarFileTransfer; import com.app.server.util.FileUtil; import com.app.services.ExecutorServicesConstruct; import ejb.logger.Log; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.jar.JarFile; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import javax.management.MBeanServer; import javax.management.ObjectName; /** * This class is the implementation of war deployer which deploys the war in * exploded form and configures the executor and its services, messaging. * * @author arun * */ public class WarDeployer implements WarDeployerMBean { String scanDirectory; Hashtable urlClassLoaderMap = new Hashtable(); Hashtable executorServiceMap = new Hashtable(); Hashtable messagingClassMap = new Hashtable(); Digester serverdigester; Digester messagedigester; Digester webxmldigester; MessagingElem messagingElem = new MessagingElem(); static int numberOfWarDeployed = 0; private String[] warDeployed; private CopyOnWriteArrayList warsDeployed = new CopyOnWriteArrayList(); ConcurrentHashMap servletMapping = new ConcurrentHashMap(); ConcurrentHashMap sessionObjects = new ConcurrentHashMap(); FarmWarFileTransfer farmWarFileTransfer = null; Logger log = Logger.getLogger(WarDeployer.class); String isdeployer = null; /* * public WarDeployer(String scanDirectory,String farmwarDir,String * clusterGroup,Hashtable urlClassLoaderMap,Hashtable * executorServiceMap,Hashtable messagingClassMap,ConcurrentHashMap * servletMapping,MessagingElem messagingElem,ConcurrentHashMap * sessionObjects){ this.scanDirectory=scanDirectory; * this.urlClassLoaderMap=urlClassLoaderMap; * this.executorServiceMap=executorServiceMap; * this.messagingClassMap=messagingClassMap; * this.servletMapping=servletMapping; this.sessionObjects=sessionObjects; * farmWarFileTransfer= * FarmWarFileTransfer.getInstance(scanDirectory+"/",farmwarDir * ,clusterGroup); try { farmWarFileTransfer.start(); } catch (Exception e2) * { e2.printStackTrace(); } try { * DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new * FromXmlRulesModule() { * * protected void loadRules() { try { * loadXMLRules( new InputSource(new * FileInputStream("./config/executorservices-config.xml"))); } catch * (FileNotFoundException e) { * e.printStackTrace(); } * * } }); serverdigester = serverdigesterLoader.newDigester(); } catch * (Exception e1) { e1.printStackTrace(); * } try { DigesterLoader serverdigesterLoader = * DigesterLoader.newLoader(new FromXmlRulesModule() { * * protected void loadRules() { try { * loadXMLRules( new InputSource(new * FileInputStream("./config/messagingclass-rules.xml"))); } catch * (FileNotFoundException e) { * e.printStackTrace(); } * * } }); messagedigester = serverdigesterLoader.newDigester(); } catch * (Exception e1) { e1.printStackTrace(); * } * * try{ DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new * FromXmlRulesModule() { * * protected void loadRules() { try { * loadXMLRules( new InputSource(new * FileInputStream("./config/webxml-rules.xml"))); } catch * (FileNotFoundException e) { * e.printStackTrace(); } * * } }); webxmldigester = serverdigesterLoader.newDigester(); } * catch(Exception ex){ //ex.printStackTrace(); } synchronized * (messagingElem) { this.messagingElem=messagingElem; ConcurrentHashMap * randomQueue=messagingElem.randomQueue; Set<String> * randomQueueSet=randomQueue.keySet(); Iterator<String> * ite=randomQueueSet.iterator(); while(ite.hasNext()){ Queue * queue=(Queue)randomQueue.get(ite.next()); ConcurrentHashMap * randomqueuemap=(ConcurrentHashMap)messagingClassMap.get("RandomQueue"); * if(randomqueuemap==null){ randomqueuemap=new ConcurrentHashMap(); * messagingClassMap.put("RandomQueue",randomqueuemap); } * CopyOnWriteArrayList randomqueuelist=(CopyOnWriteArrayList) * randomqueuemap.get(queue.getQueuename()); if(randomqueuelist==null) * randomqueuemap.put(queue.getQueuename(),new CopyOnWriteArrayList()); } * * ConcurrentHashMap roundrobinQueue=messagingElem.roundrobinQueue; * Set<String> roundrobinQueueSet=roundrobinQueue.keySet(); * ite=roundrobinQueueSet.iterator(); while(ite.hasNext()){ Queue * queue=(Queue)roundrobinQueue.get(ite.next()); ConcurrentHashMap * roundrobinqueuemap * =(ConcurrentHashMap)messagingClassMap.get("RoundRobinQueue"); * if(roundrobinqueuemap==null){ roundrobinqueuemap=new ConcurrentHashMap(); * messagingClassMap.put("RoundRobinQueue",roundrobinqueuemap); } * CopyOnWriteArrayList randomqueuelist=(CopyOnWriteArrayList) * roundrobinqueuemap.get(queue.getQueuename()); if(randomqueuelist==null) * roundrobinqueuemap.put(queue.getQueuename(),new CopyOnWriteArrayList()); * } * * ConcurrentHashMap topicMap=messagingElem.topicMap; Set<String> * topicSet=topicMap.keySet(); Iterator<String> iter=topicSet.iterator(); * while(iter.hasNext()){ Topic topic=(Topic)topicMap.get(iter.next()); * ConcurrentHashMap * topicmap=(ConcurrentHashMap)messagingClassMap.get("Topic"); * if(topicmap==null){ topicmap=new ConcurrentHashMap(); * messagingClassMap.put("Topic",topicmap); } CopyOnWriteArrayList * randomqueuelist=(CopyOnWriteArrayList) * topicmap.get(topic.getTopicname()); if(randomqueuelist==null) * topicmap.put(topic.getTopicname(),new CopyOnWriteArrayList()); } * log.info(messagingClassMap); } * * } */ Vector deployerList = null; Vector serviceList = null; ServerConfig serverConfig = null; MBeanServer mbeanServer = null; ObjectName objName = null; public void init(Vector deployerlist) { this.deployerList = deployerlist; } public void init(Vector serviceList, ServerConfig serverConfig, MBeanServer mbeanServer) { try { this.serviceList = serviceList; this.serverConfig = serverConfig; this.mbeanServer = mbeanServer; this.scanDirectory = serverConfig.getDeploydirectory(); DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() { protected void loadRules() { try { loadXMLRules(new InputSource(new FileInputStream("./config/executorservices-config.xml"))); } catch (Exception e) { log.error("Could not able to load config xml rules ./config/executorservices-config.xml", e); //e.printStackTrace(); } } }); serverdigester = serverdigesterLoader.newDigester(); } catch (Exception e1) { log.error("Could not create digester executorservices-config.xml", e1); //e1.printStackTrace(); } try { DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() { protected void loadRules() { try { loadXMLRules(new InputSource(new FileInputStream("./config/messagingclass-rules.xml"))); } catch (FileNotFoundException e) { log.error("Could not able to load config xml rules ./config/messagingclass-rules.xml", e); //e.printStackTrace(); } } }); messagedigester = serverdigesterLoader.newDigester(); DigesterLoader messagingdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() { protected void loadRules() { // TODO Auto-generated method stub try { loadXMLRules(new InputSource(new FileInputStream("./config/messagingconfig-rules.xml"))); } catch (Exception e) { log.error("Could not able to load xml config file ./config/messagingclass-rules.xml", e); e.printStackTrace(); } } }); Digester messagingdigester = messagingdigesterLoader.newDigester(); messagingElem = (MessagingElem) messagingdigester .parse(new InputSource(new FileInputStream("./config/messaging.xml"))); synchronized (messagingElem) { ConcurrentHashMap randomQueue = messagingElem.randomQueue; Set<String> randomQueueSet = randomQueue.keySet(); Iterator<String> ite = randomQueueSet.iterator(); while (ite.hasNext()) { Queue queue = (Queue) randomQueue.get(ite.next()); ConcurrentHashMap randomqueuemap = (ConcurrentHashMap) messagingClassMap.get("RandomQueue"); if (randomqueuemap == null) { randomqueuemap = new ConcurrentHashMap(); messagingClassMap.put("RandomQueue", randomqueuemap); } CopyOnWriteArrayList randomqueuelist = (CopyOnWriteArrayList) randomqueuemap .get(queue.getQueuename()); if (randomqueuelist == null) randomqueuemap.put(queue.getQueuename(), new CopyOnWriteArrayList()); } ConcurrentHashMap roundrobinQueue = messagingElem.roundrobinQueue; Set<String> roundrobinQueueSet = roundrobinQueue.keySet(); ite = roundrobinQueueSet.iterator(); while (ite.hasNext()) { Queue queue = (Queue) roundrobinQueue.get(ite.next()); ConcurrentHashMap roundrobinqueuemap = (ConcurrentHashMap) messagingClassMap .get("RoundRobinQueue"); if (roundrobinqueuemap == null) { roundrobinqueuemap = new ConcurrentHashMap(); messagingClassMap.put("RoundRobinQueue", roundrobinqueuemap); } CopyOnWriteArrayList randomqueuelist = (CopyOnWriteArrayList) roundrobinqueuemap .get(queue.getQueuename()); if (randomqueuelist == null) roundrobinqueuemap.put(queue.getQueuename(), new CopyOnWriteArrayList()); } ConcurrentHashMap topicMap = messagingElem.topicMap; Set<String> topicSet = topicMap.keySet(); Iterator<String> iter = topicSet.iterator(); while (iter.hasNext()) { Topic topic = (Topic) topicMap.get(iter.next()); ConcurrentHashMap topicmap = (ConcurrentHashMap) messagingClassMap.get("Topic"); if (topicmap == null) { topicmap = new ConcurrentHashMap(); messagingClassMap.put("Topic", topicmap); } CopyOnWriteArrayList randomqueuelist = (CopyOnWriteArrayList) topicmap .get(topic.getTopicname()); if (randomqueuelist == null) topicmap.put(topic.getTopicname(), new CopyOnWriteArrayList()); } //log.info(messagingClassMap); } } catch (Exception e1) { log.error("", e1); //e1.printStackTrace(); } try { DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() { protected void loadRules() { try { loadXMLRules(new InputSource(new FileInputStream("./config/webxml-rules.xml"))); } catch (FileNotFoundException e) { log.error("could not able to load xml config rules ./config/webxml-rules.xml", e); //e.printStackTrace(); } } }); webxmldigester = serverdigesterLoader.newDigester(); } catch (Exception ex) { log.error("could not able to create web.xml digester", ex); // ex.printStackTrace(); } log.info("initialized"); } /** * This method is the implementation of the war deployer which frequently * scans the deploy directory and if there is a change in war redeploys and * configures the map */ public void deploy(URL url) { File file; try { file = new File(url.toURI()); ClassLoader loader = (ClassLoader) getClass().getClassLoader(); //URL[] urls = loader.getURLs(); String filePath = file.getAbsolutePath(); // log.info("filePath"+filePath); filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".war")); File warDirectory = new File(filePath); if (warDirectory.exists()) { WebClassLoader webClassLoader = (WebClassLoader) urlClassLoaderMap .get(warDirectory.getAbsolutePath().replace("\\", "/")); synchronized (executorServiceMap) { try { File execxml = new File(warDirectory.getAbsolutePath().replace("\\", "/") + "/WEB-INF/" + "executorservices.xml"); if (execxml.exists() && webClassLoader != null) { new ExecutorServicesConstruct().removeExecutorServices(executorServiceMap, execxml, webClassLoader); } } catch (Exception e) { log.error("", e); //e.printStackTrace(); } // log.info("executorServiceMap"+executorServiceMap); } synchronized (messagingClassMap) { try { File messagingxml = new File(warDirectory.getAbsolutePath().replace("\\", "/") + "/WEB-INF/" + "messagingclass.xml"); if (messagingxml.exists() && webClassLoader != null) { new MessagingClassConstruct().removeMessagingClass(messagedigester, messagingxml, messagingClassMap); } } catch (Exception e) { log.error("", e); //e.printStackTrace(); } //log.info("executorServiceMap" // + executorServiceMap); } try { if (webClassLoader != null) { ClassLoaderUtil.cleanupJarFileFactory(ClassLoaderUtil.closeClassLoader(webClassLoader)); webClassLoader.close(); } } catch (IOException e) { log.error("Could not able to close webclassloader", e); //e.printStackTrace(); } //log.info("ServletMapping" + servletMapping); //log.info("warDirectory=" //+ warDirectory.getAbsolutePath().replace("\\", "/")); urlClassLoaderMap.remove(warDirectory.getAbsolutePath().replace("\\", "/")); WebAppConfig webAppConfig = (WebAppConfig) servletMapping .remove(warDirectory.getAbsolutePath().replace("\\", "/")); //System.gc(); deleteDir(warDirectory); warsDeployed.remove(url.toURI().toString()); removeServletFromSessionObject(webAppConfig, warDirectory.getAbsolutePath().replace("\\", "/")); numberOfWarDeployed--; } /*WebClassLoader customClassLoader = new WebClassLoader(new URL[]{},loader); synchronized (urlClassLoaderMap) { //log.info("WARDIRECTORY=" + warDirectory.getAbsolutePath()); urlClassLoaderMap.put( warDirectory.getAbsolutePath().replace("\\", "/"), customClassLoader); }*/ extractWar(file, loader); // log.info("War Deployed Successfully in path: "+filePath); //AddUrlToClassLoader(warDirectory, customClassLoader); numberOfWarDeployed++; warsDeployed.add(url.toURI().toString()); log.info(file + " Deployed"); //customClassLoader.close(); } catch (Exception e) { log.error("Could not able to deploy package " + url, e); //e1.printStackTrace(); } } public void removeServlets(String warDirectoryPath, String fileName) { WebAppConfig webAppConfig = (WebAppConfig) servletMapping.remove(warDirectoryPath); warsDeployed.remove(fileName); removeServletFromSessionObject(webAppConfig, warDirectoryPath); numberOfWarDeployed--; } public void removeServletFromSessionObject(WebAppConfig webAppConfig, String warDirectory) { Enumeration sessionKeys = sessionObjects.keys(); while (sessionKeys.hasMoreElements()) { String sessionKey = (String) sessionKeys.nextElement(); HttpSessionServer session = (HttpSessionServer) sessionObjects.get(sessionKey); ConcurrentHashMap servletMap = webAppConfig.getServlets(); Enumeration servlets = servletMap.keys(); while (servlets.hasMoreElements()) { String servletname = (String) servlets.nextElement(); Servlets servletsMapping = (Servlets) servletMap.get(servletname); /*log.info("SERVLETNAME:" + warDirectory + servletsMapping.getServletName() + session.getAttribute("SERVLETNAME:" + warDirectory + servletsMapping.getServletName()));*/ session.removeAttribute("SERVLETNAME:" + warDirectory + servletsMapping.getServletName()); } } } /** * 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/"); // log.info(webInfDirectory.getAbsolutePath()); if (webInfDirectory.exists()) { File[] jarfiles = webInfDirectory.listFiles(); for (int jarcount = 0; jarcount < jarfiles.length; jarcount++) { // log.info(jarfiles[jarcount]); if (jarfiles[jarcount].getName().endsWith(".jar")) { try { // //log.info("Adding absolute path "+jarfiles[jarcount].getAbsolutePath()); classLoader.addURL(new URL("file:" + jarfiles[jarcount].getAbsolutePath())); } catch (Exception e) { log.error("URL Syntax is incorrect", e); //e.printStackTrace(); } } } } } // To delete a war directory public static boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i = 0; i < children.length; i++) { boolean success = deleteDir(new File(dir, children[i])); if (!success) { return false; } } } // The directory is now empty so delete it return dir.delete(); } /** * This method deploys the war in exploded form and configures it. * * @param file * @param customClassLoader * @param warDirectoryPath */ public void extractWar(File file, ClassLoader classLoader) { StringBuffer classPath = new StringBuffer(); int numBytes; WebClassLoader customClassLoader = null; CopyOnWriteArrayList<URL> jarUrls = new CopyOnWriteArrayList<URL>(); try { ConcurrentHashMap jspMap = new ConcurrentHashMap(); ZipFile zip = new ZipFile(file); ZipEntry ze = null; // String fileName=file.getName(); String directoryName = file.getName(); directoryName = directoryName.substring(0, directoryName.indexOf('.')); try { /*ClassLoader classLoader = Thread.currentThread() .getContextClassLoader();*/ // log.info("file://"+warDirectoryPath+"/WEB-INF/classes/"); jarUrls.add(new URL("file:" + scanDirectory + "/" + directoryName + "/WEB-INF/classes/")); // new WebServer().addURL(new // URL("file://"+warDirectoryPath+"/"),customClassLoader); } catch (Exception e) { log.error("syntax of the URL is incorrect", e); //e1.printStackTrace(); } String fileDirectory; Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ze = entries.nextElement(); // //log.info("Unzipping " + ze.getName()); String filePath = scanDirectory + "/" + directoryName + "/" + ze.getName(); if (!ze.isDirectory()) { fileDirectory = filePath.substring(0, filePath.lastIndexOf('/')); } else { fileDirectory = filePath; } // //log.info(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(".jsp")) { jspMap.put(ze.getName(), filePath); } else if (ze.getName().endsWith(".jar")) { jarUrls.add(new URL("file:///" + scanDirectory + "/" + directoryName + "/" + ze.getName())); classPath.append(filePath); classPath.append(";"); } } } zip.close(); Set jsps = jspMap.keySet(); Iterator jspIterator = jsps.iterator(); classPath.append(scanDirectory + "/" + directoryName + "/WEB-INF/classes;"); jarUrls.add(new URL("file:" + scanDirectory + "/" + directoryName + "/WEB-INF/classes/;")); ArrayList<String> jspFiles = new ArrayList(); // log.info(classPath.toString()); if (jspIterator.hasNext()) { jarUrls.add(new URL("file:" + scanDirectory + "/temp/" + directoryName + "/")); customClassLoader = new WebClassLoader(jarUrls.toArray(new URL[jarUrls.size()]), classLoader); while (jspIterator.hasNext()) { String filepackageInternal = (String) jspIterator.next(); String filepackageInternalTmp = filepackageInternal; if (filepackageInternal.lastIndexOf('/') == -1) { filepackageInternal = ""; } else { filepackageInternal = filepackageInternal.substring(0, filepackageInternal.lastIndexOf('/')) .replace("/", "."); filepackageInternal = "." + filepackageInternal; } createDirectory(scanDirectory + "/temp/" + directoryName); File jspFile = new File((String) jspMap.get(filepackageInternalTmp)); String fName = jspFile.getName(); String fileNameWithoutExtension = fName.substring(0, fName.lastIndexOf(".jsp")) + "_jsp"; // String fileCreated=new JspCompiler().compileJsp((String) // jspMap.get(filepackageInternalTmp), // scanDirectory+"/temp/"+fileName, // "com.app.server"+filepackageInternal,classPath.toString()); synchronized (customClassLoader) { String fileNameInWar = filepackageInternalTmp; jspFiles.add(fileNameInWar.replace("/", "\\")); if (fileNameInWar.contains("/") || fileNameInWar.contains("\\")) { customClassLoader.addURL("/" + fileNameInWar.replace("\\", "/"), "com.app.server" + filepackageInternal.replace("WEB-INF", "WEB_002dINF") + "." + fileNameWithoutExtension); } else { customClassLoader.addURL("/" + fileNameInWar, "com.app.server" + filepackageInternal.replace("WEB-INF", "WEB_002dINF") + "." + fileNameWithoutExtension); } } } } else { customClassLoader = new WebClassLoader(jarUrls.toArray(new URL[jarUrls.size()]), classLoader); } String filePath = file.getAbsolutePath(); // log.info("filePath"+filePath); filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".war")); urlClassLoaderMap.put(filePath.replace("\\", "/"), customClassLoader); if (jspFiles.size() > 0) { ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); //Thread.currentThread().setContextClassLoader(customClassLoader); String classPathBefore = ""; try { JspCompiler jspc = new JspCompiler(); jspc.setUriroot(scanDirectory + "/" + directoryName); jspc.setAddWebXmlMappings(false); jspc.setListErrors(false); jspc.setCompile(true); jspc.setOutputDir(scanDirectory + "/temp/" + directoryName + "/"); jspc.setPackage("com.app.server"); StringBuffer buffer = new StringBuffer(); for (String jspFile : jspFiles) { buffer.append(","); buffer.append(jspFile); } String jsp = buffer.toString(); jsp = jsp.substring(1, jsp.length()); //log.info(jsp); classPathBefore = System.getProperty("java.class.path"); System.setProperty("java.class.path", System.getProperty("java.class.path") + ";" + classPath.toString().replace("/", "\\")); //jspc.setClassPath(System.getProperty("java.class.path")+";"+classPath.toString().replace("/", "\\")); jspc.setJspFiles(jsp); jspc.initCL(customClassLoader); jspc.execute(); //jspc.closeClassLoader(); //jspc.closeClassLoader(); } catch (Throwable je) { log.error("Error in compiling the jsp page", je); //je.printStackTrace(); } finally { System.setProperty("java.class.path", classPathBefore); //Thread.currentThread().setContextClassLoader(oldCL); } //Thread.currentThread().setContextClassLoader(customClassLoader); } try { File execxml = new File(scanDirectory + "/" + directoryName + "/WEB-INF/" + "executorservices.xml"); if (execxml.exists()) { new ExecutorServicesConstruct().getExecutorServices(serverdigester, executorServiceMap, execxml, customClassLoader); } } catch (Exception e) { log.error("error in getting executor services ", e); // e.printStackTrace(); } try { File messagingxml = new File( scanDirectory + "/" + directoryName + "/WEB-INF/" + "messagingclass.xml"); if (messagingxml.exists()) { new MessagingClassConstruct().getMessagingClass(messagedigester, messagingxml, customClassLoader, messagingClassMap); } } catch (Exception e) { log.error("Error in getting the messaging classes ", e); // e.printStackTrace(); } webxmldigester.setNamespaceAware(true); webxmldigester.setValidating(true); // digester.setRules(null); FileInputStream webxml = new FileInputStream( scanDirectory + "/" + directoryName + "/WEB-INF/" + "web.xml"); InputSource is = new InputSource(webxml); try { //log.info("SCHEMA"); synchronized (webxmldigester) { // webxmldigester.set("config/web-app_2_4.xsd"); WebAppConfig webappConfig = (WebAppConfig) webxmldigester.parse(is); servletMapping.put(scanDirectory + "/" + directoryName.replace("\\", "/"), webappConfig); } webxml.close(); } catch (Exception e) { log.error("Error in pasrsing the web.xml", e); //e.printStackTrace(); } //customClassLoader.close(); // ClassLoaderUtil.closeClassLoader(customClassLoader); } catch (Exception ex) { log.error("Error in Deploying war " + file.getAbsolutePath(), ex); } } public void extractWar(FileObject fileObject, WebClassLoader customClassLoader, StandardFileSystemManager fsManager) { int numBytes; try { String directoryName = fileObject.getName().getBaseName(); fileObject = fsManager.resolveFile("jar:" + fileObject.toString() + "!/"); StringBuffer classPath = new StringBuffer(); ConcurrentHashMap<String, String> jspMap = new ConcurrentHashMap<String, String>(); ArrayList<String> libs = new ArrayList<String>(); // String fileName=file.getName(); directoryName = directoryName.substring(0, directoryName.indexOf('.')); /*try { ((VFSClassLoader)customClassLoader.getParent()). // log.info("file://"+warDirectoryPath+"/WEB-INF/classes/"); customClassLoader.addURL(new URL("file:" + scanDirectory + "/" + directoryName + "/WEB-INF/classes/") ); // new WebServer().addURL(new // URL("file://"+warDirectoryPath+"/"),customClassLoader); } catch (Exception e) { log.error("syntax of the URL is incorrect", e); //e1.printStackTrace(); }*/ Vector<URL> libVec = unpack(fileObject, new File(scanDirectory + "/" + directoryName), fsManager, jspMap); //FileObject[] libraries=((VFSClassLoader)customClassLoader.getParent()).getFileObjects(); libVec.add(new URL("file:" + scanDirectory + "/" + directoryName + "/WEB-INF/classes/")); //URL[] liburl=new URL[libraries.length]; for (URL lib : libVec) { customClassLoader.addURL(lib); } //WebClassLoader web=new WebClassLoader(libVec.toArray(new URL[libVec.size()]),getClass().getClassLoader()); System.out.println(jspMap); System.out.println(libs); /*customClassLoader.addURL(new URL("file:" + scanDirectory + "/" + directoryName + "/WEB-INF/classes/") );*/ /*String fileDirectory; Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ze = entries.nextElement(); // //log.info("Unzipping " + ze.getName()); String filePath = scanDirectory + "/" + directoryName + "/" + ze.getName(); if (!ze.isDirectory()) { fileDirectory = filePath.substring(0, filePath.lastIndexOf('/')); } else { fileDirectory = filePath; } // //log.info(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(".jsp")) { jspMap.put(ze.getName(), filePath); } else if (ze.getName().endsWith(".jar")) { customClassLoader.addURL(new URL("file:///" + scanDirectory + "/" + directoryName + "/" + ze.getName())); classPath.append(filePath); classPath.append(";"); } } } zip.close();*/ Set jsps = jspMap.keySet(); Iterator jspIterator = jsps.iterator(); /*classPath.append(scanDirectory + "/" + directoryName + "/WEB-INF/classes/;");*/ ArrayList<String> jspFiles = new ArrayList(); // log.info(classPath.toString()); if (jspIterator.hasNext()) { /*customClassLoader=new WebClassLoader(new URL[]{new URL("file:" + scanDirectory + "/temp/" + directoryName + "/")},customClassLoader);*/ customClassLoader.addURL(new URL("file:" + scanDirectory + "/temp/" + directoryName + "/")); urlClassLoaderMap.put(serverConfig.getDeploydirectory() + "/" + directoryName, customClassLoader); } else { urlClassLoaderMap.put(serverConfig.getDeploydirectory() + "/" + directoryName, customClassLoader); } while (jspIterator.hasNext()) { String filepackageInternal = (String) jspIterator.next(); String filepackageInternalTmp = filepackageInternal; if (filepackageInternal.lastIndexOf('/') == -1) { filepackageInternal = ""; } else { filepackageInternal = filepackageInternal.substring(0, filepackageInternal.lastIndexOf('/')) .replace("/", "."); filepackageInternal = "." + filepackageInternal; } createDirectory(scanDirectory + "/temp/" + directoryName); File jspFile = new File((String) jspMap.get(filepackageInternalTmp)); String fName = jspFile.getName(); String fileNameWithoutExtension = fName.substring(0, fName.lastIndexOf(".jsp")) + "_jsp"; // String fileCreated=new JspCompiler().compileJsp((String) // jspMap.get(filepackageInternalTmp), // scanDirectory+"/temp/"+fileName, // "com.app.server"+filepackageInternal,classPath.toString()); synchronized (customClassLoader) { String fileNameInWar = filepackageInternalTmp; jspFiles.add(fileNameInWar.replace("/", "\\")); if (fileNameInWar.contains("/") || fileNameInWar.contains("\\")) { customClassLoader.addURL("/" + fileNameInWar.replace("\\", "/"), "com.app.server" + filepackageInternal.replace("WEB-INF", "WEB_002dINF") + "." + fileNameWithoutExtension); } else { customClassLoader.addURL("/" + fileNameInWar, "com.app.server" + filepackageInternal.replace("WEB-INF", "WEB_002dINF") + "." + fileNameWithoutExtension); } } } if (jspFiles.size() > 0) { ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); //Thread.currentThread().setContextClassLoader(customClassLoader); JspCompiler jspc = null; try { jspc = new JspCompiler(); jspc.setUriroot(scanDirectory + "/" + directoryName); jspc.setAddWebXmlMappings(false); jspc.setCompile(true); //jspc.setClassPath("d:/deploy/StrutsProj/WEB-INF/classes/"); jspc.setOutputDir(scanDirectory + "/temp/" + directoryName + "/"); jspc.setPackage("com.app.server"); StringBuffer buffer = new StringBuffer(); for (String jspFile : jspFiles) { buffer.append(","); buffer.append(jspFile); } String jsp = buffer.toString(); jsp = jsp.substring(1, jsp.length()); //log.info(jsp); jspc.setJspFiles(jsp); //jspc.init(); jspc.initCL(customClassLoader); jspc.execute(); //jspc.closeClassLoader(); } catch (Throwable je) { log.error("Error in compiling the jsp page", je); //je.printStackTrace(); } finally { //jspc.closeClassLoader(); //Thread.currentThread().setContextClassLoader(oldCL); } //Thread.currentThread().setContextClassLoader(customClassLoader); } //System.out.println(customClassLoader.loadClass("org.apache.struts.action.ActionForm")); try { File execxml = new File(scanDirectory + "/" + directoryName + "/WEB-INF/" + "executorservices.xml"); if (execxml.exists()) { new ExecutorServicesConstruct().getExecutorServices(serverdigester, executorServiceMap, execxml, customClassLoader); } } catch (Exception e) { log.error("error in getting executor services ", e); // e.printStackTrace(); } try { File messagingxml = new File( scanDirectory + "/" + directoryName + "/WEB-INF/" + "messagingclass.xml"); if (messagingxml.exists()) { new MessagingClassConstruct().getMessagingClass(messagedigester, messagingxml, customClassLoader, messagingClassMap); } } catch (Exception e) { log.error("Error in getting the messaging classes ", e); // e.printStackTrace(); } webxmldigester.setNamespaceAware(true); webxmldigester.setValidating(true); // digester.setRules(null); FileInputStream webxml = new FileInputStream( scanDirectory + "/" + directoryName + "/WEB-INF/" + "web.xml"); InputSource is = new InputSource(webxml); try { //log.info("SCHEMA"); synchronized (webxmldigester) { // webxmldigester.set("config/web-app_2_4.xsd"); WebAppConfig webappConfig = (WebAppConfig) webxmldigester.parse(is); servletMapping.put(scanDirectory + "/" + directoryName.replace("\\", "/"), webappConfig); } webxml.close(); } catch (Exception e) { log.error("Error in pasrsing the web.xml", e); //e.printStackTrace(); } // ClassLoaderUtil.closeClassLoader(customClassLoader); } catch (Exception ex) { log.error("Error in Deploying war " + fileObject.getName().getURI(), ex); } } public Vector<URL> unpack(final FileObject unpackFileObject, final File outputDir, StandardFileSystemManager fileSystemManager, ConcurrentHashMap<String, String> jsps) throws IOException { outputDir.mkdirs(); URLClassLoader webClassLoader; Vector<URL> libraries = new Vector<URL>(); final FileObject packFileObject = fileSystemManager.resolveFile(unpackFileObject.toString()); try { FileObject outputDirFileObject = fileSystemManager.toFileObject(outputDir); outputDirFileObject.copyFrom(packFileObject, new AllFileSelector()); FileObject[] jspFiles = outputDirFileObject.findFiles(new FileSelector() { public boolean includeFile(FileSelectInfo arg0) throws Exception { return arg0.getFile().getName().getBaseName().toLowerCase().endsWith(".jsp") || arg0.getFile().getName().getBaseName().toLowerCase().endsWith(".jar"); } public boolean traverseDescendents(FileSelectInfo arg0) throws Exception { // TODO Auto-generated method stub return true; } }); String replaceString = "file:///" + outputDir.getAbsolutePath().replace("\\", "/"); replaceString = replaceString.endsWith("/") ? replaceString : replaceString + "/"; // System.out.println(replaceString); for (FileObject jsplibs : jspFiles) { // System.out.println(outputDir.getAbsolutePath()); // System.out.println(jsp.getName().getFriendlyURI()); if (jsplibs.getName().getBaseName().endsWith(".jar")) { libraries.add(new URL(jsplibs.getName().getFriendlyURI())); } else { String relJspName = jsplibs.getName().getFriendlyURI().replace(replaceString, ""); jsps.put(relJspName, relJspName); } // System.out.println(relJspName); } } finally { packFileObject.close(); } return libraries; } /** * This method creates the directory for SAR * * @param dir */ public static 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(); } } } /** * @param args */ public static void main(String[] args) { /* * WarDeployer warDeployer=new WarDeployer("D:/WebServer/Deploy",new * HashMap(),new HashMap()); * * warDeployer.start(); try { warDeployer.join(); } catch * (InterruptedException e) { * e.printStackTrace(); } */ } /** * This method returns the number of war deployed */ @Override public int getNumberOfWarDeployed() { return numberOfWarDeployed; } /** * This method returns the war file names that is deployed */ @Override public String[] getWarNames() { warDeployed = (String[]) warsDeployed.toArray(new String[warsDeployed.size()]); return warDeployed; } /** * This method redeploys the war file again. */ @Override public void setRedeployTarget(String warName) { //log.info("RedeployTarget=" + warName); //log.info(scanDirectory + "/" + warName); if (warName != null && !warName.trim().equals("")) { File warDirectory = new File(scanDirectory + "/" + warName); if (warDirectory.isDirectory() && warDirectory.exists()) { deleteDir(warDirectory); numberOfWarDeployed--; } } } public void setObjectName(ObjectName objName) { this.objName = objName; } public ObjectName getObjectName() { return this.objName; } public boolean accept(URL url) { File file = null; try { file = new File(url.toURI()); return file.getName().toLowerCase().endsWith(".war"); } catch (Exception e) { log.error("syntax of the url is incorrect " + url, e); //e.printStackTrace(); } return false; } public void undeploy(URL url) { File file; try { file = new File(url.toURI()); String filePath = file.getAbsolutePath(); // log.info("filePath"+filePath); filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".war")); File warDirectory = new File(filePath); if (warDirectory.exists()) { WebClassLoader webClassLoader = (WebClassLoader) urlClassLoaderMap .get(warDirectory.getAbsolutePath().replace("\\", "/")); synchronized (executorServiceMap) { try { File execxml = new File(warDirectory.getAbsolutePath().replace("\\", "/") + "/WEB-INF/" + "executorservices.xml"); if (execxml.exists()) { new ExecutorServicesConstruct().removeExecutorServices(executorServiceMap, execxml, webClassLoader); } } catch (Exception e) { log.error("Error in configuring the executor services", e); //e.printStackTrace(); } // log.info("executorServiceMap"+executorServiceMap); } synchronized (messagingClassMap) { try { File messagingxml = new File(warDirectory.getAbsolutePath().replace("\\", "/") + "/WEB-INF/" + "messagingclass.xml"); if (messagingxml.exists()) { new MessagingClassConstruct().removeMessagingClass(messagedigester, messagingxml, messagingClassMap); } } catch (Exception e) { log.error("Error in configuring the messaging classes", e); //e.printStackTrace(); } //log.info("executorServiceMap" // + executorServiceMap); } //log.info("ServletMapping" + servletMapping); //log.info("warDirectory=" //+ warDirectory.getAbsolutePath().replace("\\", "/")); urlClassLoaderMap.remove(warDirectory.getAbsolutePath().replace("\\", "/")); WebAppConfig webAppConfig = (WebAppConfig) servletMapping .remove(warDirectory.getAbsolutePath().replace("\\", "/")); FileUtil.unloadDrivers(); try { if (webClassLoader != null) { ClassLoaderUtil.cleanupJarFileFactory(ClassLoaderUtil.closeClassLoader(webClassLoader)); webClassLoader.close(); } } catch (Exception e) { log.error("error in closing the classloader ", e); //e.printStackTrace(); } //System.gc(); deleteDir(warDirectory); warsDeployed.remove(url.toURI().toString()); removeServletFromSessionObject(webAppConfig, warDirectory.getAbsolutePath().replace("\\", "/")); numberOfWarDeployed--; log.info(file.getAbsolutePath() + " undeployed"); } file.delete(); } catch (Exception ex) { log.error("Error in undeploying the package " + url, ex); //e1.printStackTrace(); } } public String getDeployer() { return isdeployer; } public void setDeployer(String isdeployer) { this.isdeployer = isdeployer; } public void start() { if (objName != null) { this.deployerList.add(objName.getCanonicalName()); } log.info("started"); } public void stop() { log.info("stopped"); } public void destroy() { this.deployerList.remove(this.objName.getCanonicalName()); log.info("detroyed"); } public Hashtable getUrlClassLoaderMap() { // TODO Auto-generated method stub return this.urlClassLoaderMap; } public ConcurrentHashMap getServletMapping() { return servletMapping; } @Override public Hashtable getExecutorServiceMap() { // TODO Auto-generated method stub return this.executorServiceMap; } @Override public Hashtable getMessagingClassMap() { // TODO Auto-generated method stub return this.messagingClassMap; } @Override public CopyOnWriteArrayList<String> getWarsDeployed() { // TODO Auto-generated method stub return this.warsDeployed; } }