KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * $Id: CoreEvents.java 5462 2005-08-05 18:35:48Z jonesde $
3  *
4  * Copyright (c) 2001-2003 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.io.File JavaDoc;
28 import java.io.FileInputStream JavaDoc;
29 import java.io.FileNotFoundException JavaDoc;
30 import java.io.IOException JavaDoc;
31 import java.sql.Timestamp JavaDoc;
32 import java.util.Date JavaDoc;
33 import java.util.HashMap JavaDoc;
34 import java.util.Iterator JavaDoc;
35 import java.util.Locale JavaDoc;
36 import java.util.Map JavaDoc;
37 import javax.servlet.http.HttpServletRequest JavaDoc;
38 import javax.servlet.http.HttpServletResponse JavaDoc;
39
40 import org.ofbiz.base.util.Debug;
41 import org.ofbiz.base.util.UtilHttp;
42 import org.ofbiz.base.util.UtilProperties;
43 import org.ofbiz.base.util.UtilValidate;
44 import org.ofbiz.webapp.control.RequestHandler;
45 import org.ofbiz.entity.GenericDelegator;
46 import org.ofbiz.entity.GenericValue;
47 import org.ofbiz.security.Security;
48 import org.ofbiz.service.DispatchContext;
49 import org.ofbiz.service.GenericServiceException;
50 import org.ofbiz.service.LocalDispatcher;
51 import org.ofbiz.service.ModelService;
52 import org.ofbiz.service.ServiceDispatcher;
53 import org.ofbiz.service.WebAppDispatcher;
54 import org.ofbiz.service.calendar.RecurrenceRule;
55
56 /**
57  * CoreEvents - WebApp Events Related To Framework pieces
58  *
59  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
60  * @version $Rev: 5462 $
61  * @since 2.0
62  */

63 public class CoreEvents {
64     
65     public static final String JavaDoc module = CoreEvents.class.getName();
66     public static final String JavaDoc err_resource = "WebappUiLabels";
67
68     /**
69      * Return success event. Used as a place holder for events.
70      * @param request HttpServletRequest
71      * @param response HttpServletResponse
72      * @return Response code string
73      */

74     public static String JavaDoc returnSuccess(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
75         return "success";
76     }
77
78     /**
79      * Return error event. Used as a place holder for events.
80      * @param request HttpServletRequest
81      * @param response HttpServletResponse
82      * @return Response code string
83      */

84     public static String JavaDoc returnError(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
85         return "error";
86     }
87
88     /**
89      * Return null event. Used as a place holder for events.
90      * @param request HttpServletRequest
91      * @param response HttpServletResponse
92      * @return Response code string
93      */

94     public static String JavaDoc returnNull(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
95         return null;
96     }
97
98     /**
99      * Change delegator event. Changes the delegator for the current session
100      * @param request HttpServletRequest
101      * @param response HttpServletResponse
102      * @return Response code string
103      */

104     public static String JavaDoc changeDelegator(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
105         String JavaDoc delegatorName = request.getParameter("delegator");
106         Security security = (Security) request.getAttribute("security");
107         Locale JavaDoc locale = UtilHttp.getLocale(request);
108
109         if (!security.hasPermission("ENTITY_MAINT", request.getSession())) {
110             String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.not_authorized_use_fct", locale);
111             request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg);
112             return "error";
113         }
114         if (delegatorName == null) {
115             String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.delegator_not_passed", locale);
116             request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg);
117             return "error";
118         }
119
120         GenericDelegator delegator = GenericDelegator.getGenericDelegator(delegatorName);
121
122         if (delegator == null) {
123             String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.no_delegator_name_defined", locale);
124             request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg);
125             return "error";
126         }
127
128         // now change the dispatcher to use this delegator
129
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
130         DispatchContext dctx = dispatcher.getDispatchContext();
131         String JavaDoc dispatcherName = dispatcher.getName();
132
133         if (dispatcherName == null) {
134             String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.dispatcher_name_null", locale);
135             request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg);
136             return "error";
137         }
138         if (dctx == null) {
139             String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.dispatcher_context_null", locale);
140             request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg);
141             return "error";
142         }
143
144         ServiceDispatcher sd = ServiceDispatcher.getInstance(dispatcherName, delegator);
145
146         if (sd == null)
147             dispatcher = new WebAppDispatcher(dctx, delegator);
148         else
149             dispatcher = sd.getLocalContext(dispatcherName).getDispatcher();
150
151         request.getSession().setAttribute("delegator", delegator);
152         request.getSession().setAttribute("dispatcher", dispatcher);
153
154         return "success";
155     }
156
157     /**
158      * Change dispatcher event. Changes the dispatch for the current session
159      * @param request HttpServletRequest
160      * @param response HttpServletResponse
161      * @return Response code string
162      */

163     public static String JavaDoc changeDispatcher(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
164         String JavaDoc dispatcherName = request.getParameter("dispatcher");
165         Security security = (Security) request.getAttribute("security");
166         Locale JavaDoc locale = UtilHttp.getLocale(request);
167
168         if (!security.hasPermission("ENTITY_MAINT", request.getSession())) {
169             String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.not_authorized_use_fct", locale);
170             request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg);
171             return "error";
172         }
173         if (dispatcherName == null) {
174             String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.dispatcher_not_passed", locale);
175             request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg);
176             return "error";
177         }
178
179         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
180         ServiceDispatcher sd = ServiceDispatcher.getInstance(dispatcherName, delegator);
181
182         if (sd == null) {
183             String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.no_dispachter_name_registered", locale);
184             request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg);
185             return "error";
186         }
187         LocalDispatcher dispatcher = sd.getLocalContext(dispatcherName).getDispatcher();
188
189         request.getSession().setAttribute("dispatcher", dispatcher);
190         return "success";
191     }
192
193     /**
194      * Schedule a service for a specific time or recurrence
195      * Request Parameters which are used for this service:
196      *
197      * SERVICE_NAME - Name of the service to invoke
198      * SERVICE_TIME - First time the service will occur
199      * SERVICE_FREQUENCY - The type of recurrence (SECONDLY,MINUTELY,DAILY,etc)
200      * SERVICE_INTERVAL - The interval of the frequency (every 5 minutes, etc)
201      *
202      * @param request HttpServletRequest
203      * @param response HttpServletResponse
204      * @return Response code string
205      */

206     public static String JavaDoc scheduleService(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
207         GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
208         Security security = (Security) request.getAttribute("security");
209         LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
210         //GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
211
Locale JavaDoc locale = UtilHttp.getLocale(request);
212         
213         Map JavaDoc params = UtilHttp.getParameterMap(request);
214         // get the schedule parameters
215
String JavaDoc serviceName = (String JavaDoc) params.remove("SERVICE_NAME");
216         String JavaDoc poolName = (String JavaDoc) params.remove("POOL_NAME");
217         String JavaDoc serviceTime = (String JavaDoc) params.remove("SERVICE_TIME");
218         String JavaDoc serviceEndTime = (String JavaDoc) params.remove("SERVICE_END_TIME");
219         String JavaDoc serviceFreq = (String JavaDoc) params.remove("SERVICE_FREQUENCY");
220         String JavaDoc serviceIntr = (String JavaDoc) params.remove("SERVICE_INTERVAL");
221         String JavaDoc serviceCnt = (String JavaDoc) params.remove("SERVICE_COUNT");
222         String JavaDoc retryCnt = (String JavaDoc) params.remove("SERVICE_MAXRETRY");
223
224         // the frequency map
225
Map JavaDoc freqMap = new HashMap JavaDoc();
226
227         freqMap.put("SECONDLY", new Integer JavaDoc(1));
228         freqMap.put("MINUTELY", new Integer JavaDoc(2));
229         freqMap.put("HOURLY", new Integer JavaDoc(3));
230         freqMap.put("DAILY", new Integer JavaDoc(4));
231         freqMap.put("WEEKLY", new Integer JavaDoc(5));
232         freqMap.put("MONTHLY", new Integer JavaDoc(6));
233         freqMap.put("YEARLY", new Integer JavaDoc(7));
234
235         // some defaults
236
long startTime = (new Date JavaDoc()).getTime();
237         long endTime = 0;
238         int maxRetry = -1;
239         int count = 1;
240         int interval = 1;
241         int frequency = RecurrenceRule.DAILY;
242
243         StringBuffer JavaDoc errorBuf = new StringBuffer JavaDoc();
244
245         // make sure we passed a service
246
if (serviceName == null) {
247             String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.must_specify_service", locale);
248             request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg);
249             return "error";
250         }
251
252         // lookup the service definition to see if this service is externally available, if not require the SERVICE_INVOKE_ANY permission
253
ModelService modelService = null;
254         try {
255             modelService = dispatcher.getDispatchContext().getModelService(serviceName);
256         } catch (GenericServiceException e) {
257             Debug.logError(e, "Error looking up ModelService for serviceName [" + serviceName + "]", module);
258             String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.error_modelservice_for_srv_name", locale);
259             request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg + " [" + serviceName + "]: " + e.toString());
260             return "error";
261         }
262         if (modelService == null) {
263             String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_name_not_find", locale);
264             request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg + " [" + serviceName + "]");
265             return "error";
266         }
267         
268         // make the context valid; using the makeValid method from ModelService
269
Map JavaDoc serviceContext = new HashMap JavaDoc();
270         Iterator JavaDoc ci = modelService.getInParamNames().iterator();
271         while (ci.hasNext()) {
272             String JavaDoc name = (String JavaDoc) ci.next();
273
274             // don't include userLogin, that's taken care of below
275
if ("userLogin".equals(name)) continue;
276             // don't include locale, that is also taken care of below
277
if ("locale".equals(name)) continue;
278             
279             Object JavaDoc value = request.getParameter(name);
280
281             // if the parameter wasn't passed and no other value found, don't pass on the null
282
if (value == null) {
283                 value = request.getAttribute(name);
284             }
285             if (value == null) {
286                 value = request.getSession().getAttribute(name);
287             }
288             if (value == null) {
289                 // still null, give up for this one
290
continue;
291             }
292             
293             if (value instanceof String JavaDoc && ((String JavaDoc) value).length() == 0) {
294                 // interpreting empty fields as null values for each in back end handling...
295
value = null;
296             }
297
298             // set even if null so that values will get nulled in the db later on
299
serviceContext.put(name, value);
300         }
301         serviceContext = modelService.makeValid(serviceContext, ModelService.IN_PARAM, true, null, locale);
302         
303         if (userLogin != null) {
304             serviceContext.put("userLogin", userLogin);
305         }
306         
307         if (locale != null) {
308             serviceContext.put("locale", locale);
309         }
310                 
311         if (!modelService.export && !security.hasPermission("SERVICE_INVOKE_ANY", request.getSession())) {
312             String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.not_authorized_to_call", locale);
313             request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg);
314             return "error";
315         }
316         
317         // some conversions
318
if (serviceTime != null && serviceTime.length() > 0) {
319             try {
320                 Timestamp JavaDoc ts1 = Timestamp.valueOf(serviceTime);
321                 startTime = ts1.getTime();
322             } catch (IllegalArgumentException JavaDoc e) {
323                 try {
324                     startTime = Long.parseLong(serviceTime);
325                 } catch (NumberFormatException JavaDoc nfe) {
326                     String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.invalid_format_time", locale);
327                     errorBuf.append("<li>" + errMsg);
328                 }
329             }
330             if (startTime < (new Date JavaDoc()).getTime()) {
331                 String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_time_already_passed", locale);
332                 errorBuf.append("<li>" + errMsg);
333             }
334         }
335         if (serviceEndTime != null && serviceEndTime.length() > 0) {
336             try {
337                 Timestamp JavaDoc ts1 = Timestamp.valueOf(serviceEndTime);
338                 endTime = ts1.getTime();
339             } catch (IllegalArgumentException JavaDoc e) {
340                 try {
341                     endTime = Long.parseLong(serviceTime);
342                 } catch (NumberFormatException JavaDoc nfe) {
343                     String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.invalid_format_time", locale);
344                     errorBuf.append("<li>" + errMsg);
345                 }
346             }
347             if (endTime < (new Date JavaDoc()).getTime()) {
348                 String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_time_already_passed", locale);
349                 errorBuf.append("<li>" + errMsg);
350             }
351         }
352         if (serviceIntr != null && serviceIntr.length() > 0) {
353             try {
354                 interval = Integer.parseInt(serviceIntr);
355             } catch (NumberFormatException JavaDoc nfe) {
356                 String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.invalid_format_interval", locale);
357                 errorBuf.append("<li>" + errMsg);
358             }
359         }
360         if (serviceCnt != null && serviceCnt.length() > 0) {
361             try {
362                 count = Integer.parseInt(serviceCnt);
363             } catch (NumberFormatException JavaDoc nfe) {
364                 String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.invalid_format_count", locale);
365                 errorBuf.append("<li>" + errMsg);
366             }
367         }
368         if (serviceFreq != null && serviceFreq.length() > 0) {
369             int parsedValue = 0;
370
371             try {
372                 parsedValue = Integer.parseInt(serviceFreq);
373                 if (parsedValue > 0 && parsedValue < 8)
374                     frequency = parsedValue;
375             } catch (NumberFormatException JavaDoc nfe) {
376                 parsedValue = 0;
377             }
378             if (parsedValue == 0) {
379                 if (!freqMap.containsKey(serviceFreq.toUpperCase())) {
380                     String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.invalid_format_frequency", locale);
381                     errorBuf.append("<li>" + errMsg);
382                 } else {
383                     frequency = ((Integer JavaDoc) freqMap.get(serviceFreq.toUpperCase())).intValue();
384                 }
385             }
386         }
387         if (retryCnt != null && retryCnt.length() > 0) {
388             int parsedValue = -2;
389
390             try {
391                 parsedValue = Integer.parseInt(retryCnt);
392             } catch (NumberFormatException JavaDoc e) {
393                 parsedValue = -2;
394             }
395             if (parsedValue > -2) {
396                 maxRetry = parsedValue;
397             } else {
398                 maxRetry = modelService.maxRetry;
399             }
400         } else {
401             maxRetry = modelService.maxRetry;
402         }
403
404         // return the errors
405
if (errorBuf.length() > 0) {
406             request.setAttribute("_ERROR_MESSAGE_", errorBuf.toString());
407             return "error";
408         }
409                       
410         // schedule service
411
try {
412             dispatcher.schedule(poolName, serviceName, serviceContext, startTime, frequency, interval, count, endTime, maxRetry);
413         } catch (GenericServiceException e) {
414             String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_dispatcher_exception", locale);
415             request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg + e.getMessage());
416             return "error";
417         }
418
419         String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_scheduled", locale);
420         request.setAttribute("_EVENT_MESSAGE_", errMsg);
421         return "success";
422     }
423
424     public static ServiceEventHandler seh = new ServiceEventHandler();
425
426     /**
427      * Run a service.
428      * Request Parameters which are used for this event:
429      * SERVICE_NAME - Name of the service to invoke
430      *
431      * @param request HttpServletRequest
432      * @param response HttpServletResponse
433      * @return Response code string
434      */

435     public static String JavaDoc runService(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
436         // get the mode and service name
437
String JavaDoc serviceName = request.getParameter("serviceName");
438         String JavaDoc mode = request.getParameter("mode");
439         Locale JavaDoc locale = UtilHttp.getLocale(request);
440         
441         if (UtilValidate.isEmpty(serviceName)) {
442             String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.must_specify_service_name", locale);
443             request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg);
444             return "error";
445         }
446
447         if (UtilValidate.isEmpty(mode)) {
448             mode = "sync";
449         }
450         
451         // now do a security check
452

453         Security security = (Security) request.getAttribute("security");
454         LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
455         
456         //lookup the service definition to see if this service is externally available, if not require the SERVICE_INVOKE_ANY permission
457
ModelService modelService = null;
458         try {
459             modelService = dispatcher.getDispatchContext().getModelService(serviceName);
460         } catch (GenericServiceException e) {
461             Debug.logError(e, "Error looking up ModelService for serviceName [" + serviceName + "]", module);
462             String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.error_modelservice_for_srv_name", locale);
463             request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg + "[" + serviceName + "]: " + e.toString());
464             return "error";
465         }
466         if (modelService == null) {
467             String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_name_not_find", locale);
468             request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg + "[" + serviceName + "]");
469             return "error";
470         }
471
472         if (!modelService.export && !security.hasPermission("SERVICE_INVOKE_ANY", request.getSession())) {
473             String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.not_authorized_to_call", locale);
474             request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg + ".");
475             return "error";
476         }
477         
478         Debug.logInfo("Running service named [" + serviceName + "] from event with mode [" + mode + "]", module);
479         
480         // call the service via the ServiceEventHandler which
481
// adapts an event to a service.
482
try {
483             return seh.invoke(mode, serviceName, request, response);
484         } catch (EventHandlerException e) {
485             String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_eventhandler_exception", locale);
486             request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg + ": " + e.getMessage());
487             return "error";
488         }
489     }
490     
491     public static String JavaDoc streamFile(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
492         //RequestHandler rh = (RequestHandler) request.getAttribute("_REQUEST_HANDLER_");
493
String JavaDoc filePath = RequestHandler.getNextPageUri(request.getPathInfo());
494         //String fileName = filePath.substring(filePath.lastIndexOf("/")+1);
495

496         // load the file
497
File JavaDoc file = new File JavaDoc(filePath);
498         if (file.exists()) {
499             Long JavaDoc longLen = new Long JavaDoc(file.length());
500             int length = longLen.intValue();
501             try {
502                 FileInputStream JavaDoc fis = new FileInputStream JavaDoc(file);
503                 UtilHttp.streamContentToBrowser(response, fis, length, null);
504                 fis.close();
505             } catch (FileNotFoundException JavaDoc e) {
506                 Debug.logError(e, module);
507                 return "error";
508             } catch (IOException JavaDoc e) {
509                 Debug.logError(e, module);
510                 return "error";
511             }
512         }
513         return null;
514     }
515 }
516
Popular Tags