KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > caucho > ejb > EJBServer


1 /*
2  * Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
3  *
4  * This file is part of Resin(R) Open Source
5  *
6  * Each copy or derived work must preserve the copyright notice and this
7  * notice unmodified.
8  *
9  * Resin Open Source is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * Resin Open Source is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
17  * of NON-INFRINGEMENT. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with Resin Open Source; if not, write to the
22  *
23  * Free Software Foundation, Inc.
24  * 59 Temple Place, Suite 330
25  * Boston, MA 02111-1307 USA
26  *
27  * @author Scott Ferguson
28  */

29
30 package com.caucho.ejb;
31
32 import com.caucho.amber.cfg.EntityIntrospector;
33 import com.caucho.amber.manager.PersistenceEnvironmentListener;
34 import com.caucho.config.ConfigException;
35 import com.caucho.config.types.FileSetType;
36 import com.caucho.config.types.JndiBuilder;
37 import com.caucho.config.types.PathPatternType;
38 import com.caucho.config.types.Period;
39 import com.caucho.ejb.cfg.EjbMethod;
40 import com.caucho.ejb.metadata.Bean;
41 import com.caucho.ejb.protocol.ProtocolContainer;
42 import com.caucho.loader.Environment;
43 import com.caucho.loader.EnvironmentBean;
44 import com.caucho.loader.EnvironmentClassLoader;
45 import com.caucho.loader.EnvironmentListener;
46 import com.caucho.loader.EnvironmentLocal;
47 import com.caucho.log.Log;
48 import com.caucho.naming.Jndi;
49 import com.caucho.util.L10N;
50 import com.caucho.vfs.JarPath;
51 import com.caucho.vfs.MergePath;
52 import com.caucho.vfs.Path;
53 import com.caucho.vfs.Vfs;
54
55 import javax.annotation.PostConstruct;
56 import javax.jms.ConnectionFactory JavaDoc;
57 import javax.naming.NameNotFoundException JavaDoc;
58 import javax.naming.NamingException JavaDoc;
59 import javax.sql.DataSource JavaDoc;
60 import java.util.ArrayList JavaDoc;
61 import java.util.Iterator JavaDoc;
62 import java.util.logging.Level JavaDoc;
63 import java.util.logging.Logger JavaDoc;
64
65 /**
66  * Server containing all the EJBs for a given configuration.
67  *
68  * <p>Each protocol will extend the container to override Handle creation.
69  */

70 public class EJBServer
71   implements EnvironmentListener, EJBServerInterface, EnvironmentBean
72 {
73   static final L10N L = new L10N(EJBServer.class);
74   protected static final Logger JavaDoc log = Log.open(EJBServer.class);
75
76   private static EnvironmentLocal<EJBServer> _localServer
77     = new EnvironmentLocal<EJBServer>("caucho.ejb-server");
78
79   private static EnvironmentLocal<EjbServerManager> _localManager
80     = new EnvironmentLocal<EjbServerManager>();
81
82   protected static EnvironmentLocal<String JavaDoc> _localURL =
83     new EnvironmentLocal<String JavaDoc>("caucho.url");
84
85   private String JavaDoc _localJndiPrefix; // = "java:comp/env/cmp";
86
private String JavaDoc _remoteJndiPrefix; // = "java:comp/env/ejb";
87

88   private String JavaDoc _entityManagerJndiName = "java:comp/EntityManager";
89
90   private EjbServerManager _ejbManager;
91
92   private ArrayList JavaDoc<Path> _descriptors;
93   private ArrayList JavaDoc<Path> _ejbJars = new ArrayList JavaDoc<Path>();
94
95   private EntityIntrospector _entityIntrospector;
96
97   private MergePath _mergePath;
98
99   private String JavaDoc _urlPrefix;
100
101   private ArrayList JavaDoc<FileSetType> _configFileSetList =
102     new ArrayList JavaDoc<FileSetType>();
103
104   private DataSource JavaDoc _dataSource;
105   private boolean _createDatabaseSchema;
106   private boolean _validateDatabaseSchema = true;
107
108   private boolean _entityLoadLazyOnTransaction = true;
109
110   private String JavaDoc _resinIsolation;
111   private String JavaDoc _jdbcIsolation;
112
113   private ConnectionFactory JavaDoc _jmsConnectionFactory;
114
115   private int _entityCacheSize = 32 * 1024;
116   private long _entityCacheTimeout = 5000;
117
118   private boolean _forbidJVMCall;
119   private boolean _autoCompile = true;
120   private boolean _isAllowPOJO = false;
121
122   private String JavaDoc _startupMode;
123
124   private long _transactionTimeout = 0;
125
126   /**
127    * Create a server with the given prefix name.
128    */

129   public EJBServer()
130     throws ConfigException
131   {
132     _ejbManager = new EjbServerManager();
133
134     _urlPrefix = _localURL.get();
135
136     _mergePath = new MergePath();
137     _mergePath.addMergePath(Vfs.lookup());
138     _mergePath.addClassPath();
139
140     // XXX: to be reviewed. Workaround to add JARs
141
// to look up the persistence.xml and find the
142
// persistence root.
143
// See com.caucho.amber.manager.PersistenceEnvironmentListener
144
/*
145     try {
146       EnvironmentClassLoader envLoader = getClassLoader();
147
148       ArrayList<Loader> loaders = envLoader.getLoaders();
149
150       if (loaders.size() > 0) {
151
152         Loader loader = loaders.get(0);
153
154         if (loader instanceof SimpleLoader) {
155           // Gets the root dir for the deployed ear file
156           //
157           // /tmp/caucho/tck/deploy/<ear_dir>/META-INF/work/ejb
158           // /tmp/caucho/tck/deploy/<ear_dir>/*.jar
159
160           Path path = ((SimpleLoader) loader).getPath().lookup("../../..");
161
162           addJarUrls(envLoader, path);
163         }
164       }
165     } catch (Exception e) {
166       log.log(Level.WARNING, e.toString(), e);
167     }
168     */

169
170     // _entityIntrospector = new EntityIntrospector(_ejbManager);
171

172     Environment.addChildEnvironmentListener(new PersistenceEnvironmentListener());
173   }
174
175   public void addJarUrls(EnvironmentClassLoader loader, Path root)
176     throws java.io.IOException JavaDoc
177   {
178     Iterator JavaDoc<String JavaDoc> it = root.iterator();
179
180     while (it.hasNext()) {
181
182       String JavaDoc s = it.next();
183
184       Path path = root.lookup(s);
185
186       if (path.isDirectory()) {
187         addJarUrls(loader, path);
188       }
189       else if (s.endsWith(".jar")) {
190         JarPath jarPath = JarPath.create(path);
191
192         loader.addURL(jarPath);
193       }
194     }
195   }
196
197   /**
198    * Returns the local EJB server.
199    */

200   /*
201     public static EnvServerManager getLocalManager()
202     {
203     return EnvServerManager.getLocal();
204     }
205   */

206
207   /**
208    * Gets the environment class loader.
209    */

210   public EnvironmentClassLoader getClassLoader()
211   {
212     return _ejbManager.getClassLoader();
213   }
214
215   /**
216    * Sets the environment class loader.
217    */

218   public void setEnvironmentClassLoader(EnvironmentClassLoader env)
219   {
220   }
221
222   /**
223    * Sets the JNDI name.
224    */

225   public void setName(String JavaDoc name)
226   {
227     setJndiName(name);
228   }
229
230   /**
231    * Sets the JNDI name.
232    */

233   public void setJndiName(String JavaDoc name)
234   {
235     setJndiLocalPrefix(name);
236   }
237
238   /**
239    * Gets the JNDI name.
240    */

241   public void setJndiLocalPrefix(String JavaDoc name)
242   {
243     _localJndiPrefix = name;
244   }
245
246   /**
247    * Gets the JNDI name.
248    */

249   public String JavaDoc getLocalJndiPrefix()
250   {
251     return _localJndiPrefix;
252   }
253
254   /**
255    * Gets the remote JNDI name.
256    */

257   public void setJndiRemotePrefix(String JavaDoc name)
258   {
259     _remoteJndiPrefix = name;
260   }
261
262   /**
263    * Gets the JNDI name.
264    */

265   public String JavaDoc getRemoteJndiPrefix()
266   {
267     return _remoteJndiPrefix;
268   }
269
270   /**
271    * Sets the EntityManager JNDI name.
272    */

273   public void setEntityManagerJndiName(String JavaDoc name)
274   {
275     _entityManagerJndiName = name;
276   }
277
278   /**
279    * Gets the EntityManager JNDI name.
280    */

281   public String JavaDoc getEntityManagerJndiName()
282   {
283     return _entityManagerJndiName;
284   }
285
286   /**
287    * Sets the URL-prefix for all external beans.
288    */

289   public void setURLPrefix(String JavaDoc urlPrefix)
290   {
291     _urlPrefix = urlPrefix;
292   }
293
294   /**
295    * Gets the URL-prefix for all external beans.
296    */

297   public String JavaDoc getURLPrefix()
298   {
299     return _urlPrefix;
300   }
301
302   /**
303    * Sets the directory for the *.ejb files.
304    */

305   public void setConfigDirectory(Path dir)
306     throws ConfigException
307   {
308     FileSetType fileSet = new FileSetType();
309
310     fileSet.setDir(dir);
311
312     fileSet.addInclude(new PathPatternType("**/*.ejb"));
313
314     Path pwd = Vfs.lookup();
315
316     String JavaDoc dirPath = dir.getPath();
317     String JavaDoc pwdPath = pwd.getPath();
318
319     if (dirPath.startsWith(pwdPath)) {
320       String JavaDoc prefix = dirPath.substring(pwdPath.length());
321
322       fileSet.setUserPathPrefix(prefix);
323     }
324
325     _ejbManager.addConfigFiles(fileSet);
326   }
327
328   /**
329    * Adds an ejb descriptor.
330    */

331   public void addEJBDescriptor(String JavaDoc ejbDescriptor)
332   {
333     if (_descriptors == null)
334       _descriptors = new ArrayList JavaDoc<Path>();
335
336     Path path = _mergePath.lookup(ejbDescriptor);
337
338     _descriptors.add(path);
339   }
340
341   /**
342    * Adds an ejb jar.
343    */

344   public void addEJBJar(Path ejbJar)
345     throws ConfigException
346   {
347     if (! ejbJar.canRead() || ! ejbJar.isFile())
348       throw new ConfigException(L.l("<ejb-jar> {0} must refer to a valid jar file.",
349                                     ejbJar.getURL()));
350
351     _ejbJars.add(ejbJar);
352   }
353
354   /**
355    * Adds a bean.
356    */

357   public Bean createBean()
358   {
359     return new Bean(_ejbManager);
360   }
361
362   /**
363    * Adds a bean.
364    */

365   public void addBean(Bean bean)
366   {
367   }
368
369   /**
370    * Sets the data-source
371    */

372   public void setDataSource(DataSource JavaDoc dataSource)
373     throws ConfigException
374   {
375     _dataSource = dataSource;
376
377     if (_dataSource == null)
378       throw new ConfigException(L.l("<ejb-server> data-source must be a valid DataSource."));
379
380     _ejbManager.setDataSource(_dataSource);
381   }
382
383   /**
384    * Sets the data-source
385    */

386   public void setReadDataSource(DataSource JavaDoc dataSource)
387     throws ConfigException
388   {
389     _ejbManager.setReadDataSource(dataSource);
390   }
391
392   /**
393    * Sets the xa data-source
394    */

395   public void setXADataSource(DataSource JavaDoc dataSource)
396     throws ConfigException
397   {
398     _ejbManager.setXADataSource(dataSource);
399   }
400
401   /**
402    * Sets true if database schema should be generated automatically.
403    */

404   public void setCreateDatabaseSchema(boolean create)
405   {
406     _createDatabaseSchema = create;
407     _ejbManager.getAmberContainer().setCreateDatabaseTables(create);
408     _ejbManager.getAmberManager().setCreateDatabaseTables(create);
409   }
410
411   /**
412    * True if database schema should be generated automatically.
413    */

414   public boolean getCreateDatabaseSchema()
415   {
416     return _ejbManager.getAmberContainer().getCreateDatabaseTables();
417   }
418
419   /**
420    * Sets true if database schema should be validated automatically.
421    */

422   public void setValidateDatabaseSchema(boolean validate)
423   {
424     _validateDatabaseSchema = validate;
425   }
426
427   /**
428    * True if database schema should be validated automatically.
429    */

430   public boolean getValidateDatabaseSchema()
431   {
432     return _validateDatabaseSchema;
433   }
434
435   /**
436    * Sets true if database schema should be validated automatically.
437    */

438   public void setLoadLazyOnTransaction(boolean isLazy)
439   {
440     _ejbManager.setEntityLoadLazyOnTransaction(isLazy);
441   }
442
443   /**
444    * Sets the jndi name of the jmsConnectionFactory
445    */

446   public void setJMSConnectionFactory(JndiBuilder factory)
447     throws ConfigException, NamingException JavaDoc
448   {
449     Object JavaDoc obj = factory.getObject();
450
451     if (! (obj instanceof ConnectionFactory JavaDoc))
452       throw new ConfigException(L.l("`{0}' must be a JMS ConnectionFactory.", obj));
453
454     _jmsConnectionFactory = (ConnectionFactory JavaDoc) obj;
455   }
456
457   /**
458    * Gets the jndi name of the jmsQueueConnectionFactory
459    */

460   public ConnectionFactory JavaDoc getConnectionFactory()
461   {
462     return _jmsConnectionFactory;
463   }
464
465   /**
466    * Sets consumer max
467    */

468   public void setMessageConsumerMax(int consumerMax)
469     throws ConfigException, NamingException JavaDoc
470   {
471     _ejbManager.setMessageConsumerMax(consumerMax);
472   }
473
474   /**
475    * Gets the entity cache size.
476    */

477   public int getEntityCacheSize()
478   {
479     return _entityCacheSize;
480   }
481
482   /**
483    * Sets the entity cache size.
484    */

485   public void setCacheSize(int size)
486   {
487     _entityCacheSize = size;
488   }
489
490   /**
491    * Gets the entity cache timeout.
492    */

493   public long getEntityCacheTimeout()
494   {
495     return _entityCacheTimeout;
496   }
497
498   /**
499    * Sets the entity cache timeout.
500    */

501   public void setCacheTimeout(Period timeout)
502   {
503     _entityCacheTimeout = timeout.getPeriod();
504   }
505
506   /**
507    * Gets transaction timeout.
508    */

509   public long getTransactionTimeout()
510   {
511     return _transactionTimeout;
512   }
513
514   /**
515    * Sets the transaction timeout.
516    */

517   public void setTransactionTimeout(Period timeout)
518   {
519     _transactionTimeout = timeout.getPeriod();
520   }
521
522   /**
523    * Gets the Resin isolation.
524    */

525   public String JavaDoc getResinIsolation()
526   {
527     return _resinIsolation;
528   }
529
530   /**
531    * Sets the Resin isolation.
532    */

533   public void setResinIsolation(String JavaDoc resinIsolation)
534   {
535     _resinIsolation = resinIsolation;
536   }
537
538   /**
539    * Gets the JDBC isolation.
540    */

541   public String JavaDoc getJdbcIsolation()
542   {
543     return _jdbcIsolation;
544   }
545
546   /**
547    * Sets the JDBC isolation.
548    */

549   public void setJdbcIsolation(String JavaDoc jdbcIsolation)
550   {
551     _jdbcIsolation = jdbcIsolation;
552   }
553
554   /**
555    * If true, JVM calls are forbidden.
556    */

557   public void setForbidJvmCall(boolean forbid)
558   {
559     _forbidJVMCall = forbid;
560   }
561
562   /**
563    * If true, automatically compile old EJBs.
564    */

565   public boolean isAutoCompile()
566   {
567     return _autoCompile;
568   }
569
570   /**
571    * Set true to automatically compile old EJBs.
572    */

573   public void setAutoCompile(boolean autoCompile)
574   {
575     _autoCompile = autoCompile;
576   }
577
578   /**
579    * If true, allow POJO beans
580    */

581   public boolean isAllowPOJO()
582   {
583     return _isAllowPOJO;
584   }
585
586   /**
587    * Set true to allow POJO beans
588    */

589   public void setAllowPOJO(boolean allowPOJO)
590   {
591     _isAllowPOJO = allowPOJO;
592   }
593
594   /**
595    * Sets the EJB server startup mode.
596    */

597   public void setStartupMode(String JavaDoc startupMode)
598   {
599     _startupMode = startupMode;
600   }
601
602   public static EJBServer getLocal()
603   {
604     return _localServer.get();
605   }
606
607   public static EjbServerManager getLocalManager()
608   {
609     return _localManager.get();
610   }
611
612   /**
613    * Initialize the container.
614    */

615   @PostConstruct
616   public void init()
617     throws Exception JavaDoc
618   {
619     /*
620       try {
621       if (_localJndiName != null)
622       Jndi.rebindDeepShort(_localJndiName, this);
623       } catch (NamingException e) {
624       log.log(Level.FINER, e.toString(), e);
625       }
626     */

627
628     if (_localServer.getLevel() == null
629         || "java:comp/env/cmp".equals(_localJndiPrefix)) {
630       _localServer.set(this);
631       _localManager.set(_ejbManager);
632     }
633
634     try {
635       if (_localJndiPrefix != null)
636     Jndi.bindDeepShort(_localJndiPrefix + "/resin-ejb-server", _ejbManager);
637     } catch (NamingException JavaDoc e) {
638       log.log(Level.WARNING, e.toString(), e);
639     }
640
641     try {
642       if (_localJndiPrefix != null)
643     Jndi.bindDeepShort(_localJndiPrefix + "/caucho-ejb-admin", _ejbManager);
644     } catch (NamingException JavaDoc e) {
645       log.log(Level.WARNING, e.toString(), e);
646     }
647
648     try {
649       if (_entityManagerJndiName != null) {
650         Jndi.rebindDeepShort(_entityManagerJndiName,
651                              _ejbManager.getAmberManager().getEntityManager());
652       }
653     } catch (NamingException JavaDoc e) {
654       log.log(Level.FINER, e.toString(), e);
655     }
656
657     if ("manual".equals(_startupMode))
658       return;
659
660     manualInit();
661   }
662
663   /**
664    * Initialize the container.
665    */

666   public void manualInit()
667     throws Exception JavaDoc
668   {
669     try {
670       log.fine("Initializing ejb-server : local-jndi=" + _localJndiPrefix
671            + " remote-jndi=" + _remoteJndiPrefix);
672
673       ProtocolContainer protocol = new ProtocolContainer();
674       if (_urlPrefix != null)
675         protocol.setURLPrefix(_urlPrefix);
676
677       protocol.setServerManager(_ejbManager); // .getEnvServerManager());
678

679       _ejbManager.getProtocolManager().setProtocolContainer(protocol);
680       _ejbManager.setLocalJndiPrefix(_localJndiPrefix);
681       _ejbManager.setRemoteJndiPrefix(_remoteJndiPrefix);
682
683       //_ejbManager.setDataSource(_dataSource);
684
//_ejbManager.setCreateDatabaseSchema(_createDatabaseSchema);
685
_ejbManager.setValidateDatabaseSchema(_validateDatabaseSchema);
686       _ejbManager.setJMSConnectionFactory(_jmsConnectionFactory);
687       _ejbManager.setCacheSize(_entityCacheSize);
688       _ejbManager.setCacheTimeout(_entityCacheTimeout);
689       _ejbManager.setTransactionTimeout(_transactionTimeout);
690       _ejbManager.setAllowJVMCall(! _forbidJVMCall);
691       _ejbManager.setAutoCompile(_autoCompile);
692       _ejbManager.setAllowPOJO(isAllowPOJO());
693
694       int resinIsolation = -1;
695
696       if (_resinIsolation == null) {
697       }
698       else if (_resinIsolation.equals("row-locking"))
699         resinIsolation = EjbMethod.RESIN_ROW_LOCKING;
700       else if (_resinIsolation.equals("database"))
701         resinIsolation = EjbMethod.RESIN_DATABASE;
702       else {
703         throw new ConfigException(L.l("resin-isolation may only be `row-locking' or `database' in EJBServer, not `{0}'", _resinIsolation));
704       }
705
706       _ejbManager.setResinIsolation(resinIsolation);
707
708       int jdbcIsolation = -1;
709
710       if (_jdbcIsolation == null) {
711       }
712       else if (_jdbcIsolation.equals("none"))
713         jdbcIsolation = java.sql.Connection.TRANSACTION_NONE;
714       else if (_jdbcIsolation.equals("read-committed"))
715         jdbcIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED;
716       else if (_jdbcIsolation.equals("read-uncommitted"))
717         jdbcIsolation = java.sql.Connection.TRANSACTION_READ_UNCOMMITTED;
718       else if (_jdbcIsolation.equals("repeatable-read"))
719         jdbcIsolation = java.sql.Connection.TRANSACTION_REPEATABLE_READ;
720       else if (_jdbcIsolation.equals("serializable"))
721         jdbcIsolation = java.sql.Connection.TRANSACTION_SERIALIZABLE;
722       else
723         throw new ConfigException(L.l("unknown value for jdbc-isolation at `{0}'",
724                                       _jdbcIsolation));
725
726       _ejbManager.setJDBCIsolation(jdbcIsolation);
727
728       // _entityIntrospector.init();
729

730       initAllEjbs();
731
732       _ejbManager.init();
733
734       /*
735         String name = _jndiName;
736         if (! name.startsWith("java:"))
737         name = "java:comp/env/" + name;
738
739         Jndi.bindDeep(name, this);
740       */

741
742       Environment.addEnvironmentListener(this);
743     } catch (Exception JavaDoc e) {
744       log.log(Level.WARNING, e.toString(), e);
745
746       throw e;
747     }
748   }
749
750   /**
751    * Initialize all EJBs for any *.ejb or ejb-jar.xml in the WEB-INF or
752    * in a META-INF in the classpath.
753    */

754   public void initEJBs()
755     throws Exception JavaDoc
756   {
757     manualInit();
758   }
759
760   /**
761    * Initialize all EJBs for any *.ejb or ejb-jar.xml in the WEB-INF or
762    * in a META-INF in the classpath.
763    */

764   private void initAllEjbs()
765     throws Exception JavaDoc
766   {
767     addEJBJars();
768
769     if (_descriptors != null) {
770       for (int i = 0; i < _descriptors.size(); i++) {
771         Path path = _descriptors.get(i);
772
773         // XXX: app.addDepend(path);
774
_ejbManager.addEJBPath(path, path);
775       }
776     }
777   }
778
779   private void addEJBJars()
780     throws Exception JavaDoc
781   {
782     for (int i = 0; i < _ejbJars.size(); i++) {
783       Path path = _ejbJars.get(i);
784
785       Environment.addDependency(path);
786
787       JarPath jar = JarPath.create(path);
788
789       _ejbManager.addEJBJar(jar);
790     }
791   }
792
793   /**
794    * Return the server for a given path and ejbName
795    *
796    * @param path the archive-path or expand-path of a module
797    */

798   public AbstractServer getServer(Path path, String JavaDoc ejbName)
799     throws NameNotFoundException JavaDoc
800   {
801     return _ejbManager.getServer(path, ejbName);
802   }
803
804   /**
805    * Handles the case where a class loader is activated.
806    */

807   public void environmentStart(EnvironmentClassLoader loader)
808   {
809   }
810
811   /**
812    * Handles the case where a class loader is dropped.
813    */

814   public void environmentStop(EnvironmentClassLoader loader)
815   {
816     close();
817   }
818
819   public void close()
820   {
821     _ejbManager.destroy();
822   }
823
824 }
825
826
Popular Tags