KickJava   Java API By Example, From Geeks To Geeks.

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


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.ejb.protocol.ProtocolContainer;
33 import com.caucho.ejb.protocol.Skeleton;
34 import com.caucho.log.Log;
35 import com.caucho.server.connection.AbstractHttpRequest;
36 import com.caucho.server.connection.AbstractHttpResponse;
37 import com.caucho.server.util.CauchoSystem;
38 import com.caucho.server.webapp.Application;
39 import com.caucho.server.webapp.WebApp;
40 import com.caucho.util.CharBuffer;
41 import com.caucho.util.L10N;
42 import com.caucho.vfs.Path;
43
44 import javax.servlet.GenericServlet JavaDoc;
45 import javax.servlet.ServletException JavaDoc;
46 import javax.servlet.ServletRequest JavaDoc;
47 import javax.servlet.ServletResponse JavaDoc;
48 import java.io.IOException JavaDoc;
49 import java.io.InputStream JavaDoc;
50 import java.io.PrintWriter JavaDoc;
51 import java.util.Hashtable JavaDoc;
52 import java.util.logging.Level JavaDoc;
53 import java.util.logging.Logger JavaDoc;
54
55 /**
56  * Servlet for serving EJBs from the Resin web server.
57  */

58 public class EJBServlet extends GenericServlet JavaDoc {
59   private static final L10N L = new L10N(EJBServlet.class);
60   private final Logger JavaDoc log = Log.open(EJBServlet.class);
61
62   private String JavaDoc _urlPrefix;
63
64   private String JavaDoc _ejbServerJndiName = "java:comp/env/cmp";
65   private String JavaDoc _containerId;
66   private String JavaDoc _servletId;
67   private String JavaDoc _localId;
68
69   private boolean _isDebug;
70   
71   // URL to bean map
72
private Hashtable JavaDoc<CharSequence JavaDoc,Skeleton> _beanMap
73     = new Hashtable JavaDoc<CharSequence JavaDoc,Skeleton>();
74
75   private EjbServerManager _ejbManager;
76   private ProtocolContainer _protocolContainer;
77
78   private ServletException JavaDoc _exception;
79
80   private Path _workPath;
81
82   protected String JavaDoc getDefaultProtocolContainer()
83   {
84     return "com.caucho.hessian.HessianProtocol";
85   }
86
87   /**
88    * Set true for a debug.
89    */

90   public void setDebug(boolean debug)
91   {
92     _isDebug = debug;
93   }
94
95   public void setURLPrefix(String JavaDoc prefix)
96   {
97     _urlPrefix = prefix;
98   }
99
100   /**
101    * Initialize the servlet
102    */

103   public void init()
104     throws ServletException JavaDoc
105   {
106     _ejbManager = EJBServer.getLocalManager();
107
108     if (_ejbManager == null) {
109       throw new ServletException JavaDoc(L.l("No <ejb-server> detected. '{0}' requires a configured <ejb-server>",
110                      getClass().getName()));
111     }
112
113     _workPath = CauchoSystem.getWorkPath();
114
115     _urlPrefix = getInitParameter("url-prefix");
116     
117     _localId = getInitParameter("local-prefix");
118
119     String JavaDoc protocol = getInitParameter("protocol");
120     if (protocol == null)
121       protocol = getInitParameter("protocol-container");
122     if (protocol == null)
123       protocol = getInitParameter("protocol-factory");
124     if (protocol == null)
125       protocol = getDefaultProtocolContainer();
126
127     try {
128       Class JavaDoc cl = CauchoSystem.loadClass(protocol);
129
130       _protocolContainer = (ProtocolContainer) cl.newInstance();
131     } catch (Exception JavaDoc e) {
132       throw new ServletException JavaDoc(e);
133     }
134
135     Application app = (Application) getServletContext();
136
137     // need to initialize in the case of message driven beans.
138
//if (containerId == null)
139
// containerId = app.getURL();
140

141     initEjb();
142     
143     if (_urlPrefix != null)
144       initProtocol();
145   }
146
147   /**
148    * Execute a request. The path-info of the request selects the bean.
149    * Once the bean's selected, it will be applied.
150    */

151   public void service(ServletRequest JavaDoc request, ServletResponse JavaDoc response)
152     throws IOException JavaDoc, ServletException JavaDoc
153   {
154     AbstractHttpRequest req = (AbstractHttpRequest) request;
155     AbstractHttpResponse res = (AbstractHttpResponse) response;
156
157     if (_urlPrefix == null) {
158       synchronized (this) {
159         if (_urlPrefix == null)
160           serverInit(req);
161       }
162     }
163
164     if (! req.getMethod().equals("POST")) {
165       String JavaDoc protocol = _protocolContainer.getName();
166       res.setStatus(500, protocol + " Protocol Error");
167       PrintWriter JavaDoc out = res.getWriter();
168       out.println(protocol + " expects a POST containing an RPC call.");
169       return;
170     }
171
172     try {
173       String JavaDoc pathInfo = req.getPathInfo();
174       String JavaDoc queryString = req.getQueryString();
175       
176       CharBuffer cb = new CharBuffer();
177       cb.append(pathInfo);
178       cb.append('?');
179       cb.append(queryString);
180       
181       InputStream JavaDoc is = req.getInputStream();
182
183       if (_isDebug) {
184       }
185
186       Skeleton skeleton = (Skeleton) _beanMap.get(cb);
187
188       if (skeleton == null) {
189         // If this was a load just to force the initialization, then return
190
if (req.getParameter("ejb-load") != null)
191           return;
192       
193         if (_exception != null)
194           throw _exception;
195
196     try {
197       if (pathInfo == null)
198         pathInfo = "";
199       
200       skeleton = _protocolContainer.getSkeleton(pathInfo, queryString);
201     } catch (Exception JavaDoc e) {
202       log.log(Level.WARNING, e.toString(), e);
203       
204       skeleton = _protocolContainer.getExceptionSkeleton();
205
206       if (skeleton != null) {
207         skeleton._service(req.getInputStream(), res.getOutputStream(), e);
208
209         return;
210       }
211       else
212         throw e;
213     }
214
215         if (skeleton == null)
216           throw new ServletException JavaDoc(L.l("Can't load skeleton for '{0}?{1}'",
217                                          pathInfo, queryString));
218
219         if (skeleton != null) {
220       skeleton.setDebug(_isDebug);
221           _beanMap.put(cb, skeleton);
222     }
223       }
224
225       skeleton._service(req.getInputStream(), res.getOutputStream());
226     } catch (ServletException JavaDoc e) {
227       throw e;
228     } catch (Throwable JavaDoc e) {
229       log.log(Level.WARNING, e.toString(), e);
230       
231       throw new ServletException JavaDoc(e);
232     }
233   }
234
235   /**
236    * Returns the server container responsible for handling the request
237    *
238    * @param pathInfo the path info of the request
239    *
240    * @return the server bean responsible for handling the request
241    */

242   Skeleton getSkeleton(String JavaDoc pathInfo, String JavaDoc queryString)
243     throws Exception JavaDoc
244   {
245     CharBuffer cb = CharBuffer.allocate();
246     cb.append(pathInfo);
247     cb.append('?');
248     cb.append(queryString);
249     
250     Skeleton skeleton = (Skeleton) _beanMap.get(cb);
251     
252     if (skeleton != null) {
253       cb.free();
254       return skeleton;
255     }
256
257     skeleton = _protocolContainer.getSkeleton(pathInfo, queryString);
258     
259     _beanMap.put(cb, skeleton);
260
261     return skeleton;
262   }
263
264   /**
265    * Initialize the server.
266    */

267   private void serverInit(AbstractHttpRequest req)
268     throws ServletException JavaDoc
269   {
270     if (_urlPrefix != null)
271       return;
272     
273     WebApp app = (WebApp) getServletContext();
274
275     // calculate the URL prefix
276
_servletId = req.getServletPath();
277
278     CharBuffer cb = CharBuffer.allocate();
279
280     if (! "default".equals(app.getAdmin().getHost().getName())
281     && ! "".equals(app.getAdmin().getHost().getName())) {
282       String JavaDoc hostName = app.getAdmin().getHost().getURL();
283
284       cb.append(hostName);
285       cb.append(app.getContextPath());
286       cb.append(_servletId);
287     }
288     else {
289       cb.append(req.getScheme());
290       cb.append("://");
291       cb.append(req.getServerName());
292       cb.append(":");
293       cb.append(req.getServerPort());
294       cb.append(app.getContextPath());
295       cb.append(_servletId);
296     }
297   
298     _urlPrefix = cb.close();
299
300     initProtocol();
301   }
302
303   private void initProtocol()
304   {
305     normalizeId();
306
307     _protocolContainer.setProtocolManager(_ejbManager.getProtocolManager());
308     _protocolContainer.setURLPrefix(_urlPrefix);
309     _protocolContainer.setWorkPath(_workPath);
310
311     _ejbManager.getProtocolManager().addProtocolContainer(_protocolContainer);
312   }
313
314   private void normalizeId()
315   {
316     if (_urlPrefix == null)
317       return;
318
319     Application application = (Application) getServletContext();
320     String JavaDoc hostName = "localhost"; // application.getHost();
321
String JavaDoc contextPath = application.getContextPath();
322
323     if (_urlPrefix.startsWith("/")) {
324       _servletId = _urlPrefix;
325       _urlPrefix = application.getURL() + _urlPrefix;
326     }
327     else if (_urlPrefix.startsWith("http://")) {
328       int p = _urlPrefix.indexOf('/', "http://".length());
329
330       String JavaDoc uri = _urlPrefix;
331       if (p > 0)
332         uri = _urlPrefix.substring(p);
333       else
334         uri = "";
335
336       if (uri.startsWith(contextPath))
337         _servletId = uri.substring(contextPath.length());
338       else if (_servletId == null)
339         _servletId = uri;
340     }
341     else if (_urlPrefix.startsWith("https://")) {
342       int p = _urlPrefix.indexOf('/', "https://".length());
343
344       String JavaDoc uri = _urlPrefix;
345       if (p > 0)
346         uri = _urlPrefix.substring(p);
347       else
348         uri = "";
349
350       if (uri.startsWith(contextPath))
351         _servletId = uri.substring(contextPath.length());
352       else if (_servletId == null)
353         _servletId = uri;
354     }
355     else if (_urlPrefix.startsWith("cron:")) {
356       _urlPrefix = application.getURL() + _servletId;
357     }
358     else
359       _servletId = _urlPrefix;
360
361     if (_servletId.equals(""))
362       _servletId = "/";
363   }
364
365   private void initEjb()
366     throws ServletException JavaDoc
367   {
368     if (_ejbManager != null)
369       return;
370
371     /*
372     String cmpJndi = "java:comp/env/cmp";
373     try {
374     Object cmp = new InitialContext().lookup(cmpJndi);
375
376       if (cmp instanceof LocalContext) {
377         LocalContext cxt = (LocalContext) cmp;
378
379         LocalModel model = (LocalModel) cxt.getModel();
380         _ejbManager = model.getServerContainer();
381       }
382     } catch (Exception e) {
383     }
384
385     if (_serverContainer == null)
386       throw new ServletException(L.l("Can't find servers container at `{0}'",
387                                      cmpJndi));
388     */

389
390     if (_urlPrefix != null) {
391       normalizeId();
392
393       _protocolContainer.setServerManager(_ejbManager);
394       _protocolContainer.setURLPrefix(_urlPrefix);
395       _protocolContainer.setWorkPath(_workPath);
396     
397       _ejbManager.getProtocolManager().addProtocolContainer(_protocolContainer);
398     }
399   }
400 }
401
Popular Tags