KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > easybeans > component > smartclient > spi > SmartContextFactory


1 /**
2  * EasyBeans
3  * Copyright (C) 2006 Bull S.A.S.
4  * Contact: easybeans@objectweb.org
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19  * USA
20  *
21  * --------------------------------------------------------------------------
22  * $Id:$
23  * --------------------------------------------------------------------------
24  */

25
26 package org.objectweb.easybeans.component.smartclient.spi;
27
28 import java.util.Hashtable JavaDoc;
29 import java.util.StringTokenizer JavaDoc;
30 import java.util.logging.Level JavaDoc;
31 import java.util.logging.Logger JavaDoc;
32
33 import javax.naming.Context JavaDoc;
34 import javax.naming.InitialContext JavaDoc;
35 import javax.naming.NamingException JavaDoc;
36 import javax.naming.spi.InitialContextFactory JavaDoc;
37
38 import org.objectweb.easybeans.component.smartclient.client.AskingClassLoader;
39
40 /**
41  * Initial Context factory used on the client side.<br>
42  * It will ask the server for every class/resource not found in local.
43  * @author Florent Benoit
44  *
45  */

46 public class SmartContextFactory implements InitialContextFactory JavaDoc {
47
48     /**
49      * Use the JDK logger (to avoid any dependency).
50      */

51     private static Logger JavaDoc logger = Logger.getLogger(SmartContextFactory.class.getName());
52
53     /**
54      * Default PROVIDER_URL.
55      */

56     private static final String JavaDoc DEFAULT_URL = "smart://localhost:2503";
57
58     /**
59      * Carol factory.
60      */

61     private static final String JavaDoc CAROL_FACTORY = "org.objectweb.carol.jndi.spi.MultiOrbInitialContextFactory";
62
63     /**
64      * EasyBeans delegating factory. (by default it will be ourself)
65      */

66     public static final String JavaDoc EASYBEANS_DELEGATING_FACTORY = "easybeans.smart.delegate.factory";
67
68     /**
69      * EasyBeans factory.
70      */

71     public static final String JavaDoc EASYBEANS_FACTORY = "easybeans.rpc.rmi.factory";
72
73     /**
74      * Instance of classloader that is used to load class.<br>
75      * This is this classloader which will download class.
76      */

77     private static AskingClassLoader classLoader = null;
78
79     /**
80      * Provider URL to use for connecting.
81      */

82     private static String JavaDoc providerURL = null;
83
84     /**
85      * Default constructor.<br>
86      * Sets the Portable RemoteObject Wrapper class too.
87      */

88     public SmartContextFactory() {
89         // sets our class (or the delegating factory)
90
System.setProperty(EASYBEANS_FACTORY, System.getProperty(EASYBEANS_DELEGATING_FACTORY, this.getClass().getName()));
91         System.setProperty("javax.rmi.CORBA.PortableRemoteObjectClass", ProDelegate.class.getName());
92     }
93
94     /**
95       * Creates an Initial Context for beginning name resolution.
96       * Special requirements of this context are supplied
97       * @param environment the given environment.
98       * @return the context.
99       * @throws NamingException if no context can be built.
100     */

101     @SuppressWarnings JavaDoc("unchecked")
102     public Context JavaDoc getInitialContext(final Hashtable JavaDoc environment)
103             throws NamingException JavaDoc {
104
105         if (classLoader == null) {
106             try {
107                 // Gets the provider url
108
String JavaDoc currentProviderURL = (String JavaDoc) environment.get(Context.PROVIDER_URL);
109                 if (currentProviderURL == null) {
110                     logger.log(Level.WARNING, "No PROVIDER_URL setting found, use the default URL '" + DEFAULT_URL + "'.");
111                     currentProviderURL = DEFAULT_URL;
112                 }
113
114                 logger.log(Level.INFO, "Initializing Smart Factory with remote URL '" + currentProviderURL + "'.");
115
116                 // extract host
117
String JavaDoc host = getHostOfUrl(currentProviderURL);
118
119                 // extract port
120
int portNumber = getPortOfUrl(currentProviderURL);
121
122                 // build the classloader to use.
123
classLoader = new AskingClassLoader(host, portNumber);
124
125
126                 providerURL = classLoader.getProviderURL();
127                 logger.log(Level.INFO, "Got remote PROVIDER_URL '" + providerURL + "'.");
128
129                 // Set the classloader for the ProDelegate class
130
ProDelegate.setClassLoader(classLoader);
131
132             } catch (Exception JavaDoc e) {
133                 NamingException JavaDoc ne = new NamingException JavaDoc("Cannot get a remote ClassLoader");
134                 ne.initCause(e);
135                 throw ne;
136             }
137         }
138
139         ClassLoader JavaDoc old = Thread.currentThread().getContextClassLoader();
140         Thread.currentThread().setContextClassLoader(classLoader);
141         try {
142             // set the right factory
143
environment.put(Context.INITIAL_CONTEXT_FACTORY, CAROL_FACTORY);
144             environment.put(Context.PROVIDER_URL, providerURL);
145
146             // return wrapped context
147
return new SmartContext(new InitialContext JavaDoc(environment), classLoader);
148         } finally {
149             Thread.currentThread().setContextClassLoader(old);
150         }
151
152     }
153
154
155     /**
156      * Parses the given url, and returns the port number. 0 is given in error
157      * case)
158      * @param url given url on which extract port number
159      * @return port number of the url
160      * @throws NamingException if URL is invalid
161      */

162     public int getPortOfUrl(final String JavaDoc url) throws NamingException JavaDoc {
163         int portNumber = 0;
164         try {
165             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(url, ":");
166             st.nextToken();
167             st.nextToken();
168             if (st.hasMoreTokens()) {
169                 StringTokenizer JavaDoc lastst = new StringTokenizer JavaDoc(st.nextToken(), "/");
170                 String JavaDoc pts = lastst.nextToken().trim();
171                 int i = pts.indexOf(',');
172                 if (i > 0) {
173                     pts = pts.substring(0, i);
174                 }
175                 portNumber = new Integer JavaDoc(pts).intValue();
176             }
177             return portNumber;
178         } catch (Exception JavaDoc e) {
179             // don't rethrow original exception. only URL name is important
180
throw new NamingException JavaDoc("Invalid URL '" + url + "'. It should be on the format <protocol>://<hostname>:<port>");
181         }
182     }
183
184     /**
185      * Parses the given url, and returns the hostname.
186      * @param url given url on which extract hostname
187      * @return hostname of the url
188      * @throws NamingException if URL is invalid
189      */

190     private String JavaDoc getHostOfUrl(final String JavaDoc url) throws NamingException JavaDoc {
191         String JavaDoc host = null;
192         // this would be simpler with a regexp :)
193
try {
194             // url is of the form protocol://<hostname>:<port>
195
String JavaDoc[] tmpSplitStr = url.split(":");
196
197             // array should be of length = 3
198
// get 2nd element (should be //<hostname>)
199
String JavaDoc tmpHost = tmpSplitStr[1];
200
201             // remove //
202
String JavaDoc[] tmpSplitHost = tmpHost.split("/");
203
204             // Get last element of the array to get hostname
205
host = tmpSplitHost[tmpSplitHost.length - 1];
206         } catch (Exception JavaDoc e) {
207             // don't rethrow original exception. only URL name is important
208
throw new NamingException JavaDoc("Invalid URL '" + url + "'. It should be on the format <protocol>://<hostname>:<port>");
209         }
210         return host;
211     }
212 }
213
Popular Tags