KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > turbine > services > rundata > TurbineRunDataService


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

56
57 import java.lang.reflect.Method JavaDoc;
58 import java.util.HashMap JavaDoc;
59 import java.util.Iterator JavaDoc;
60
61 import javax.servlet.ServletConfig JavaDoc;
62 import javax.servlet.http.HttpServletRequest JavaDoc;
63 import javax.servlet.http.HttpServletResponse JavaDoc;
64
65 import org.apache.fulcrum.BaseService;
66 import org.apache.fulcrum.InitializationException;
67 import org.apache.fulcrum.ServiceException;
68 import org.apache.fulcrum.TurbineServices;
69 import org.apache.fulcrum.parser.CookieParser;
70 import org.apache.fulcrum.parser.ParameterParser;
71 import org.apache.fulcrum.parser.DefaultParameterParser;
72 import org.apache.fulcrum.pool.PoolException;
73 import org.apache.fulcrum.pool.PoolService;
74 import org.apache.fulcrum.upload.UploadService;
75 import org.apache.turbine.RunData;
76 import org.apache.turbine.services.yaaficomponent.YaafiComponentService;
77
78 /**
79  * The RunData Service provides the implementations for RunData and
80  * related interfaces required by request processing. It supports
81  * different configurations of implementations, which can be selected
82  * by specifying a configuration key. It may use pooling, in which case
83  * the implementations should implement the Recyclable interface.
84  *
85  * @author <a HREF="mailto:ilkka.priha@simsoft.fi">Ilkka Priha</a>
86  * @version $Id: TurbineRunDataService.java,v 1.10 2004/11/12 10:26:23 epugh Exp $
87  */

88 public class TurbineRunDataService
89     extends BaseService
90     implements RunDataService
91 {
92     /**
93      * The property for the implemention of RunData.
94      */

95     public static final String JavaDoc RUN_DATA = "run.data";
96
97     /**
98      * The property for the implemention of ParameterParser.
99      */

100     public static final String JavaDoc PARAMETER_PARSER = "parameter.parser";
101
102     /**
103      * The property for the implemention of CookieParser.
104      */

105     public static final String JavaDoc COOKIE_PARSER = "cookie.parser";
106
107     /**
108      * The default implementations.
109      */

110     private static final String JavaDoc DEFAULT_RUN_DATA =
111         "org.apache.fulcrum.rundata.DefaultTurbineRunData";
112     private static final String JavaDoc DEFAULT_PARAMETER_PARSER =
113         "org.apache.fulcrum.parser.DefaultParameterParser";
114     private static final String JavaDoc DEFAULT_COOKIE_PARSER =
115         "org.apache.fulcrum.parser.DefaultCookieParser";
116
117     /**
118      * The map of configurations.
119      */

120     private HashMap JavaDoc configurations = new HashMap JavaDoc();
121
122     /**
123      * The getContextPath method from servet API >2.0.
124      */

125     private Method JavaDoc getContextPath;
126
127     /**
128      * Constructs a RunData Service.
129      */

130     public TurbineRunDataService()
131     {
132         // Allow Turbine to work with both 2.2 (and 2.1) and 2.0 Servlet API.
133
try
134         {
135             getContextPath =
136                 HttpServletRequest JavaDoc.class.getDeclaredMethod("getContextPath",null);
137         }
138         catch (NoSuchMethodException JavaDoc x)
139         {
140             // Ignore a NoSuchMethodException because
141
// it means we are using Servlet API 2.0.
142
}
143     }
144
145     /**
146      * Initializes the service.
147      *
148      * @throws InitializationException if initialization fails.
149      */

150     public void init()
151         throws InitializationException
152     {
153         // Create a default configuration.
154
String JavaDoc[] def = new String JavaDoc[]
155         {
156             DEFAULT_RUN_DATA,
157             DEFAULT_PARAMETER_PARSER,
158             DEFAULT_COOKIE_PARSER
159         };
160         configurations.put(DEFAULT_CONFIG,def.clone());
161
162         if (getConfiguration() != null)
163         {
164             String JavaDoc key,value;
165             String JavaDoc[] config;
166             String JavaDoc[] plist = new String JavaDoc[]
167             {
168                 RUN_DATA,
169                 PARAMETER_PARSER,
170                 COOKIE_PARSER
171             };
172             for (Iterator JavaDoc i = getConfiguration().getKeys(); i.hasNext();)
173             {
174                 key = (String JavaDoc) i.next();
175                 value = getConfiguration().getString(key);
176                 for (int j = 0; j < plist.length; j++)
177                 {
178                     if (key.endsWith(plist[j]) &&
179                         (key.length() > (plist[j].length() + 1)))
180                     {
181                         key = key.substring(0,key.length() - plist[j].length() - 1);
182                         config = (String JavaDoc[]) configurations.get(key);
183                         if (config == null)
184                         {
185                             config = (String JavaDoc[]) def.clone();
186                             configurations.put(key,config);
187                         }
188                         config[j] = value;
189                         break;
190                     }
191                 }
192             }
193         }
194         setInit(true);
195     }
196
197     /**
198      * Gets a default RunData object.
199      *
200      * @param req a servlet request.
201      * @param res a servlet response.
202      * @param config a servlet config.
203      * @return a new or recycled RunData object.
204      * @throws ServiceException if the operation fails.
205      */

206     public RunData getRunData(HttpServletRequest JavaDoc req,
207                               HttpServletResponse JavaDoc res,
208                               ServletConfig JavaDoc config)
209         throws ServiceException
210     {
211         return getRunData(DEFAULT_CONFIG,req,res,config);
212     }
213
214     /**
215      * Gets a RunData instance from a specific configuration.
216      *
217      * @param key a configuration key.
218      * @param req a servlet request.
219      * @param res a servlet response.
220      * @param config a servlet config.
221      * @return a new or recycled RunData object.
222      * @throws ServiceException if the operation fails.
223      * @throws IllegalArgumentException if any of the parameters are null.
224      */

225     public RunData getRunData(String JavaDoc key,
226                               HttpServletRequest JavaDoc req,
227                               HttpServletResponse JavaDoc res,
228                               ServletConfig JavaDoc config)
229         throws ServiceException,
230                IllegalArgumentException JavaDoc
231     {
232         // The RunData object caches all the information that is needed for
233
// the execution lifetime of a single request. A RunData object
234
// is created/recycled for each and every request and is passed
235
// to each and every module. Since each thread has its own RunData
236
// object, it is not necessary to perform syncronization for
237
// the data within this object.
238
if (req == null || res == null || config == null)
239         {
240             throw new IllegalArgumentException JavaDoc(
241                 "RunDataFactory fatal error: HttpServletRequest, HttpServletResponse or ServletConfig was null.");
242         }
243
244         // Get the specified configuration.
245
String JavaDoc[] cfg = (String JavaDoc[]) configurations.get(key);
246         if (cfg == null)
247         {
248             throw new ServiceException("RunTime configuration '" + key +
249                                        "' is undefined");
250         }
251
252         TurbineRunData data;
253         try
254         {
255             // Use the Pool Service for recycling the implementing objects.
256
YaafiComponentService yaafi = (YaafiComponentService)TurbineServices.getInstance().getService(YaafiComponentService.SERVICE_NAME);
257
258             PoolService pool = (PoolService)yaafi.lookup(PoolService.class.getName());
259             data = (TurbineRunData) pool.getInstance(Class.forName(cfg[0]));
260             data.setParameterParser((ParameterParser) pool.getInstance(Class.forName(cfg[1])));
261             if( data.getParameterParser() instanceof DefaultParameterParser){
262                 DefaultParameterParser parser = (DefaultParameterParser)data.getParameterParser();
263                 UploadService uploadService = (UploadService)yaafi.lookup(UploadService.class.getName());
264                 parser.setUploadService(uploadService);
265             }
266             data.setCookieParser((CookieParser) pool.getInstance(Class.forName(cfg[2])));
267         }
268         catch (ClassNotFoundException JavaDoc cnfe)
269         {
270             throw new ServiceException("Missing class", cnfe);
271         }
272         catch (ClassCastException JavaDoc x)
273         {
274             throw new ServiceException("RunData configuration '" + key +
275                                        "' is illegal", x);
276         }
277         catch (PoolException pe)
278         {
279             throw new ServiceException("Pooling Exception", pe);
280         }
281         catch (Exception JavaDoc e)
282         {
283             throw new ServiceException("Lookup Exception", e);
284         }
285
286         // Set the request and response.
287
data.setRequest(req);
288         data.setResponse(res);
289
290         // Set the session object.
291
data.setSession(data.getRequest().getSession(true));
292
293         // Set the servlet configuration.
294
data.setServletConfig(config);
295
296         // Set server info
297
String JavaDoc contextPath;
298
299         try
300         {
301             contextPath = getContextPath != null ?
302                 (String JavaDoc) getContextPath.invoke(req,null) : "";
303         }
304         catch (Exception JavaDoc x)
305         {
306             contextPath = "";
307         }
308         String JavaDoc scriptName = contextPath + req.getServletPath();
309
310         data.setServerName(req.getServerName());
311         data.setServerPort(req.getServerPort());
312         data.setServerScheme(req.getScheme());
313         data.setScriptName(scriptName);
314         data.setContextPath(contextPath);
315
316         return (RunData) data;
317     }
318
319     /**
320      * Puts the used RunData object back to the factory for recycling.
321      *
322      * @param data the used RunData object.
323      * @return true, if pooling is supported and the object was accepted.
324      */

325     public boolean putRunData(RunData data)
326     {
327         if (data instanceof TurbineRunData)
328         {
329             YaafiComponentService yaafi = (YaafiComponentService)TurbineServices.getInstance().getService(YaafiComponentService.SERVICE_NAME);
330             try {
331             PoolService pool = (PoolService)yaafi.lookup(PoolService.class.getName());
332                 
333             pool.putInstance(((TurbineRunData) data).getParameterParser());
334             pool.putInstance(((TurbineRunData) data).getCookieParser());
335             return pool.putInstance(data);
336             }
337             catch (Exception JavaDoc e){
338                 throw new RuntimeException JavaDoc("Problem looking up pool service",e);
339             }
340         }
341         else
342         {
343             return false;
344         }
345     }
346 }
347
Popular Tags