KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > ejb3 > embedded > EJB3StandaloneDeployer


1 /*
2 * JBoss, Home of Professional Open Source
3 * Copyright 2005, JBoss Inc., and individual contributors as indicated
4 * by the @authors tag. See the copyright.txt in the distribution for a
5 * full listing of individual contributors.
6 *
7 * This is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU Lesser General Public License as
9 * published by the Free Software Foundation; either version 2.1 of
10 * the License, or (at your option) any later version.
11 *
12 * This software is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this software; if not, write to the Free
19 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21 */

22 package org.jboss.ejb3.embedded;
23
24 import java.io.File JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.InputStream JavaDoc;
27 import java.net.JarURLConnection JavaDoc;
28 import java.net.URL JavaDoc;
29 import java.net.URLClassLoader JavaDoc;
30 import java.net.URLConnection JavaDoc;
31 import java.net.MalformedURLException JavaDoc;
32 import java.util.ArrayList JavaDoc;
33 import java.util.Enumeration JavaDoc;
34 import java.util.HashSet JavaDoc;
35 import java.util.Hashtable JavaDoc;
36 import java.util.List JavaDoc;
37 import java.util.Map JavaDoc;
38 import java.util.Properties JavaDoc;
39 import java.util.Set JavaDoc;
40 import java.util.zip.ZipFile JavaDoc;
41 import javax.management.MBeanServer JavaDoc;
42 import javax.management.MBeanServerFactory JavaDoc;
43 import javax.naming.InitialContext JavaDoc;
44 import javax.naming.NamingEnumeration JavaDoc;
45
46 import org.jboss.dependency.spi.ControllerContext;
47 import org.jboss.ejb3.DeploymentUnit;
48 import org.jboss.ejb3.interceptor.InterceptorInfoRepository;
49 import org.jboss.kernel.Kernel;
50 import org.jboss.logging.Logger;
51 import org.jboss.virtual.VFS;
52 import org.jboss.virtual.VirtualFile;
53 import org.jboss.virtual.VirtualFileFilter;
54 import org.jboss.virtual.VisitorAttributes;
55 import org.jboss.virtual.plugins.context.jar.JarUtils;
56 import org.jboss.virtual.plugins.vfs.helpers.FilterVirtualFileVisitor;
57 import org.jboss.virtual.plugins.vfs.helpers.SuffixesExcludeFilter;
58
59 /**
60  * When initialized properly, this class will search for annotated classes and archives in your
61  * classpath and try to create EJB containers and EntityManagers automatically.
62  * <p/>
63  * All classes and jars must already be in your classpath for this deployer to work.
64  *
65  * @author <a HREF="mailto:bill@jboss.org">Bill Burke</a>
66  * @version $Revision: 57946 $
67  */

68 public class EJB3StandaloneDeployer
69 {
70    private static class DeployerUnit implements DeploymentUnit
71    {
72       private URL JavaDoc url;
73       private ClassLoader JavaDoc resourceLoader;
74       private ClassLoader JavaDoc loader;
75       private Map JavaDoc defaultProps;
76       private Hashtable JavaDoc jndiProperties;
77       private InterceptorInfoRepository interceptorInfoRepository = new InterceptorInfoRepository();
78       private VirtualFile virtualFile;
79
80       public DeployerUnit(ClassLoader JavaDoc loader, URL JavaDoc url, Map JavaDoc defaultProps, Hashtable JavaDoc jndiProperties)
81       {
82          this.loader = loader;
83          this.url = url;
84          URL JavaDoc[] urls = {url};
85          URL JavaDoc[] empty = {};
86          URLClassLoader JavaDoc parent = new URLClassLoader JavaDoc(empty)
87          {
88             @Override JavaDoc
89             public URL JavaDoc getResource(String JavaDoc name)
90             {
91                return null;
92             }
93          };
94          resourceLoader = new URLClassLoader JavaDoc(urls, parent);
95          this.defaultProps = defaultProps;
96          this.jndiProperties = jndiProperties;
97          try
98          {
99             VFS vfs = VFS.getVFS(url);
100             virtualFile = vfs.getRoot();
101          }
102          catch (IOException JavaDoc e)
103          {
104             throw new RuntimeException JavaDoc();
105          }
106       }
107
108       public URL JavaDoc getRelativeURL(String JavaDoc jar)
109       {
110          URL JavaDoc url = null;
111          try
112          {
113             url = new URL JavaDoc(jar);
114          }
115          catch (MalformedURLException JavaDoc e)
116          {
117             try
118             {
119                if (jar.startsWith(".."))
120                {
121                   if (getUrl() == null)
122                      throw new RuntimeException JavaDoc("relative <jar-file> not allowed when standalone deployment unit is used");
123                   String JavaDoc base = getUrl().toString();
124                   jar = jar.replaceAll("\\.\\./", "+");
125                   int idx = jar.lastIndexOf('+');
126                   jar = jar.substring(idx + 1);
127                   for (int i = 0; i < idx + 1; i++)
128                   {
129                      int slash = base.lastIndexOf('/');
130                      base = base.substring(0, slash + 1);
131                   }
132                   url = new URL JavaDoc(base + jar.substring(idx));
133                }
134                else
135                {
136                   File JavaDoc fp = new File JavaDoc(jar);
137                   url = fp.toURL();
138                }
139             }
140             catch (MalformedURLException JavaDoc e1)
141             {
142                throw new RuntimeException JavaDoc("Unable to find relative url: " + jar, e1);
143             }
144          }
145          return url;
146       }
147       
148
149       public List JavaDoc<VirtualFile> getResources(VirtualFileFilter filter)
150       {
151          VisitorAttributes va = new VisitorAttributes();
152          va.setLeavesOnly(true);
153          SuffixesExcludeFilter noJars = new SuffixesExcludeFilter(JarUtils.getSuffixes());
154          va.setRecurseFilter(noJars);
155          FilterVirtualFileVisitor visitor = new FilterVirtualFileVisitor(filter, va);
156          try
157          {
158             virtualFile.visit(visitor);
159          }
160          catch (IOException JavaDoc e)
161          {
162             throw new RuntimeException JavaDoc(e);
163          }
164          return visitor.getMatched();
165
166       }
167
168       public Hashtable JavaDoc getJndiProperties()
169       {
170          return jndiProperties;
171       }
172
173       public URL JavaDoc getPersistenceXml()
174       {
175          return getResourceLoader().getResource("META-INF/persistence.xml");
176       }
177
178       public URL JavaDoc getEjbJarXml()
179       {
180          return getResourceLoader().getResource("META-INF/ejb-jar.xml");
181       }
182
183       public URL JavaDoc getJbossXml()
184       {
185          return getResourceLoader().getResource("META-INF/jboss.xml");
186       }
187
188       public List JavaDoc<Class JavaDoc> getClasses()
189       {
190          return null;
191       }
192
193       public ClassLoader JavaDoc getClassLoader()
194       {
195          return loader;
196       }
197
198       public ClassLoader JavaDoc getResourceLoader()
199       {
200          return resourceLoader;
201       }
202
203       public String JavaDoc getShortName()
204       {
205          String JavaDoc url = getUrl().toString();
206          if (url.endsWith("/")) url = url.substring(0, url.length() - 1);
207
208          int dotIdx = url.lastIndexOf('.');
209          int slashIdx = url.lastIndexOf('/');
210          String JavaDoc name = null;
211          if (slashIdx > dotIdx)
212          {
213             name = url.substring(url.lastIndexOf('/') + 1);
214          }
215          else
216          {
217             name = url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('.'));
218          }
219          return name;
220       }
221
222       public URL JavaDoc getUrl()
223       {
224          return url;
225       }
226
227       public String JavaDoc getDefaultEntityManagerName()
228       {
229          return getShortName();
230       }
231
232       public Map JavaDoc getDefaultPersistenceProperties()
233       {
234          return defaultProps;
235       }
236
237       public InterceptorInfoRepository getInterceptorInfoRepository()
238       {
239          return interceptorInfoRepository;
240       }
241    }
242
243    protected static final Logger log = Logger.getLogger(EJB3StandaloneDeployer.class);
244
245    protected Set JavaDoc<URL JavaDoc> archives = new HashSet JavaDoc<URL JavaDoc>();
246    protected Set JavaDoc<URL JavaDoc> deployDirs = new HashSet JavaDoc<URL JavaDoc>();
247    protected Set JavaDoc<String JavaDoc> archivesByResource = new HashSet JavaDoc<String JavaDoc>();
248    protected Set JavaDoc<String JavaDoc> deployDirsByResource = new HashSet JavaDoc<String JavaDoc>();
249    protected ClassLoader JavaDoc classLoader;
250    private Map JavaDoc defaultPersistenceProperties;
251    private Hashtable JavaDoc jndiProperties;
252
253    private List JavaDoc<EJB3StandaloneDeployment> deployments = new ArrayList JavaDoc<EJB3StandaloneDeployment>();
254
255    private Kernel kernel;
256    private MBeanServer JavaDoc mbeanServer;
257
258
259    public EJB3StandaloneDeployer()
260    {
261       classLoader = Thread.currentThread().getContextClassLoader();
262    }
263
264    public Kernel getKernel()
265    {
266       return kernel;
267    }
268
269    public void setKernel(Kernel kernel)
270    {
271       this.kernel = kernel;
272    }
273
274    /**
275     * This is used by deployer for @Service beans that have @Management interfaces
276     *
277     * @return
278     */

279    public MBeanServer JavaDoc getMbeanServer()
280    {
281       return mbeanServer;
282    }
283
284    public void setMbeanServer(MBeanServer JavaDoc mbeanServer)
285    {
286       this.mbeanServer = mbeanServer;
287    }
288
289    /**
290     * A set of URLs of jar archives to search for annotated EJB classes
291     *
292     * @return this will not return null.
293     */

294    public Set JavaDoc<URL JavaDoc> getArchives()
295    {
296       return archives;
297    }
298
299    public void setArchives(Set JavaDoc archives)
300    {
301       new Exception JavaDoc().printStackTrace();
302       this.archives = archives;
303    }
304
305
306    /**
307     * Set of directories where there are jar files and directories
308     * The deployer will search through all archives and directories for
309     * annotated classes
310     *
311     * @return this will not return null.
312     */

313    public Set JavaDoc<URL JavaDoc> getDeployDirs()
314    {
315       return deployDirs;
316    }
317
318    public void setDeployDirs(Set JavaDoc deployDirs)
319    {
320       this.deployDirs = deployDirs;
321    }
322
323    /**
324     * All strings in this set will be used with ClassLoader.getResources()
325     * All URLs returned will be used to search for annotated classes.
326     *
327     * @return
328     */

329    public Set JavaDoc<String JavaDoc> getArchivesByResource()
330    {
331       return archivesByResource;
332    }
333
334    public void setArchivesByResource(Set JavaDoc archivesByResource)
335    {
336       this.archivesByResource = archivesByResource;
337    }
338
339    /**
340     * All strings in this set will be used with ClassLoader.getResources().
341     * All URLs returned will be create a set of deploy directories that will
342     * be used to find archives and directories that will be searched for annotated classes
343     *
344     * @return
345     */

346    public Set JavaDoc<String JavaDoc> getDeployDirsByResource()
347    {
348       return deployDirsByResource;
349    }
350
351    public void setDeployDirsByResource(Set JavaDoc deployDirsByResource)
352    {
353       this.deployDirsByResource = deployDirsByResource;
354    }
355
356    public ClassLoader JavaDoc getClassLoader()
357    {
358       return classLoader;
359    }
360
361
362    /**
363     * You can set the classloader that will be used
364     *
365     * @param classLoader
366     */

367    public void setClassLoader(ClassLoader JavaDoc classLoader)
368    {
369       this.classLoader = classLoader;
370    }
371
372    public Map JavaDoc getDefaultPersistenceProperties()
373    {
374       return defaultPersistenceProperties;
375    }
376
377
378    /**
379     * If you do not specifiy the default persistence properties, the resource
380     * "default.persistence.properties" will be search for in your classpath
381     *
382     * @param defaultPersistenceProperties
383     */

384    public void setDefaultPersistenceProperties(Map JavaDoc defaultPersistenceProperties)
385    {
386       this.defaultPersistenceProperties = defaultPersistenceProperties;
387    }
388
389    public Hashtable JavaDoc getJndiProperties()
390    {
391       return jndiProperties;
392    }
393
394    public void setJndiProperties(Hashtable JavaDoc jndiProperties)
395    {
396       this.jndiProperties = jndiProperties;
397    }
398
399    /**
400     * Returns a list of deployments found in this
401     *
402     * @return
403     */

404    public List JavaDoc<EJB3StandaloneDeployment> getDeployments()
405    {
406       return deployments;
407    }
408
409    public void setDeployments(List JavaDoc<EJB3StandaloneDeployment> deployments)
410    {
411       this.deployments = deployments;
412    }
413
414    public static URL JavaDoc getContainingUrlFromResource(URL JavaDoc url, String JavaDoc resource) throws Exception JavaDoc
415    {
416       if (url.getProtocol().equals("jar"))
417       {
418          URL JavaDoc jarURL = url;
419          URLConnection JavaDoc urlConn = jarURL.openConnection();
420          JarURLConnection JavaDoc jarConn = (JarURLConnection JavaDoc) urlConn;
421          // Extract the archive to dest/jarName-contents/archive
422
String JavaDoc parentArchiveName = jarConn.getJarFile().getName();
423          File JavaDoc fp = new File JavaDoc(parentArchiveName);
424          return fp.toURL();
425       }
426
427       // its a file
428
String JavaDoc base = url.toString();
429       int idx = base.lastIndexOf(resource);
430       base = base.substring(0, idx);
431       return new URL JavaDoc(base);
432    }
433
434    public static URL JavaDoc getDeployDirFromResource(URL JavaDoc url, String JavaDoc resource) throws Exception JavaDoc
435    {
436       if (url.getProtocol().equals("jar"))
437       {
438          URL JavaDoc jarURL = url;
439          URLConnection JavaDoc urlConn = jarURL.openConnection();
440          JarURLConnection JavaDoc jarConn = (JarURLConnection JavaDoc) urlConn;
441          // Extract the archive to dest/jarName-contents/archive
442
String JavaDoc parentArchiveName = jarConn.getJarFile().getName();
443          File JavaDoc fp = new File JavaDoc(parentArchiveName);
444          return fp.getParentFile().toURL();
445       }
446
447       // its a file
448
String JavaDoc base = url.toString();
449       int idx = base.lastIndexOf(resource);
450       base = base.substring(0, idx);
451       File JavaDoc fp = new File JavaDoc(base);
452       return fp.getParentFile().toURL();
453    }
454
455    public void create() throws Exception JavaDoc
456    {
457       try
458       {
459          for (String JavaDoc resource : deployDirsByResource)
460          {
461             Enumeration JavaDoc<URL JavaDoc> urls = classLoader.getResources(resource);
462             while (urls.hasMoreElements())
463             {
464                URL JavaDoc url = urls.nextElement();
465                URL JavaDoc deployUrl = getDeployDirFromResource(url, resource);
466                deployDirs.add(deployUrl);
467             }
468          }
469
470          for (URL JavaDoc url : deployDirs)
471          {
472             File JavaDoc dir = new File JavaDoc(url.toURI());
473             for (File JavaDoc fp : dir.listFiles())
474             {
475                if (fp.isDirectory())
476                {
477                   archives.add(fp.toURL());
478                   continue;
479                }
480                try
481                {
482                   ZipFile JavaDoc zip = new ZipFile JavaDoc(fp);
483                   zip.entries();
484                   zip.close();
485                   archives.add(fp.toURL());
486                }
487                catch (IOException JavaDoc e)
488                {
489                }
490             }
491          }
492
493          for (String JavaDoc resource : archivesByResource)
494          {
495             Enumeration JavaDoc<URL JavaDoc> urls = classLoader.getResources(resource);
496             while (urls.hasMoreElements())
497             {
498                URL JavaDoc url = urls.nextElement();
499                URL JavaDoc archiveUrl = getContainingUrlFromResource(url, resource);
500                archives.add(archiveUrl);
501             }
502          }
503
504          if (defaultPersistenceProperties == null)
505          {
506             InputStream JavaDoc is = Thread.currentThread().getContextClassLoader().getResourceAsStream("default.persistence.properties");
507             if (is == null) throw new RuntimeException JavaDoc("cannot find default.persistence.properties");
508             Properties JavaDoc defaults = new Properties JavaDoc();
509             defaults.load(is);
510             defaultPersistenceProperties = defaults;
511          }
512
513          for (URL JavaDoc archive : archives)
514          {
515             DeployerUnit du = new DeployerUnit(classLoader, archive, defaultPersistenceProperties, jndiProperties);
516             EJB3StandaloneDeployment deployment = new EJB3StandaloneDeployment(du, kernel, mbeanServer);
517             deployments.add(deployment);
518             deployment.create();
519          }
520       }
521       catch (Exception JavaDoc e)
522       {
523          e.printStackTrace();
524          throw e;
525       }
526    }
527
528    private void lookup(String JavaDoc name)
529    {
530       System.out.println("lookup " + name);
531       try {
532          InitialContext JavaDoc jndiContext = new InitialContext JavaDoc();
533          NamingEnumeration JavaDoc names = jndiContext.list(name);
534          if (names != null){
535             while (names.hasMore()){
536                System.out.println(" " + names.next());
537             }
538          }
539       } catch (Exception JavaDoc e){
540       }
541    }
542
543    public void start() throws Exception JavaDoc
544    {
545       try
546       {
547          loadMbeanServer();
548
549          for (EJB3StandaloneDeployment deployment : deployments)
550          {
551             if (deployment.getMbeanServer() == null)
552             {
553                deployment.setMbeanServer(mbeanServer);
554             }
555
556             deployment.start();
557             lookup("");
558          }
559       }
560       catch (Exception JavaDoc e)
561       {
562          e.printStackTrace();
563          throw e;
564       }
565    }
566
567    private void loadMbeanServer()
568    {
569       if (mbeanServer == null)
570       {
571          ControllerContext context = kernel.getController().getInstalledContext("MBeanServer");
572
573          if (context != null)
574             mbeanServer = (MBeanServer JavaDoc) context.getTarget();
575          else
576          {
577             ArrayList JavaDoc servers = MBeanServerFactory.findMBeanServer(null);
578             if (servers.size() == 0)
579                mbeanServer = MBeanServerFactory.createMBeanServer();
580             else
581                mbeanServer = (MBeanServer JavaDoc)MBeanServerFactory.findMBeanServer(null).get(0);
582          }
583       }
584    }
585
586    public void stop() throws Exception JavaDoc
587    {
588       for (EJB3StandaloneDeployment deployment : deployments)
589       {
590          deployment.stop();
591       }
592    }
593
594    public void destroy() throws Exception JavaDoc
595    {
596       for (EJB3StandaloneDeployment deployment : deployments)
597       {
598          deployment.destroy();
599       }
600    }
601 }
602
Popular Tags