KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > winstone > jndi > ContainerJNDIManager


1 /*
2  * Copyright 2003-2006 Rick Knowles <winstone-devel at lists sourceforge net>
3  * Distributed under the terms of either:
4  * - the common development and distribution license (CDDL), v1.0; or
5  * - the GNU Lesser General Public License, v2.1 or later
6  */

7 package winstone.jndi;
8
9 import java.lang.reflect.Constructor JavaDoc;
10 import java.lang.reflect.Method JavaDoc;
11 import java.util.ArrayList JavaDoc;
12 import java.util.Collection JavaDoc;
13 import java.util.HashMap JavaDoc;
14 import java.util.Iterator JavaDoc;
15 import java.util.List JavaDoc;
16 import java.util.Map JavaDoc;
17 import java.util.Properties JavaDoc;
18
19 import javax.naming.CompositeName JavaDoc;
20 import javax.naming.Context JavaDoc;
21 import javax.naming.InitialContext JavaDoc;
22 import javax.naming.Name JavaDoc;
23 import javax.naming.NamingException JavaDoc;
24
25 import winstone.JNDIManager;
26 import winstone.Logger;
27 import winstone.WinstoneResourceBundle;
28 import winstone.jndi.resourceFactories.WinstoneDataSource;
29
30 /**
31  * Implements a simple web.xml + command line arguments style jndi manager
32  *
33  * @author <a HREF="mailto:rick_knowles@hotmail.com">Rick Knowles</a>
34  * @version $Id: ContainerJNDIManager.java,v 1.3 2006/02/28 07:32:48 rickknowles Exp $
35  */

36 public class ContainerJNDIManager implements JNDIManager {
37     public static final WinstoneResourceBundle JNDI_RESOURCES = new WinstoneResourceBundle("winstone.jndi.LocalStrings");
38     
39     protected Map JavaDoc objectsToCreate;
40
41     /**
42      * Gets the relevant list of objects from the args, validating against the
43      * web.xml nodes supplied. All node addresses are assumed to be relative to
44      * the java:/comp/env context
45      */

46     public ContainerJNDIManager(Map JavaDoc args, List JavaDoc webXmlNodes, ClassLoader JavaDoc loader) {
47         // Build all the objects we wanted
48
this.objectsToCreate = new HashMap JavaDoc();
49         
50         Collection JavaDoc keys = new ArrayList JavaDoc(args != null ? args.keySet() : (Collection JavaDoc) new ArrayList JavaDoc());
51         for (Iterator JavaDoc i = keys.iterator(); i.hasNext();) {
52             String JavaDoc key = (String JavaDoc) i.next();
53
54             if (key.startsWith("jndi.resource.")) {
55                 String JavaDoc resName = key.substring(14);
56                 String JavaDoc className = (String JavaDoc) args.get(key);
57                 String JavaDoc value = (String JavaDoc) args.get("jndi.param." + resName
58                         + ".value");
59                 Logger.log(Logger.FULL_DEBUG, JNDI_RESOURCES,
60                         "ContainerJNDIManager.CreatingResourceArgs", resName);
61                 Object JavaDoc obj = createObject(resName.trim(), className.trim(),
62                         value, args, loader);
63                 if (obj != null)
64                     this.objectsToCreate.put(resName, obj);
65             }
66         }
67     }
68
69     /**
70      * Add the objects passed to the constructor to the JNDI Context addresses
71      * specified
72      */

73     public void setup() {
74         
75         try {
76             InitialContext JavaDoc ic = new InitialContext JavaDoc();
77             for (Iterator JavaDoc i = this.objectsToCreate.keySet().iterator(); i.hasNext();) {
78                 String JavaDoc name = (String JavaDoc) i.next();
79                 try {
80                     Name JavaDoc fullName = new CompositeName JavaDoc(name);
81                     Context JavaDoc currentContext = ic;
82                     while (fullName.size() > 1) {
83                         // Make contexts that are not already present
84
try {
85                             currentContext = currentContext
86                                     .createSubcontext(fullName.get(0));
87                         } catch (NamingException JavaDoc err) {
88                             currentContext = (Context JavaDoc) currentContext
89                                     .lookup(fullName.get(0));
90                         }
91                         fullName = fullName.getSuffix(1);
92                     }
93                     ic.bind(name, this.objectsToCreate.get(name));
94                     Logger.log(Logger.FULL_DEBUG, JNDI_RESOURCES,
95                             "ContainerJNDIManager.BoundResource", name);
96                 } catch (NamingException JavaDoc err) {
97                     Logger.log(Logger.ERROR, JNDI_RESOURCES,
98                                     "ContainerJNDIManager.ErrorBindingResource",
99                                     name, err);
100                 }
101             }
102             Logger.log(Logger.DEBUG, JNDI_RESOURCES,
103                     "ContainerJNDIManager.SetupComplete", "" + this.objectsToCreate.size());
104         } catch (NamingException JavaDoc err) {
105             Logger.log(Logger.ERROR, JNDI_RESOURCES,
106                     "ContainerJNDIManager.ErrorGettingInitialContext", err);
107         }
108     }
109
110     /**
111      * Remove the objects under administration from the JNDI Context, and then
112      * destroy the objects
113      */

114     public void tearDown() {
115         try {
116             InitialContext JavaDoc ic = new InitialContext JavaDoc();
117             for (Iterator JavaDoc i = this.objectsToCreate.keySet().iterator(); i
118                     .hasNext();) {
119                 String JavaDoc name = (String JavaDoc) i.next();
120                 try {
121                     ic.unbind(name);
122                 } catch (NamingException JavaDoc err) {
123                     Logger.log(Logger.ERROR, JNDI_RESOURCES,
124                             "ContainerJNDIManager.ErrorUnbindingResource", name,
125                             err);
126                 }
127                 Object JavaDoc unboundObject = this.objectsToCreate.get(name);
128                 if (unboundObject instanceof WinstoneDataSource)
129                     ((WinstoneDataSource) unboundObject).destroy();
130                 Logger.log(Logger.FULL_DEBUG, JNDI_RESOURCES,
131                         "ContainerJNDIManager.UnboundResource", name);
132             }
133             Logger.log(Logger.DEBUG, JNDI_RESOURCES,
134                     "ContainerJNDIManager.TeardownComplete", "" + this.objectsToCreate.size());
135         } catch (NamingException JavaDoc err) {
136             Logger.log(Logger.ERROR, JNDI_RESOURCES,
137                     "ContainerJNDIManager.ErrorGettingInitialContext", err);
138         }
139     }
140
141     /**
142      * Build an object to insert into the jndi space
143      */

144     protected Object JavaDoc createObject(String JavaDoc name, String JavaDoc className, String JavaDoc value,
145             Map JavaDoc args, ClassLoader JavaDoc loader) {
146         
147         if ((className == null) || (name == null))
148             return null;
149         
150         // Set context class loader
151
ClassLoader JavaDoc cl = Thread.currentThread().getContextClassLoader();
152         Thread.currentThread().setContextClassLoader(loader);
153         
154         try {
155             // If we are working with a datasource
156
if (className.equals("javax.sql.DataSource")) {
157                 try {
158                     return new WinstoneDataSource(name, extractRelevantArgs(args, name), loader);
159                 } catch (Throwable JavaDoc err) {
160                     Logger.log(Logger.ERROR, JNDI_RESOURCES,
161                             "ContainerJNDIManager.ErrorBuildingDatasource", name, err);
162                 }
163             }
164
165             // If we are working with a mail session
166
else if (className.equals("javax.mail.Session")) {
167                 try {
168                     Class JavaDoc smtpClass = Class.forName(className, true, loader);
169                     Method JavaDoc smtpMethod = smtpClass.getMethod("getInstance",
170                             new Class JavaDoc[] { Properties JavaDoc.class,
171                                     Class.forName("javax.mail.Authenticator") });
172                     return smtpMethod.invoke(null, new Object JavaDoc[] {
173                             extractRelevantArgs(args, name), null });
174                     //return Session.getInstance(extractRelevantArgs(args, name), null);
175
} catch (Throwable JavaDoc err) {
176                     Logger.log(Logger.ERROR, JNDI_RESOURCES,
177                                     "ContainerJNDIManager.ErrorBuildingMailSession",
178                                     name, err);
179                 }
180             }
181
182             // If unknown type, try to instantiate with the string constructor
183
else if (value != null) {
184                 try {
185                     Class JavaDoc objClass = Class.forName(className.trim(), true, loader);
186                     Constructor JavaDoc objConstr = objClass
187                             .getConstructor(new Class JavaDoc[] { String JavaDoc.class });
188                     return objConstr.newInstance(new Object JavaDoc[] { value });
189                 } catch (Throwable JavaDoc err) {
190                     Logger.log(Logger.ERROR, JNDI_RESOURCES,
191                             "ContainerJNDIManager.ErrorBuildingObject", new String JavaDoc[] {
192                                     name, className }, err);
193                 }
194             }
195                 
196             return null;
197             
198         } finally {
199             Thread.currentThread().setContextClassLoader(cl);
200         }
201     }
202
203     /**
204      * Rips the parameters relevant to a particular resource from the command args
205      */

206     private Properties JavaDoc extractRelevantArgs(Map JavaDoc input, String JavaDoc name) {
207         Properties JavaDoc relevantArgs = new Properties JavaDoc();
208         for (Iterator JavaDoc i = input.keySet().iterator(); i.hasNext();) {
209             String JavaDoc key = (String JavaDoc) i.next();
210             if (key.startsWith("jndi.param." + name + "."))
211                 relevantArgs.put(key.substring(12 + name.length()), input
212                         .get(key));
213         }
214         return relevantArgs;
215     }
216
217 }
218
Popular Tags