KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > webapp > event > ServiceEventHandler


1 /*
2  * $Id: ServiceEventHandler.java 6475 2006-01-07 17:57:17Z jonesde $
3  *
4  * Copyright (c) 2001-2005 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  */

25 package org.ofbiz.webapp.event;
26
27 import java.util.ArrayList JavaDoc;
28 import java.util.Arrays JavaDoc;
29 import java.util.HashMap JavaDoc;
30 import java.util.Iterator JavaDoc;
31 import java.util.LinkedList JavaDoc;
32 import java.util.List JavaDoc;
33 import java.util.Locale JavaDoc;
34 import java.util.Map JavaDoc;
35 import javax.servlet.ServletContext JavaDoc;
36 import javax.servlet.http.HttpServletRequest JavaDoc;
37 import javax.servlet.http.HttpServletResponse JavaDoc;
38 import javax.servlet.http.HttpSession JavaDoc;
39
40 import org.apache.commons.fileupload.DiskFileUpload;
41 import org.apache.commons.fileupload.FileItem;
42 import org.apache.commons.fileupload.FileUpload;
43 import org.apache.commons.fileupload.FileUploadException;
44
45 import org.ofbiz.base.util.Debug;
46 import org.ofbiz.base.util.UtilHttp;
47 import org.ofbiz.base.util.UtilProperties;
48 import org.ofbiz.base.util.UtilValidate;
49 import org.ofbiz.entity.GenericValue;
50 import org.ofbiz.entity.util.ByteWrapper;
51 import org.ofbiz.service.DispatchContext;
52 import org.ofbiz.service.GenericServiceException;
53 import org.ofbiz.service.LocalDispatcher;
54 import org.ofbiz.service.ModelParam;
55 import org.ofbiz.service.ModelService;
56 import org.ofbiz.service.ServiceAuthException;
57 import org.ofbiz.service.ServiceValidationException;
58
59 /**
60  * ServiceEventHandler - Service Event Handler
61  *
62  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
63  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
64  * @version $Rev: 6475 $
65  * @since 2.0
66  */

67 public class ServiceEventHandler implements EventHandler {
68
69     public static final String JavaDoc module = ServiceEventHandler.class.getName();
70
71     public static final String JavaDoc SYNC = "sync";
72     public static final String JavaDoc ASYNC = "async";
73
74     /**
75      * @see org.ofbiz.webapp.event.EventHandler#init(javax.servlet.ServletContext)
76      */

77     public void init(ServletContext JavaDoc context) throws EventHandlerException {
78     }
79
80     /**
81      * @see org.ofbiz.webapp.event.EventHandler#invoke(java.lang.String, java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
82      */

83     public String JavaDoc invoke(String JavaDoc eventPath, String JavaDoc eventMethod, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws EventHandlerException {
84         // make sure we have a valid reference to the Service Engine
85
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
86         if (dispatcher == null) {
87             throw new EventHandlerException("The local service dispatcher is null");
88         }
89         DispatchContext dctx = dispatcher.getDispatchContext();
90         if (dctx == null) {
91             throw new EventHandlerException("Dispatch context cannot be found");
92         }
93
94         // get the details for the service(s) to call
95
String JavaDoc mode = SYNC;
96         String JavaDoc serviceName = null;
97
98         if (eventPath == null || eventPath.length() == 0) {
99             mode = SYNC;
100         } else {
101             mode = eventPath;
102         }
103
104         // nake sure we have a defined service to call
105
serviceName = eventMethod;
106         if (serviceName == null) {
107             throw new EventHandlerException("Service name (eventMethod) cannot be null");
108         }
109         if (Debug.verboseOn()) Debug.logVerbose("[Set mode/service]: " + mode + "/" + serviceName, module);
110
111         // some needed info for when running the service
112
Locale JavaDoc locale = UtilHttp.getLocale(request);
113         HttpSession JavaDoc session = request.getSession();
114         GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
115
116         // get the service model to generate context
117
ModelService model = null;
118
119         try {
120             model = dctx.getModelService(serviceName);
121         } catch (GenericServiceException e) {
122             throw new EventHandlerException("Problems getting the service model", e);
123         }
124
125         if (model == null) {
126             throw new EventHandlerException("Problems getting the service model");
127         }
128
129         if (Debug.verboseOn()) Debug.logVerbose("[Processing]: SERVICE Event", module);
130         if (Debug.verboseOn()) Debug.logVerbose("[Using delegator]: " + dispatcher.getDelegator().getDelegatorName(), module);
131
132         // get the http upload configuration
133
String JavaDoc maxSizeStr = UtilProperties.getPropertyValue("general.properties", "http.upload.max.size", "-1");
134         long maxUploadSize = -1;
135         try {
136             maxUploadSize = Long.parseLong(maxSizeStr);
137         } catch (NumberFormatException JavaDoc e) {
138             Debug.logError(e, "Unable to obtain the max upload size from general.properties; using default -1", module);
139             maxUploadSize = -1;
140         }
141
142         // check for multipart content types which may have uploaded items
143
boolean isMultiPart = FileUpload.isMultipartContent(request);
144         Map JavaDoc multiPartMap = new HashMap JavaDoc();
145         if (isMultiPart) {
146             DiskFileUpload upload = new DiskFileUpload();
147             upload.setSizeMax(maxUploadSize);
148
149             List JavaDoc uploadedItems = null;
150             try {
151                 uploadedItems = upload.parseRequest(request);
152             } catch (FileUploadException e) {
153                 throw new EventHandlerException("Problems reading uploaded data", e);
154             }
155             if (uploadedItems != null) {
156                 Iterator JavaDoc i = uploadedItems.iterator();
157                 while (i.hasNext()) {
158                     FileItem item = (FileItem) i.next();
159                     String JavaDoc fieldName = item.getFieldName();
160                     //byte[] itemBytes = item.get();
161

162                     //Debug.log("Item Info : " + item.getName() + " / " + item.getSize() + " / " + item.getContentType(), module);
163
if (item.isFormField() || item.getSize() == 0) {
164                         if (multiPartMap.containsKey(fieldName)) {
165                             Object JavaDoc mapValue = multiPartMap.get(fieldName);
166                             if (mapValue instanceof List JavaDoc) {
167                                 ((List JavaDoc) mapValue).add(item.getString());
168                             } else if (mapValue instanceof String JavaDoc) {
169                                 List JavaDoc newList = new ArrayList JavaDoc();
170                                 newList.add((String JavaDoc) mapValue);
171                                 newList.add(item.getString());
172                                 multiPartMap.put(fieldName, newList);
173                             } else {
174                                 Debug.logWarning("Form field found [" + fieldName + "] which was not handled!", module);
175                             }
176                         } else {
177                             multiPartMap.put(fieldName, item.getString());
178                         }
179                     } else {
180                         String JavaDoc fileName = item.getName();
181                         if (fileName.indexOf('\\') > -1 || fileName.indexOf('/') > -1) {
182                             // get just the file name IE and other browsers also pass in the local path
183
int lastIndex = fileName.lastIndexOf('\\');
184                             if (lastIndex == -1) {
185                                 lastIndex = fileName.lastIndexOf('/');
186                             }
187                             if (lastIndex > -1) {
188                                 fileName = fileName.substring(lastIndex + 1);
189                             }
190                         }
191                         multiPartMap.put(fieldName, new ByteWrapper(item.get()));
192                         multiPartMap.put("_" + fieldName + "_size", new Long JavaDoc(item.getSize()));
193                         multiPartMap.put("_" + fieldName + "_fileName", fileName);
194                         multiPartMap.put("_" + fieldName + "_contentType", item.getContentType());
195                     }
196                 }
197             }
198         }
199
200         // store the multi-part map as an attribute so we can access the parameters
201
request.setAttribute("multiPartMap", multiPartMap);
202
203         // we have a service and the model; build the context
204
Map JavaDoc serviceContext = new HashMap JavaDoc();
205         Iterator JavaDoc modelParmInIter = model.getInModelParamList().iterator();
206         while (modelParmInIter.hasNext()) {
207             ModelParam modelParam = (ModelParam) modelParmInIter.next();
208             String JavaDoc name = modelParam.name;
209
210             // don't include userLogin, that's taken care of below
211
if ("userLogin".equals(name)) continue;
212             // don't include locale, that is also taken care of below
213
if ("locale".equals(name)) continue;
214
215             Object JavaDoc value = null;
216             if (modelParam.stringMapPrefix != null && modelParam.stringMapPrefix.length() > 0) {
217                 Map JavaDoc paramMap = UtilHttp.makeParamMapWithPrefix(request, multiPartMap, modelParam.stringMapPrefix, null);
218                 value = paramMap;
219                 if (Debug.verboseOn()) Debug.log("Set [" + modelParam.name + "]: " + paramMap, module);
220             } else if (modelParam.stringListSuffix != null && modelParam.stringListSuffix.length() > 0) {
221                 List JavaDoc paramList = UtilHttp.makeParamListWithSuffix(request, multiPartMap, modelParam.stringListSuffix, null);
222                 value = paramList;
223             } else {
224                 // first check the multi-part map
225
value = multiPartMap.get(name);
226
227                 // check the request parameters
228
if (UtilValidate.isEmpty(value)) {
229                     // normal parameter data, which can either be a single value or an array of values
230
String JavaDoc[] paramArr = request.getParameterValues(name);
231                     if (paramArr != null) {
232                         if (paramArr.length > 1) {
233                             value = Arrays.asList(paramArr);
234                         } else {
235                             value = paramArr[0];
236                         }
237                     }
238                     // make any composite parameter data (e.g., from a set of parameters {name_c_date, name_c_hour, name_c_minutes})
239
if (value == null) {
240                         value = UtilHttp.makeParamValueFromComposite(request, name, locale);
241                     }
242                 }
243
244                 // next check attributes
245
if (UtilValidate.isEmpty(value)) {
246                     Object JavaDoc tempVal = request.getAttribute(name);
247                     if (tempVal != null) {
248                         value = tempVal;
249                     }
250                 }
251
252                 // then session
253
if (UtilValidate.isEmpty(value)) {
254                     Object JavaDoc tempVal = request.getSession().getAttribute(name);
255                     if (tempVal != null) {
256                         value = tempVal;
257                     }
258                 }
259
260                 // no field found
261
if (value == null) {
262                     //still null, give up for this one
263
continue;
264                 }
265
266                 if (value instanceof String JavaDoc && ((String JavaDoc) value).length() == 0) {
267                     // interpreting empty fields as null values for each in back end handling...
268
value = null;
269                 }
270             }
271             // set even if null so that values will get nulled in the db later on
272
serviceContext.put(name, value);
273         }
274
275         // get only the parameters for this service - converted to proper type
276
// TODO: pass in a list for error messages, like could not convert type or not a proper X, return immediately with messages if there are any
277
List JavaDoc errorMessages = new LinkedList JavaDoc();
278         serviceContext = model.makeValid(serviceContext, ModelService.IN_PARAM, true, errorMessages, locale);
279         if (errorMessages.size() > 0) {
280             // uh-oh, had some problems...
281
request.setAttribute("_ERROR_MESSAGE_LIST_", errorMessages);
282             return "error";
283         }
284
285         // include the UserLogin value object
286
if (userLogin != null) {
287             serviceContext.put("userLogin", userLogin);
288         }
289
290         // include the Locale object
291
if (locale != null) {
292             serviceContext.put("locale", locale);
293         }
294
295         // invoke the service
296
Map JavaDoc result = null;
297         try {
298             if (ASYNC.equalsIgnoreCase(mode)) {
299                 dispatcher.runAsync(serviceName, serviceContext);
300             } else {
301                 result = dispatcher.runSync(serviceName, serviceContext);
302             }
303         } catch (ServiceAuthException e) {
304             // not logging since the service engine already did
305
request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage());
306             return "error";
307         } catch (ServiceValidationException e) {
308             // not logging since the service engine already did
309
request.setAttribute("serviceValidationException", e);
310             if (e.getMessageList() != null) {
311                 request.setAttribute("_ERROR_MESSAGE_LIST_", e.getMessageList());
312             } else {
313                 request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage());
314             }
315             return "error";
316         } catch (GenericServiceException e) {
317             Debug.logError(e, "Service invocation error", module);
318             throw new EventHandlerException("Service invocation error", e.getNested());
319         }
320
321         String JavaDoc responseString = null;
322
323         if (result == null) {
324             responseString = ModelService.RESPOND_SUCCESS;
325         } else {
326
327             if (!result.containsKey(ModelService.RESPONSE_MESSAGE)) {
328                 responseString = ModelService.RESPOND_SUCCESS;
329             } else {
330                 responseString = (String JavaDoc) result.get(ModelService.RESPONSE_MESSAGE);
331             }
332
333             // set the messages in the request; this will be picked up by messages.ftl and displayed
334
request.setAttribute("_ERROR_MESSAGE_LIST_", result.get(ModelService.ERROR_MESSAGE_LIST));
335             request.setAttribute("_ERROR_MESSAGE_MAP_", result.get(ModelService.ERROR_MESSAGE_MAP));
336             request.setAttribute("_ERROR_MESSAGE_", result.get(ModelService.ERROR_MESSAGE));
337
338             request.setAttribute("_EVENT_MESSAGE_LIST_", result.get(ModelService.SUCCESS_MESSAGE_LIST));
339             request.setAttribute("_EVENT_MESSAGE_", result.get(ModelService.SUCCESS_MESSAGE));
340
341             // set the results in the request
342
Iterator JavaDoc rmei = result.entrySet().iterator();
343             while (rmei.hasNext()) {
344                 Map.Entry JavaDoc rme = (Map.Entry JavaDoc) rmei.next();
345                 String JavaDoc resultKey = (String JavaDoc) rme.getKey();
346                 Object JavaDoc resultValue = rme.getValue();
347
348                 if (resultKey != null && !ModelService.RESPONSE_MESSAGE.equals(resultKey) && !ModelService.ERROR_MESSAGE.equals(resultKey) &&
349                         !ModelService.ERROR_MESSAGE_LIST.equals(resultKey) && !ModelService.ERROR_MESSAGE_MAP.equals(resultKey) &&
350                         !ModelService.SUCCESS_MESSAGE.equals(resultKey) && !ModelService.SUCCESS_MESSAGE_LIST.equals(resultKey)) {
351                     request.setAttribute(resultKey, resultValue);
352                 }
353             }
354         }
355
356         if (Debug.verboseOn()) Debug.logVerbose("[Event Return]: " + responseString, module);
357         return responseString;
358     }
359 }
360
Popular Tags