package org.jboss.deployment;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.HashMap;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.jboss.mx.loading.LoaderRepositoryFactory;
import org.jboss.mx.loading.LoaderRepositoryFactory.LoaderRepositoryConfig;
import org.jboss.mx.util.MBeanProxyExt;
import org.jboss.net.protocol.URLLister;
import org.jboss.net.protocol.URLListerFactory;
import org.jboss.system.ServiceControllerMBean;
import org.jboss.system.server.ServerConfig;
import org.jboss.system.server.ServerConfigLocator;
import org.jboss.util.StringPropertyReplacer;
import org.jboss.util.Strings;
import org.jboss.util.xml.JBossEntityResolver;
import org.jboss.util.stream.Streams;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class SARDeployer
extends SubDeployerSupport
implements SubDeployer, SARDeployerMBean
{
private ServiceControllerMBean serviceController;
private File dataDir;
private URL serverHomeURL;
private HashMap serviceDeploymentMap = new HashMap();
private boolean useNamespaceAwareParser;
public boolean isUseNamespaceAwareParser()
{
return useNamespaceAwareParser;
}
public void setUseNamespaceAwareParser(boolean useNamespaceAwareParser)
{
this.useNamespaceAwareParser = useNamespaceAwareParser;
}
public DeploymentInfo getService(ObjectName serviceName)
{
DeploymentInfo di = null;
synchronized( serviceDeploymentMap )
{
di = (DeploymentInfo) serviceDeploymentMap.get(serviceName);
}
return di;
}
public boolean accepts(DeploymentInfo di)
{
String urlStr = di.url.toString();
return urlStr.endsWith("sar") || urlStr.endsWith("sar/") ||
urlStr.endsWith("deployer") || urlStr.endsWith("deployer/") ||
urlStr.endsWith("service.xml") || urlStr.endsWith("deployer.xml");
}
public void init(DeploymentInfo di)
throws DeploymentException
{
try
{
if (di.url.getPath().endsWith("/"))
{
di.watch = new URL(di.url, "META-INF/jboss-service.xml");
}
else
{
di.watch = di.url;
}
parseDocument(di);
NodeList loaders = di.document.getElementsByTagName("loader-repository");
if( loaders.getLength() > 0 )
{
Element loader = (Element) loaders.item(0);
LoaderRepositoryConfig config = LoaderRepositoryFactory.parseRepositoryConfig(loader);
di.setRepositoryInfo(config);
}
parseXMLClasspath(di);
NodeList lds = di.document.getElementsByTagName("local-directory");
log.debug("about to copy " + lds.getLength() + " local directories");
for (int i = 0; i< lds.getLength(); i++)
{
Element ld = (Element)lds.item(i);
String path = ld.getAttribute("path");
log.debug("about to copy local directory at " + path);
log.debug("copying from " + di.localUrl + path + " -> " + dataDir);
inflateJar(di.localUrl, dataDir, path);
}
}
catch (DeploymentException de)
{
throw de;
}
catch (Exception e)
{
throw new DeploymentException(e);
}
super.init(di);
}
public void create(DeploymentInfo di)
throws DeploymentException
{
try
{
log.debug("Deploying SAR, create step: url " + di.url);
ObjectName uclName = di.ucl.getObjectName();
if( getServer().isRegistered(uclName) == false )
{
log.debug("Registering service UCL="+uclName);
getServer().registerMBean(di.ucl, uclName);
}
List mbeans = di.mbeans;
mbeans.clear();
List descriptorMbeans = serviceController.install(di.document.getDocumentElement(), uclName);
mbeans.addAll(descriptorMbeans);
for (Iterator iter = di.mbeans.iterator(); iter.hasNext(); )
{
ObjectName service = (ObjectName)iter.next();
serviceController.create(service);
synchronized( this.serviceDeploymentMap )
{
serviceDeploymentMap.put(service, di);
}
}
super.create(di);
}
catch(DeploymentException e)
{
log.debug("create operation failed for package "+ di.url, e);
destroy(di);
throw e;
}
catch (Exception e)
{
log.debug("create operation failed for package "+ di.url, e);
destroy(di);
throw new DeploymentException("create operation failed for package "
+ di.url, e);
}
}
public void start(DeploymentInfo di) throws DeploymentException
{
log.debug("Deploying SAR, start step: url " + di.url);
try
{
for (Iterator iter = di.mbeans.iterator(); iter.hasNext(); )
{
ObjectName service = (ObjectName)iter.next();
serviceController.start(service);
}
super.start(di);
}
catch (Exception e)
{
stop(di);
destroy(di);
throw new DeploymentException("start operation failed on package "
+ di.url, e);
}
}
public void stop(DeploymentInfo di)
{
log.debug("undeploying document " + di.url);
List services = di.mbeans;
int lastService = services.size();
for (ListIterator i = services.listIterator(lastService); i.hasPrevious();)
{
ObjectName name = (ObjectName)i.previous();
log.debug("stopping mbean " + name);
try
{
serviceController.stop(name);
}
catch (Exception e)
{
log.error("Could not stop mbean: " + name, e);
} }
try
{
super.stop(di);
}
catch(Exception ignore)
{
}
}
public void destroy(DeploymentInfo di)
{
List services = di.mbeans;
int lastService = services.size();
for (ListIterator i = services.listIterator(lastService); i.hasPrevious();)
{
ObjectName name = (ObjectName)i.previous();
log.debug("destroying mbean " + name);
synchronized( serviceDeploymentMap )
{
serviceDeploymentMap.remove(name);
}
try
{
serviceController.destroy(name);
}
catch (Exception e)
{
log.error("Could not destroy mbean: " + name, e);
} }
for (ListIterator i = services.listIterator(lastService); i.hasPrevious();)
{
ObjectName name = (ObjectName)i.previous();
log.debug("removing mbean " + name);
try
{
serviceController.remove(name);
}
catch (Exception e)
{
log.error("Could not remove mbean: " + name, e);
} }
try
{
ObjectName uclName = di.ucl.getObjectName();
if( getServer().isRegistered(uclName) == true )
{
log.debug("Unregistering service UCL="+uclName);
getServer().unregisterMBean(uclName);
}
}
catch(Exception ignore)
{
}
try
{
super.destroy(di);
}
catch(Exception ignore)
{
}
}
protected File[] listFiles(final String urlspec) throws Exception
{
URL url = Strings.toURL(urlspec);
File dir = new File(url.getFile());
File[] files = dir.listFiles(new java.io.FileFilter()
{
public boolean accept(File pathname)
{
String name = pathname.getName().toLowerCase();
return (name.endsWith(".jar") || name.endsWith(".zip"));
}
});
return files;
}
protected void parseXMLClasspath(DeploymentInfo di)
throws Exception
{
ArrayList classpath = new ArrayList();
URLListerFactory listerFactory = new URLListerFactory();
NodeList children = di.document.getDocumentElement().getChildNodes();
for (int i = 0; i < children.getLength(); i++)
{
if (children.item(i).getNodeType() == Node.ELEMENT_NODE)
{
Element classpathElement = (Element)children.item(i);
if (classpathElement.getTagName().equals("classpath"))
{
log.debug("Found classpath element: " + classpathElement);
if (!classpathElement.hasAttribute("codebase"))
{
throw new DeploymentException
("Invalid classpath element missing codebase: " + classpathElement);
}
String codebase = classpathElement.getAttribute("codebase").trim();
codebase = StringPropertyReplacer.replaceProperties(codebase);
String archives = null;
if (classpathElement.hasAttribute("archives"))
{
archives = classpathElement.getAttribute("archives").trim();
archives = StringPropertyReplacer.replaceProperties(archives);
if ("".equals(archives))
{
archives = null;
}
}
URL codebaseUrl;
if (".".equals(codebase))
{
codebaseUrl = new URL(di.url, "./");
}
else
{
if (archives != null && codebase.endsWith("/") == false)
{
codebase += "/";
}
codebaseUrl = new URL(serverHomeURL, codebase);
}
log.debug("codebase URL is " + codebaseUrl);
if (archives == null)
{
classpath.add(codebaseUrl);
log.debug("added codebase to classpath");
}
else
{
log.debug("listing codebase for archives matching " + archives);
URLLister lister = listerFactory.createURLLister(codebaseUrl);
log.debug("URLLister class is " + lister.getClass().getName());
classpath.addAll(lister.listMembers(codebaseUrl, archives));
}
}
} }
Iterator jars = classpath.iterator();
while (jars.hasNext())
{
URL neededURL = (URL) jars.next();
di.addLibraryJar(neededURL);
log.debug("deployed classes for " + neededURL);
}
}
protected void startService() throws Exception
{
super.startService();
serviceController = (ServiceControllerMBean)
MBeanProxyExt.create(ServiceControllerMBean.class,
ServiceControllerMBean.OBJECT_NAME, server);
ServerConfig config = ServerConfigLocator.locate();
dataDir = config.getServerDataDir();
serverHomeURL = config.getServerHomeURL();
}
protected ObjectName getObjectName(MBeanServer server, ObjectName name)
throws MalformedObjectNameException
{
return name == null ? OBJECT_NAME : name;
}
protected void parseDocument(DeploymentInfo di)
throws Exception
{
InputStream stream = null;
try
{
if (di.document == null)
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(useNamespaceAwareParser);
DocumentBuilder parser = factory.newDocumentBuilder();
URL docURL = di.localUrl;
URLClassLoader localCL = di.localCl;
if (di.isXML == false)
docURL = localCL.findResource("META-INF/jboss-service.xml");
if (docURL == null)
throw new DeploymentException("Failed to find META-INF/jboss-service.xml");
stream = docURL.openStream();
InputSource is = new InputSource(stream);
is.setSystemId(docURL.toString());
parser.setEntityResolver(new JBossEntityResolver());
di.document = parser.parse(is);
}
else
{
log.debug("Using existing deployment.document");
}
}
finally
{
try
{
stream.close();
}
catch (Exception ignore)
{
}
}
}
protected void inflateJar(URL url, File destDir, String path)
throws DeploymentException, IOException
{
String filename = url.getFile();
JarFile jarFile = new JarFile(filename);
try
{
for (Enumeration e = jarFile.entries(); e.hasMoreElements(); )
{
JarEntry entry = (JarEntry)e.nextElement();
String name = entry.getName();
if (path == null || name.startsWith(path))
{
File outFile = new File(destDir, name);
if (!outFile.exists())
{
if (entry.isDirectory())
{
outFile.mkdirs();
}
else
{
Streams.copyb(jarFile.getInputStream(entry),
new FileOutputStream(outFile));
}
} } }
}
finally
{
jarFile.close();
}
}
}