001: /*
002: * $Id: CoreEvents.java,v 1.5 2003/12/05 21:03:55 ajzeneski Exp $
003: *
004: * Copyright (c) 2001-2003 The Open For Business Project - www.ofbiz.org
005: *
006: * Permission is hereby granted, free of charge, to any person obtaining a
007: * copy of this software and associated documentation files (the "Software"),
008: * to deal in the Software without restriction, including without limitation
009: * the rights to use, copy, modify, merge, publish, distribute, sublicense,
010: * and/or sell copies of the Software, and to permit persons to whom the
011: * Software is furnished to do so, subject to the following conditions:
012: *
013: * The above copyright notice and this permission notice shall be included
014: * in all copies or substantial portions of the Software.
015: *
016: * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
017: * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
018: * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
019: * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
020: * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
021: * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
022: * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
023: *
024: */
025: package org.ofbiz.content.webapp.event;
026:
027: import java.io.File;
028: import java.io.FileInputStream;
029: import java.io.FileNotFoundException;
030: import java.io.IOException;
031: import java.sql.Timestamp;
032: import java.util.Date;
033: import java.util.HashMap;
034: import java.util.Iterator;
035: import java.util.Locale;
036: import java.util.Map;
037:
038: import javax.servlet.http.HttpServletRequest;
039: import javax.servlet.http.HttpServletResponse;
040:
041: import org.ofbiz.base.util.Debug;
042: import org.ofbiz.base.util.UtilHttp;
043: import org.ofbiz.base.util.UtilValidate;
044: import org.ofbiz.content.webapp.control.RequestHandler;
045: import org.ofbiz.entity.GenericDelegator;
046: import org.ofbiz.entity.GenericValue;
047: import org.ofbiz.security.Security;
048: import org.ofbiz.service.DispatchContext;
049: import org.ofbiz.service.GenericServiceException;
050: import org.ofbiz.service.LocalDispatcher;
051: import org.ofbiz.service.ModelService;
052: import org.ofbiz.service.ServiceDispatcher;
053: import org.ofbiz.service.WebAppDispatcher;
054: import org.ofbiz.service.calendar.RecurrenceRule;
055:
056: /**
057: * CoreEvents - WebApp Events Related To CORE components
058: *
059: * @author <a href="mailto:jaz@ofbiz.org">Andy Zeneski</a>
060: * @version $Revision: 1.5 $
061: * @since 2.0
062: */
063: public class CoreEvents {
064:
065: public static final String module = CoreEvents.class.getName();
066:
067: /**
068: * Return success event. Used as a place holder for events.
069: * @param request HttpServletRequest
070: * @param response HttpServletResponse
071: * @return Response code string
072: */
073: public static String returnSuccess(HttpServletRequest request,
074: HttpServletResponse response) {
075: return "success";
076: }
077:
078: /**
079: * Return error event. Used as a place holder for events.
080: * @param request HttpServletRequest
081: * @param response HttpServletResponse
082: * @return Response code string
083: */
084: public static String returnError(HttpServletRequest request,
085: HttpServletResponse response) {
086: return "error";
087: }
088:
089: /**
090: * Return null event. Used as a place holder for events.
091: * @param request HttpServletRequest
092: * @param response HttpServletResponse
093: * @return Response code string
094: */
095: public static String returnNull(HttpServletRequest request,
096: HttpServletResponse response) {
097: return null;
098: }
099:
100: /**
101: * Change delegator event. Changes the delegator for the current session
102: * @param request HttpServletRequest
103: * @param response HttpServletResponse
104: * @return Response code string
105: */
106: public static String changeDelegator(HttpServletRequest request,
107: HttpServletResponse response) {
108: String delegatorName = request.getParameter("delegator");
109: Security security = (Security) request.getAttribute("security");
110:
111: if (!security.hasPermission("ENTITY_MAINT", request
112: .getSession())) {
113: request.setAttribute("_ERROR_MESSAGE_",
114: "<li>You are not authorized to use this function.");
115: return "error";
116: }
117: if (delegatorName == null) {
118: request.setAttribute("_ERROR_MESSAGE_",
119: "<li>Required parameter 'delegator' not passed.");
120: return "error";
121: }
122:
123: GenericDelegator delegator = GenericDelegator
124: .getGenericDelegator(delegatorName);
125:
126: if (delegator == null) {
127: request.setAttribute("_ERROR_MESSAGE_",
128: "<li>No delegator defined by that name.");
129: return "error";
130: }
131:
132: // now change the dispatcher to use this delegator
133: LocalDispatcher dispatcher = (LocalDispatcher) request
134: .getAttribute("dispatcher");
135: DispatchContext dctx = dispatcher.getDispatchContext();
136: String dispatcherName = dispatcher.getName();
137:
138: if (dispatcherName == null) {
139: request.setAttribute("_ERROR_MESSAGE_",
140: "<li>Dispatcher name is null.");
141: return "error";
142: }
143: if (dctx == null) {
144: request.setAttribute("_ERROR_MESSAGE_",
145: "<li>Dispatch context is null.");
146: return "error";
147: }
148:
149: ServiceDispatcher sd = ServiceDispatcher.getInstance(
150: dispatcherName, delegator);
151:
152: if (sd == null)
153: dispatcher = new WebAppDispatcher(dctx, delegator);
154: else
155: dispatcher = sd.getLocalContext(dispatcherName)
156: .getDispatcher();
157:
158: request.getSession().setAttribute("delegator", delegator);
159: request.getSession().setAttribute("dispatcher", dispatcher);
160:
161: return "success";
162: }
163:
164: /**
165: * Change dispatcher event. Changes the dispatch for the current session
166: * @param request HttpServletRequest
167: * @param response HttpServletResponse
168: * @return Response code string
169: */
170: public static String changeDispatcher(HttpServletRequest request,
171: HttpServletResponse response) {
172: String dispatcherName = request.getParameter("dispatcher");
173: Security security = (Security) request.getAttribute("security");
174:
175: if (!security.hasPermission("ENTITY_MAINT", request
176: .getSession())) {
177: request.setAttribute("_ERROR_MESSAGE_",
178: "<li>You are not authorized to use this function.");
179: return "error";
180: }
181: if (dispatcherName == null) {
182: request.setAttribute("_ERROR_MESSAGE_",
183: "<li>Required parameter 'dispatcher' not passed.");
184: return "error";
185: }
186:
187: GenericDelegator delegator = (GenericDelegator) request
188: .getAttribute("delegator");
189: ServiceDispatcher sd = ServiceDispatcher.getInstance(
190: dispatcherName, delegator);
191:
192: if (sd == null) {
193: request
194: .setAttribute("_ERROR_MESSAGE_",
195: "<li>No dispatcher with that name has been registered.");
196: return "error";
197: }
198: LocalDispatcher dispatcher = sd.getLocalContext(dispatcherName)
199: .getDispatcher();
200:
201: request.getSession().setAttribute("dispatcher", dispatcher);
202: return "success";
203: }
204:
205: /**
206: * Schedule a service for a specific time or recurrence
207: * Request Parameters which are used for this service:
208: *
209: * SERVICE_NAME - Name of the service to invoke
210: * SERVICE_TIME - First time the service will occur
211: * SERVICE_FREQUENCY - The type of recurrence (SECONDLY,MINUTELY,DAILY,etc)
212: * SERVICE_INTERVAL - The interval of the frequency (every 5 minutes, etc)
213: *
214: * @param request HttpServletRequest
215: * @param response HttpServletResponse
216: * @return Response code string
217: */
218: public static String scheduleService(HttpServletRequest request,
219: HttpServletResponse response) {
220: Security security = (Security) request.getAttribute("security");
221: LocalDispatcher dispatcher = (LocalDispatcher) request
222: .getAttribute("dispatcher");
223: GenericDelegator delegator = (GenericDelegator) request
224: .getAttribute("delegator");
225:
226: Map params = UtilHttp.getParameterMap(request);
227: // get the schedule parameters
228: String serviceName = (String) params.remove("SERVICE_NAME");
229: String poolName = (String) params.remove("POOL_NAME");
230: String serviceTime = (String) params.remove("SERVICE_TIME");
231: String serviceEndTime = (String) params
232: .remove("SERVICE_END_TIME");
233: String serviceFreq = (String) params
234: .remove("SERVICE_FREQUENCY");
235: String serviceIntr = (String) params.remove("SERVICE_INTERVAL");
236: String serviceCnt = (String) params.remove("SERVICE_COUNT");
237:
238: // the frequency map
239: Map freqMap = new HashMap();
240:
241: freqMap.put("SECONDLY", new Integer(1));
242: freqMap.put("MINUTELY", new Integer(2));
243: freqMap.put("HOURLY", new Integer(3));
244: freqMap.put("DAILY", new Integer(4));
245: freqMap.put("WEEKLY", new Integer(5));
246: freqMap.put("MONTHLY", new Integer(6));
247: freqMap.put("YEARLY", new Integer(7));
248:
249: // some defaults
250: long startTime = (new Date()).getTime();
251: long endTime = 0;
252: int count = 1;
253: int interval = 1;
254: int frequency = RecurrenceRule.DAILY;
255:
256: StringBuffer errorBuf = new StringBuffer();
257:
258: // make sure we passed a service
259: if (serviceName == null) {
260: request
261: .setAttribute(
262: "_ERROR_MESSAGE_",
263: "<li>You must specify a 'SERVICE_NAME' (other parameters include: SERVICE_TIME, SERVICE_FREQUENCY, SERVICE_INTERVAL, SERVICE_COUNT).");
264: return "error";
265: }
266:
267: Timestamp ts = null;
268:
269: GenericValue userLogin = (GenericValue) request.getSession()
270: .getAttribute("userLogin");
271: Locale locale = UtilHttp.getLocale(request);
272:
273: // lookup the service definition to see if this service is externally available, if not require the SERVICE_INVOKE_ANY permission
274: ModelService modelService = null;
275: try {
276: modelService = dispatcher.getDispatchContext()
277: .getModelService(serviceName);
278: } catch (GenericServiceException e) {
279: Debug.logError(e,
280: "Error looking up ModelService for serviceName ["
281: + serviceName + "]", module);
282: request.setAttribute("_ERROR_MESSAGE_",
283: "<li>Error looking up ModelService for serviceName ["
284: + serviceName + "]: " + e.toString());
285: return "error";
286: }
287: if (modelService == null) {
288: request.setAttribute("_ERROR_MESSAGE_",
289: "<li>Could not find a service with the serviceName ["
290: + serviceName + "]");
291: return "error";
292: }
293:
294: // make the context valid; using the makeValid method from ModelService
295: Map serviceContext = new HashMap();
296: Iterator ci = modelService.getInParamNames().iterator();
297: while (ci.hasNext()) {
298: String name = (String) ci.next();
299:
300: // don't include userLogin, that's taken care of below
301: if ("userLogin".equals(name))
302: continue;
303: // don't include locale, that is also taken care of below
304: if ("locale".equals(name))
305: continue;
306:
307: Object value = request.getParameter(name);
308:
309: // if the parameter wasn't passed and no other value found, don't pass on the null
310: if (value == null) {
311: value = request.getAttribute(name);
312: }
313: if (value == null) {
314: value = request.getSession().getAttribute(name);
315: }
316: if (value == null) {
317: // still null, give up for this one
318: continue;
319: }
320:
321: if (value instanceof String
322: && ((String) value).length() == 0) {
323: // interpreting empty fields as null values for each in back end handling...
324: value = null;
325: }
326:
327: // set even if null so that values will get nulled in the db later on
328: serviceContext.put(name, value);
329: }
330: serviceContext = modelService.makeValid(serviceContext,
331: ModelService.IN_PARAM);
332:
333: if (userLogin != null) {
334: serviceContext.put("userLogin", userLogin);
335: }
336:
337: if (locale != null) {
338: serviceContext.put("locale", locale);
339: }
340:
341: if (!modelService.export
342: && !security.hasPermission("SERVICE_INVOKE_ANY",
343: request.getSession())) {
344: request
345: .setAttribute(
346: "_ERROR_MESSAGE_",
347: "<li>You are not authorized to call this non-exported service, you must be logged in and have the SERVICE_INVOKE_ANY permission.");
348: return "error";
349: }
350:
351: // some conversions
352: if (serviceTime != null && serviceTime.length() > 0) {
353: try {
354: Timestamp ts1 = Timestamp.valueOf(serviceTime);
355: startTime = ts1.getTime();
356: } catch (IllegalArgumentException e) {
357: try {
358: startTime = Long.parseLong(serviceTime);
359: } catch (NumberFormatException nfe) {
360: errorBuf
361: .append("<li>Invalid format for SERVICE_TIME");
362: }
363: }
364: if (startTime < (new Date()).getTime()) {
365: errorBuf.append("<li>SERVICE_TIME has already passed");
366: }
367: }
368: if (serviceEndTime != null && serviceEndTime.length() > 0) {
369: try {
370: Timestamp ts1 = Timestamp.valueOf(serviceEndTime);
371: endTime = ts1.getTime();
372: } catch (IllegalArgumentException e) {
373: try {
374: endTime = Long.parseLong(serviceTime);
375: } catch (NumberFormatException nfe) {
376: errorBuf
377: .append("<li>Invalid format for SERVICE_TIME");
378: }
379: }
380: if (endTime < (new Date()).getTime()) {
381: errorBuf.append("<li>SERVICE_TIME has already passed");
382: }
383: }
384: if (serviceIntr != null && serviceIntr.length() > 0) {
385: try {
386: interval = Integer.parseInt(serviceIntr);
387: } catch (NumberFormatException nfe) {
388: errorBuf
389: .append("<li>Invalid format for SERVICE_INTERVAL");
390: }
391: }
392: if (serviceCnt != null && serviceCnt.length() > 0) {
393: try {
394: count = Integer.parseInt(serviceCnt);
395: } catch (NumberFormatException nfe) {
396: errorBuf.append("<li>Invalid format for SERVICE_COUNT");
397: }
398: }
399: if (serviceFreq != null && serviceFreq.length() > 0) {
400: int parsedValue = 0;
401:
402: try {
403: parsedValue = Integer.parseInt(serviceFreq);
404: if (parsedValue > 0 && parsedValue < 8)
405: frequency = parsedValue;
406: } catch (NumberFormatException nfe) {
407: parsedValue = 0;
408: }
409: if (parsedValue == 0) {
410: if (!freqMap.containsKey(serviceFreq.toUpperCase())) {
411: errorBuf
412: .append("<li>Invalid format for SERIVCE_FREQUENCY");
413: } else {
414: frequency = ((Integer) freqMap.get(serviceFreq
415: .toUpperCase())).intValue();
416: }
417: }
418: }
419:
420: // return the errors
421: if (errorBuf.length() > 0) {
422: request
423: .setAttribute("_ERROR_MESSAGE_", errorBuf
424: .toString());
425: return "error";
426: }
427:
428: // schedule service
429: try {
430: dispatcher.schedule(poolName, serviceName, serviceContext,
431: startTime, frequency, interval, count, endTime);
432: } catch (GenericServiceException e) {
433: request.setAttribute("_ERROR_MESSAGE_",
434: "<li>Service dispatcher threw an exception: "
435: + e.getMessage());
436: return "error";
437: }
438:
439: request.setAttribute("_EVENT_MESSAGE_",
440: "<li>Service has been scheduled");
441: return "success";
442: }
443:
444: public static ServiceEventHandler seh = new ServiceEventHandler();
445:
446: /**
447: * Run a service.
448: * Request Parameters which are used for this event:
449: * SERVICE_NAME - Name of the service to invoke
450: *
451: * @param request HttpServletRequest
452: * @param response HttpServletResponse
453: * @return Response code string
454: */
455: public static String runService(HttpServletRequest request,
456: HttpServletResponse response) {
457: // get the mode and service name
458: String serviceName = request.getParameter("serviceName");
459: String mode = request.getParameter("mode");
460:
461: if (UtilValidate.isEmpty(serviceName)) {
462: request
463: .setAttribute(
464: "_ERROR_MESSAGE_",
465: "<li>You must specify a 'serviceName', and optionally a 'mode' (sync or async, defaults to sync).");
466: return "error";
467: }
468:
469: if (UtilValidate.isEmpty(mode)) {
470: mode = "sync";
471: }
472:
473: // now do a security check
474:
475: Security security = (Security) request.getAttribute("security");
476: LocalDispatcher dispatcher = (LocalDispatcher) request
477: .getAttribute("dispatcher");
478:
479: //lookup the service definition to see if this service is externally available, if not require the SERVICE_INVOKE_ANY permission
480: ModelService modelService = null;
481: try {
482: modelService = dispatcher.getDispatchContext()
483: .getModelService(serviceName);
484: } catch (GenericServiceException e) {
485: Debug.logError(e,
486: "Error looking up ModelService for serviceName ["
487: + serviceName + "]", module);
488: request.setAttribute("_ERROR_MESSAGE_",
489: "<li>Error looking up ModelService for serviceName ["
490: + serviceName + "]: " + e.toString());
491: return "error";
492: }
493: if (modelService == null) {
494: request.setAttribute("_ERROR_MESSAGE_",
495: "<li>Could not find a service with the serviceName ["
496: + serviceName + "]");
497: return "error";
498: }
499:
500: if (!modelService.export
501: && !security.hasPermission("SERVICE_INVOKE_ANY",
502: request.getSession())) {
503: request
504: .setAttribute(
505: "_ERROR_MESSAGE_",
506: "<li>You are not authorized to call this non-exported service, you must be logged in and have the SERVICE_INVOKE_ANY permission.");
507: return "error";
508: }
509:
510: Debug.logInfo("Running service named [" + serviceName
511: + "] from event with mode [" + mode + "]", module);
512:
513: // call the service via the ServiceEventHandler which
514: // adapts an event to a service.
515: try {
516: return seh.invoke(mode, serviceName, request, response);
517: } catch (EventHandlerException e) {
518: request.setAttribute("_ERROR_MESSAGE_",
519: "<li>ServiceEventHandler threw an exception: "
520: + e.getMessage());
521: return "error";
522: }
523: }
524:
525: public static String streamFile(HttpServletRequest request,
526: HttpServletResponse response) {
527: RequestHandler rh = (RequestHandler) request
528: .getAttribute("_REQUEST_HANDLER_");
529: String filePath = RequestHandler.getNextPageUri(request
530: .getPathInfo());
531: String fileName = filePath
532: .substring(filePath.lastIndexOf("/") + 1);
533:
534: // load the file
535: File file = new File(filePath);
536: if (file.exists()) {
537: Long longLen = new Long(file.length());
538: int length = longLen.intValue();
539: try {
540: FileInputStream fis = new FileInputStream(file);
541: UtilHttp.streamContentToBrowser(response, fis, length,
542: null);
543: fis.close();
544: } catch (FileNotFoundException e) {
545: Debug.logError(e, module);
546: return "error";
547: } catch (IOException e) {
548: Debug.logError(e, module);
549: return "error";
550: }
551: }
552: return null;
553: }
554: }
|