KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > speedo > j2eedo > web > MainServlet


1 /**
2  * Speedo: an implementation of JDO compliant personality on top of JORM generic
3  * I/O sub-system.
4  * Copyright (C) 2001-2004 France Telecom R&D
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 of the License, or (at your option) 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 USA
19  *
20  * Release: 1.0
21  *
22  *@author fmillevi@yahoo.com
23  *
24  */

25 package org.objectweb.speedo.j2eedo.web;
26 import java.io.IOException JavaDoc;
27 import java.rmi.RemoteException JavaDoc;
28
29 import javax.ejb.CreateException JavaDoc;
30 import javax.jdo.JDOException;
31 import javax.jdo.PersistenceManager;
32 import javax.jdo.PersistenceManagerFactory;
33 import javax.naming.InitialContext JavaDoc;
34 import javax.naming.NamingException JavaDoc;
35
36 import javax.servlet.ServletException JavaDoc;
37 import javax.servlet.http.HttpServlet JavaDoc;
38 import javax.servlet.http.HttpServletRequest JavaDoc;
39 import javax.servlet.http.HttpServletResponse JavaDoc;
40
41 import org.objectweb.speedo.j2eedo.common.PMHolder;
42 import org.objectweb.speedo.j2eedo.ejb.StoreServicesLocal;
43 import org.objectweb.speedo.j2eedo.ejb.StoreServicesLocalHome;
44 import org.objectweb.speedo.j2eedo.ejb.StoreServicesRemote;
45 import org.objectweb.speedo.j2eedo.ejb.StoreServicesRemoteHome;
46 import org.objectweb.util.monolog.Monolog;
47 import org.objectweb.util.monolog.api.BasicLevel;
48 import org.objectweb.util.monolog.api.Logger;
49
50 abstract class MainServlet extends HttpServlet JavaDoc {
51     // define the class name parameter
52
/**
53      * The constant <code>WITHOUT_TRANSACTION_PARAMETER</code> is used
54      * to retrive the HTTP request parameter <b>"withoutTrans"</b> used by the servlet
55      * to know if a transaction must be start at the servlet level.
56      */

57     public final static String JavaDoc WITH_TRANSACTION_PARAMETER = "withTrans";
58     /**
59      * The constant <code>TYPE_CONTAINER_PARAMETER</code> is used
60      * to retrive the HTTP request parameter <b>"container"</b> used by the servlet
61      * to know if the action must be done through a Session Bean Container.
62      */

63     public final static String JavaDoc TYPE_CONTAINER_PARAMETER = "container";
64
65     public final static String JavaDoc LOCAL_SESSION_BEAN_PARAMETER = "localsession";
66     
67     /**
68      * The constant <code>WITH_GETPM_PARAMETER</code> is used
69      * to retrive the HTTP request parameter <b>"withGetPM"</b> used by the servlet
70      * to know if the persistence manager must be get by the servelt.
71      */

72     public final static String JavaDoc WITH_GETPM_PARAMETER = "withGetPM";
73
74     private final static String JavaDoc PMF_JNDI_NAME = "speedo";
75
76     protected static Logger logger = null;
77
78     protected PersistenceManagerFactory persistenceManagerFactory = null;
79     
80     protected StoreServicesLocalHome lstoreServicesLH;
81     protected StoreServicesRemoteHome lstoreServicesRH;
82     
83     /**
84      * This servlet executes current request:<ul>
85      * <li>Gets the Persistence manager when required (false by default),</li>
86      * <li>Starts a local transaction when requested (false by default),</li>
87      * <li>Calls the dedicated action directly or through a Session Bean Container
88      * (direct call by default),</li>
89      * <li>Close the PM when initialized at the servlet level.</li>
90      * </ul>
91      * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest,
92      * javax.servlet.http.HttpServletResponse)
93      */

94     public void service(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc resp)
95         throws ServletException JavaDoc, IOException JavaDoc {
96         boolean withTransaction = getParameterValue(
97                 req, MainServlet.WITH_TRANSACTION_PARAMETER, false);
98         boolean withGetPM = getParameterValue(
99                 req, MainServlet.WITH_GETPM_PARAMETER, withTransaction);
100         boolean useSessionBean = getParameterValue(
101                 req, MainServlet.TYPE_CONTAINER_PARAMETER, false);
102         boolean localSessionBean = getParameterValue(
103                 req, MainServlet.LOCAL_SESSION_BEAN_PARAMETER, false);
104         if (logger.isLoggable(BasicLevel.DEBUG)) {
105             logger.log(BasicLevel.DEBUG, "Invoke Servlet: "
106                     +" \n\t-withGetPM=" + withGetPM
107                     + "\n\t-withTransaction=" + withTransaction
108                     + "\n\t-useSessionBean=" + useSessionBean
109                     + "\n\t-localSessionBean=" + localSessionBean
110                 );
111         }
112         // check sequence of parameters
113
if (useSessionBean && withTransaction) {
114             withTransaction = false;
115             logger.log(BasicLevel.WARN,
116                 "Use local transaction is forbiden when using an ejb session");
117         }
118         if (withTransaction && !withGetPM) {
119             // to begin and close an transaction the pm is required
120
withGetPM = true;
121             logger.log(BasicLevel.WARN,
122                 "Use of the persistence manager is required when using transaction");
123         }
124         PMHolder pmh = new PMHolder(persistenceManagerFactory);
125         PersistenceManager pm = null;
126         javax.jdo.Transaction utx = null;
127         try {
128             if ((!useSessionBean || localSessionBean) && withGetPM) {
129                 logger.log(BasicLevel.DEBUG, "GetPM");
130                 pm = pmh.getPersistenceManager();
131             }
132             if ((!useSessionBean || localSessionBean) && withTransaction) {
133                 utx = pm.currentTransaction();
134                 utx.begin();
135                 logger.log(BasicLevel.DEBUG, "Begin local Transaction");
136             }
137             if (useSessionBean) {
138                 //The action will be done by the Session bean
139
if (localSessionBean) {
140                     //Invoke the session bean through the local interface
141
logger.log(BasicLevel.DEBUG, "Use local session bean");
142                     StoreServicesLocal lstoreServices = null;
143                     try {
144                         lstoreServices = lstoreServicesLH.create();
145                     } catch (CreateException JavaDoc e) {
146                         logger.log(BasicLevel.ERROR, "Error during the creation of Local Session", e);
147                         throw new ServletException JavaDoc(e);
148                     }
149                     try {
150                         executeSessionBean(req, resp, lstoreServices, pmh);
151                     } finally {
152                         //release the session bean from the pool
153
lstoreServices.remove();
154                     }
155                 } else {
156                     //Invoke the session bean through the Remote interface
157
logger.log(BasicLevel.DEBUG, "Use remote session bean");
158                     StoreServicesRemote lstoreServices = null;
159                     try {
160                         lstoreServices = lstoreServicesRH.create();
161                     } catch (CreateException JavaDoc e) {
162                         logger.log(BasicLevel.ERROR, "Error during the creation of Local Session", e);
163                         throw new ServletException JavaDoc(e);
164                     }
165                     try {
166                         executeSessionBean(req, resp, lstoreServices);
167                     } finally {
168                         //release the session bean from the pool
169
lstoreServices.remove();
170                     }
171                 }
172             } else {
173                 logger.log(BasicLevel.DEBUG, "Use direct call");
174                 executeDirectCall(req, resp, pmh);
175             }
176         } catch (Exception JavaDoc e) {
177             if (utx != null && utx.isActive()) {
178                 logger.log(BasicLevel.DEBUG, "Rollback the local Transaction due to an error: ", e);
179                 utx.rollback();
180             } else {
181                 logger.log(BasicLevel.ERROR, "An error has occured: ", e);
182             }
183             throw new ServletException JavaDoc(e);
184         } finally {
185             if (utx != null && utx.isActive()) {
186                 logger.log(BasicLevel.DEBUG, "Commit the local Transaction");
187                 utx.commit();
188             }
189             if (pm != null && !pm.isClosed()) {
190                 logger.log(BasicLevel.DEBUG, "Close local PM");
191                 pmh.closePersistenceManager();
192             }
193         }
194     }
195         
196     public void init() throws ServletException JavaDoc {
197         super.init();
198         
199         // get the logger
200
logger = Monolog.initialize().getLogger(getClass().getName());
201
202         //get the PersistenceManagerFactory
203
persistenceManagerFactory = (PersistenceManagerFactory)
204             getObjectFromContext(null, PMF_JNDI_NAME);
205         
206         try {
207             getStoreServicesRemoteHome();
208         } catch (ServletException JavaDoc e) {
209             logger.log(BasicLevel.WARN, "No StoreServicesRemoteHome found", e);
210         }
211         try {
212             getStoreServicesLocalHome();
213         } catch (ServletException JavaDoc e) {
214             logger.log(BasicLevel.WARN, "No StoreServicesLocalHome found", e);
215         }
216     }
217     
218     /**
219      * get the StoreServicesLocalHome.
220      */

221     private StoreServicesLocalHome getStoreServicesLocalHome() throws ServletException JavaDoc {
222         if (lstoreServicesLH == null) {
223             lstoreServicesLH = (StoreServicesLocalHome)
224                 getObjectFromContext(null, "java:comp/env/ejb/StoreServicesHomeLocal");
225         }
226         return lstoreServicesLH;
227     }
228     
229     /**
230      * get the StoreServicesRemoteHome.
231      */

232     private StoreServicesRemoteHome getStoreServicesRemoteHome() throws ServletException JavaDoc {
233         if (lstoreServicesRH == null) {
234             lstoreServicesRH = (StoreServicesRemoteHome)
235                 getObjectFromContext(null, "ejb/storeService");
236         }
237         return lstoreServicesRH;
238     }
239     
240     /**
241      * Get an object from JNDI
242      * @param ictx is the InitialContext to use. If this parameter is null
243      * a new context is created and closed
244      * @param name is the JNDI name of the searched object
245      * @return the object (never null)
246      * @throws ServletException if the object cannot be found.
247      */

248     private static Object JavaDoc getObjectFromContext(InitialContext JavaDoc ictx, String JavaDoc name) throws ServletException JavaDoc {
249         boolean hasToCloseContext = false;
250         if (ictx == null) {
251             try {
252                 ictx = new InitialContext JavaDoc();
253                 hasToCloseContext = true;
254             } catch (NamingException JavaDoc e) {
255                 logger.log(BasicLevel.ERROR,
256                         "Impossible to get the InitialContext: ", e);
257                 throw new ServletException JavaDoc(
258                         "Impossible to get the InitialContext: " + e.getMessage());
259             }
260         }
261         try {
262             Object JavaDoc o = ictx.lookup(name);
263             if (o == null) {
264                 throw new ServletException JavaDoc("'" + name + "' has not been found from JNDI");
265             }
266             return o;
267         } catch (ServletException JavaDoc e) {
268             throw e;
269         } catch (Exception JavaDoc e) {
270             logger.log(BasicLevel.ERROR, "Impossible to find " + name +": ", e);
271             return null;
272         } finally {
273             if (hasToCloseContext && ictx != null) {
274                 try {
275                     ictx.close();
276                 } catch (NamingException JavaDoc ne) {
277                 }
278             }
279         }
280     }
281     
282     /**
283      * Get the value of a prameter from a HttpServletRequest instance
284      * @param req is the HttpServletRequest
285      * @param paramName is the name of the parameter
286      * @param defaultValue is the default value to return if the parameter
287      * is not defined in the HttpServletRequest
288      */

289     private static boolean getParameterValue(HttpServletRequest JavaDoc req,
290             String JavaDoc paramName,
291             boolean defaultValue) {
292         try {
293             String JavaDoc val = req.getParameter(paramName);
294             return val != null && Boolean.valueOf(val).booleanValue();
295         } catch (Exception JavaDoc e) {
296             return defaultValue;
297         }
298     }
299         
300     /**
301      * Empty threatment call for a ejb session
302      *
303      * @param lstoreServices
304      * @param persistenceManagerHolder
305      * @param out
306      * @throws JDOException
307      * @throws RemoteException
308      * @throws Exception
309      * @throws IOException
310      */

311     protected abstract void executeSessionBean(
312         HttpServletRequest JavaDoc req,
313         HttpServletResponse JavaDoc resp,
314         StoreServicesRemote storeServices)
315         throws JDOException, RemoteException JavaDoc, Exception JavaDoc, IOException JavaDoc;
316
317     protected abstract void executeSessionBean(
318             HttpServletRequest JavaDoc req,
319             HttpServletResponse JavaDoc resp,
320             StoreServicesLocal storeServices,
321             PMHolder persistenceManagerHolder)
322             throws JDOException, RemoteException JavaDoc, Exception JavaDoc, IOException JavaDoc;
323     
324     /**
325      * Empty threatment call for a jdo direct call
326      *
327      * @param persistenceManagerHolder
328      * @param out
329      * @throws JDOException
330      * @throws Exception
331      * @throws IOException
332      */

333     protected abstract void executeDirectCall(
334         HttpServletRequest JavaDoc req,
335         HttpServletResponse JavaDoc resp,
336         PMHolder persistenceManagerHolder)
337         throws JDOException, Exception JavaDoc, IOException JavaDoc ;
338 }
339
Popular Tags