KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > lateralnz > common > util > JNDIUtils


1 /* ====================================================================
2  * The LateralNZ Software License, Version 1.0
3  *
4  * Copyright (c) 2003 LateralNZ. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. The end-user documentation included with the redistribution,
19  * if any, must include the following acknowledgment:
20  * "This product includes software developed by
21  * LateralNZ (http://www.lateralnz.org/) and other third parties."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. The names "LateralNZ" must not be used to endorse or promote
26  * products derived from this software without prior written
27  * permission. For written permission, please
28  * contact oss@lateralnz.org.
29  *
30  * 5. Products derived from this software may not be called "Panther",
31  * or "Lateral" or "LateralNZ", nor may "PANTHER" or "LATERAL" or
32  * "LATERALNZ" appear in their name, without prior written
33  * permission of LateralNZ.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of LateralNZ. For more
51  * information on Lateral, please see http://www.lateralnz.com/ or
52  * http://www.lateralnz.org
53  *
54  */

55 package org.lateralnz.common.util;
56
57 import java.util.HashMap JavaDoc;
58 import java.util.Hashtable JavaDoc;
59 import java.util.Map JavaDoc;
60 import java.util.MissingResourceException JavaDoc;
61 import java.util.ResourceBundle JavaDoc;
62 import java.util.StringTokenizer JavaDoc;
63
64 import javax.ejb.EJBHome JavaDoc;
65 import javax.ejb.EJBObject JavaDoc;
66 import javax.naming.Context JavaDoc;
67 import javax.naming.InitialContext JavaDoc;
68 import javax.naming.Name JavaDoc;
69 import javax.naming.NameNotFoundException JavaDoc;
70 import javax.naming.NamingException JavaDoc;
71 import javax.naming.spi.ObjectFactory JavaDoc;
72 import javax.naming.Reference JavaDoc;
73 import javax.naming.RefAddr JavaDoc;
74 import javax.naming.StringRefAddr JavaDoc;
75 import javax.rmi.PortableRemoteObject JavaDoc;
76
77 import org.apache.log4j.Logger;
78
79 /**
80  * common utilities for looking up objects (EJBs, Datasources, etc)
81  * in the JNDI tree
82  *
83  * @author J R Briggs
84  */

85 public final class JNDIUtils implements Constants, ObjectFactory JavaDoc {
86   private static final Logger log = Logger.getLogger(JNDIUtils.class.getName());
87   private static final String JavaDoc NAME = "name";
88   private static final String JavaDoc LOCALHOST = "localhost";
89   private static final String JavaDoc DOT_ALIAS = ".alias";
90
91   private static final NamingException JavaDoc NO_DEFAULT_CONTEXT = new NamingException JavaDoc("no default context");
92   
93   private static Context JavaDoc DEFAULT_CONTEXT = null;
94   private static Context JavaDoc EJB_CONTEXT = null;
95   public static Context JavaDoc DAO_CONTEXT = null;
96
97   private static String JavaDoc defaultContextName = null;
98   private static String JavaDoc ejbContextName = null;
99   private static String JavaDoc daoContextName = null;
100   
101   private static String JavaDoc ejbPrefix = null;
102
103   private static ResourceBundle JavaDoc resources;
104   private static Map JavaDoc contexts = new HashMap JavaDoc();
105   private static Map JavaDoc nonSerializableObjects = new HashMap JavaDoc();
106
107
108   static {
109     resources = ResourceUtils.getStaticBundle(JNDIUtils.class);
110     try {
111       defaultContextName = resources.getString("default_context.alias");
112     }
113     catch (Exception JavaDoc e) {}
114     
115     try {
116       ejbContextName = resources.getString("ejb_context.alias");
117     }
118     catch (Exception JavaDoc e) {}
119     
120     try {
121       daoContextName = resources.getString("dao_context.alias");
122     }
123     catch (Exception JavaDoc e) {}
124     
125     if (defaultContextName != null) {
126       try {
127         DEFAULT_CONTEXT = getContext(defaultContextName);
128         log.info("got default context " + DEFAULT_CONTEXT);
129       }
130       catch (Exception JavaDoc e) {
131         log.error("error loading default context");
132         e.printStackTrace();
133       }
134     }
135     
136     if (ejbContextName != null) {
137       try {
138         EJB_CONTEXT = getContext(ejbContextName);
139       }
140       catch (Exception JavaDoc e) {
141         log.error("error loading ejb context");
142         e.printStackTrace();
143       }
144
145     }
146     
147     if (daoContextName != null) {
148       try {
149         DAO_CONTEXT = getContext(daoContextName);
150       }
151       catch (Exception JavaDoc e) {
152         log.error("error loading dao context");
153         e.printStackTrace();
154       }
155     }
156   }
157
158  /**
159   * get a named context for localhost
160   */

161   public static final Context JavaDoc getContext(String JavaDoc contextName) throws NamingException JavaDoc {
162     return getContext(contextName, LOCALHOST);
163   }
164   
165  /**
166   * get a named context for the specified server
167   */

168   public static final Context JavaDoc getContext(String JavaDoc contextName, String JavaDoc server) throws NamingException JavaDoc {
169     Context JavaDoc ctx = null;
170     if (log.isDebugEnabled()) {
171       log.debug("getContext(" + contextName + "," + server + ")");
172     }
173         
174     if (ResourceUtils.hasString(resources, contextName + DOT_ALIAS)) {
175       contextName = resources.getString(contextName + DOT_ALIAS);
176       if (log.isDebugEnabled()) {
177         log.debug("found alias, context now " + contextName);
178       }
179     }
180
181     String JavaDoc name = contextName + UNDERSCORE + server;
182
183     if (contexts.containsKey(name)) {
184       ctx = (Context JavaDoc)contexts.get(name);
185     }
186     else {
187       Hashtable JavaDoc ht = new Hashtable JavaDoc();
188       String JavaDoc ctxparams = null;
189       try {
190         ctxparams = resources.getString(contextName + ".params");
191       }
192       catch (MissingResourceException JavaDoc mre) {
193         // do nothing
194
}
195       
196       if (!StringUtils.isEmpty(ctxparams)) {
197         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(ctxparams, COMMA);
198
199         while (st.hasMoreTokens()) {
200           String JavaDoc param = st.nextToken();
201           try {
202             ht.put(param, resources.getString(contextName + DOT + param));
203           }
204           catch (MissingResourceException JavaDoc mre) {
205             throw new NamingException JavaDoc("param " + param + " does not contain a value");
206           }
207         }
208       }
209      
210       if (ht.size() < 1) {
211         ctx = new InitialContext JavaDoc();
212       }
213       else {
214         String JavaDoc tmp = (String JavaDoc)ht.get(Context.PROVIDER_URL);
215         if (!StringUtils.isEmpty(tmp)) {
216           ht.put(Context.PROVIDER_URL, StringUtils.replace(tmp, "<!--server-->", server));
217         }
218         
219         ctx = new InitialContext JavaDoc(ht);
220       }
221
222       if (log.isDebugEnabled()) {
223         log.debug("context " + name + " = " + ctx + ", env=" + ht.toString());
224       }
225       contexts.put(name, ctx);
226     }
227     return ctx;
228   }
229   
230   public static final Context JavaDoc getDefaultContext() {
231     return DEFAULT_CONTEXT;
232   }
233
234  /**
235   * bind a named object to the JNDI tree using the default context
236   */

237   public static void bind(String JavaDoc objectName, Object JavaDoc obj) throws NamingException JavaDoc {
238     if (DEFAULT_CONTEXT == null) {
239       throw NO_DEFAULT_CONTEXT;
240     }
241     else {
242       bind(DEFAULT_CONTEXT, objectName, obj);
243     }
244   }
245
246  /**
247   * bind a named object to the JNDI tree using the specified context
248   */

249   public static void bind(Context JavaDoc ctx, String JavaDoc objectName, Object JavaDoc obj) throws NamingException JavaDoc {
250     if (log.isDebugEnabled()) {
251       log.debug("binding " + objectName + " into default context " + ctx);
252     }
253     ctx.rebind(objectName, obj);
254   }
255
256  /**
257   * bind a non serializable object
258   */

259   public static final void bindNonSerializable(String JavaDoc name, Object JavaDoc obj, Context JavaDoc ctx) throws NamingException JavaDoc {
260     Reference JavaDoc ref = new Reference JavaDoc(obj.getClass().getName(), JNDIUtils.class.getName(), null);
261     ref.add(new StringRefAddr JavaDoc(NAME, name));
262     ctx.rebind(name, ref);
263     nonSerializableObjects.put(name, obj);
264   }
265
266   public static final Context JavaDoc createSubcontext(Context JavaDoc ctx, String JavaDoc name) throws NamingException JavaDoc {
267     Context JavaDoc context;
268     try {
269       context = (Context JavaDoc)ctx.lookup(name);
270     }
271     catch (NameNotFoundException JavaDoc nnfe) {
272       context = ctx.createSubcontext(name);
273     }
274     return context;
275   }
276   
277  /**
278   * unbind an object from the JNDI tree using the default context
279   */

280   public static void unbind(String JavaDoc objectName) throws NamingException JavaDoc {
281     if (DEFAULT_CONTEXT == null) {
282       throw NO_DEFAULT_CONTEXT;
283     }
284     else {
285       unbind(DEFAULT_CONTEXT, objectName);
286     }
287   }
288
289  /**
290   * unbind an object from the JNDI tree using the specified context
291   */

292   public static void unbind(Context JavaDoc ctx, String JavaDoc objectName) throws NamingException JavaDoc {
293     ctx.unbind(objectName);
294   }
295
296  /**
297   * get an object from the JNDI tree using the default context
298   */

299   public static final Object JavaDoc get(String JavaDoc objectName) throws NamingException JavaDoc {
300     if (DEFAULT_CONTEXT == null) {
301       throw NO_DEFAULT_CONTEXT;
302     }
303     else {
304       return get(DEFAULT_CONTEXT, objectName);
305     }
306   }
307
308  /**
309   * get an object from the JNDI tree using the specified context
310   */

311   public static final Object JavaDoc get(Context JavaDoc ctx, String JavaDoc objectName) throws NamingException JavaDoc {
312     if (StringUtils.isEmpty(objectName)) {
313       throw new NamingException JavaDoc("no object name specified");
314     }
315     
316     return ctx.lookup(objectName);
317   }
318
319  /**
320   * get an EJB home using the default context
321   */

322   public static final EJBHome JavaDoc getEJBHome(String JavaDoc ejbName, Class JavaDoc ejbHomeClass) throws NamingException JavaDoc {
323     if (EJB_CONTEXT == null) {
324       throw NO_DEFAULT_CONTEXT;
325     }
326     else {
327       return getEJBHome(EJB_CONTEXT, ejbName, ejbHomeClass);
328     }
329   }
330
331  /**
332   * get an EJB home using the specified context
333   */

334   public static final EJBHome JavaDoc getEJBHome(Context JavaDoc ctx, String JavaDoc ejbName, Class JavaDoc ejbHomeClass) throws NamingException JavaDoc {
335     Object JavaDoc tmp = get(ctx, ejbName);
336     
337     return (EJBHome JavaDoc)PortableRemoteObject.narrow(tmp, ejbHomeClass);
338   }
339
340  /**
341   * call the remove() method on an EJB -- and ignore any exceptions
342   */

343   public static final void remove(EJBObject JavaDoc obj) {
344     if (obj != null) {
345       try {
346         obj.remove();
347         //if(log.isInfoEnabled()) {
348
//log.info("### ejb removed ###");
349
//}
350
}
351       catch (Exception JavaDoc e) {}
352     }
353   }
354
355
356
357   public Object JavaDoc getObjectInstance(Object JavaDoc obj, Name JavaDoc name, Context JavaDoc ctx, Hashtable JavaDoc environment) throws NamingException JavaDoc {
358     Reference JavaDoc ref = (Reference JavaDoc)obj;
359     Object JavaDoc rtn = nonSerializableObjects.get(getProperty(ref, "name"));
360     System.out.println("JNDI " + getProperty(ref, "name") + ", " + rtn.getClass().getName());
361     return rtn;
362   }
363
364   protected String JavaDoc getProperty(Reference JavaDoc ref, String JavaDoc s) {
365     RefAddr JavaDoc addr = ref.get(s);
366     if (addr == null) {
367       return null;
368     }
369     return (String JavaDoc)addr.getContent();
370   }
371   
372   public static final void main(String JavaDoc[] args) {
373     try {
374       Object JavaDoc obj = JNDIUtils.getEJBHome(args[0], Class.forName(args[1]));
375       System.out.println(">> got object " + obj.getClass().getName());
376       java.lang.reflect.Method JavaDoc method = obj.getClass().getMethod("create", null);
377       Object JavaDoc ejb = method.invoke(obj, null);
378       System.out.println(">> got ejb " + ejb.getClass().getName());
379       java.lang.reflect.Method JavaDoc ejbmethod = ejb.getClass().getMethod(args[2], null);
380       System.out.println(ejbmethod.invoke(ejb, null));
381     }
382     catch (Exception JavaDoc e) {
383       e.printStackTrace();
384     }
385   }
386 }
Popular Tags