KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > service > ServiceUtil


1 /*
2  * $Id: ServiceUtil.java 7027 2006-03-20 18:21:03Z jaz $
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.service;
26
27 import java.sql.Timestamp JavaDoc;
28 import java.util.Calendar JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.LinkedList JavaDoc;
31 import java.util.List JavaDoc;
32 import java.util.Locale JavaDoc;
33 import java.util.Map JavaDoc;
34 import javax.servlet.http.HttpServletRequest JavaDoc;
35 import javax.transaction.Transaction JavaDoc;
36
37 import javolution.util.FastMap;
38 import javolution.util.FastList;
39
40 import org.ofbiz.base.util.Debug;
41 import org.ofbiz.base.util.UtilDateTime;
42 import org.ofbiz.base.util.UtilMisc;
43 import org.ofbiz.base.util.UtilProperties;
44 import org.ofbiz.base.util.UtilValidate;
45 import org.ofbiz.entity.GenericDelegator;
46 import org.ofbiz.entity.GenericEntityException;
47 import org.ofbiz.entity.GenericValue;
48 import org.ofbiz.entity.transaction.TransactionUtil;
49 import org.ofbiz.entity.transaction.GenericTransactionException;
50 import org.ofbiz.entity.condition.EntityCondition;
51 import org.ofbiz.entity.condition.EntityConditionList;
52 import org.ofbiz.entity.condition.EntityExpr;
53 import org.ofbiz.entity.condition.EntityOperator;
54 import org.ofbiz.entity.util.EntityFindOptions;
55 import org.ofbiz.entity.util.EntityListIterator;
56 import org.ofbiz.security.Security;
57 import org.ofbiz.service.config.ServiceConfigUtil;
58
59 /**
60  * Generic Service Utility Class
61  *
62  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
63  * @version $Rev: 7027 $
64  * @since 2.0
65  */

66 public class ServiceUtil {
67
68     public static final String JavaDoc module = ServiceUtil.class.getName();
69     public static final String JavaDoc resource = "ServiceErrorUiLabels";
70
71     /** A little short-cut method to check to see if a service returned an error */
72     public static boolean isError(Map JavaDoc results) {
73         if (results == null || results.get(ModelService.RESPONSE_MESSAGE) == null) {
74             return false;
75         }
76         return ModelService.RESPOND_ERROR.equals(results.get(ModelService.RESPONSE_MESSAGE));
77     }
78
79     public static boolean isFailure(Map JavaDoc results) {
80         if (results == null || results.get(ModelService.RESPONSE_MESSAGE) == null) {
81             return false;
82         }
83         return ModelService.RESPOND_FAIL.equals(results.get(ModelService.RESPONSE_MESSAGE));
84     }
85
86     /** A small routine used all over to improve code efficiency, make a result map with the message and the error response code */
87     public static Map JavaDoc returnError(String JavaDoc errorMessage) {
88         return returnProblem(ModelService.RESPOND_ERROR, errorMessage, null, null, null);
89     }
90
91     /** A small routine used all over to improve code efficiency, make a result map with the message and the error response code */
92     public static Map JavaDoc returnError(String JavaDoc errorMessage, List JavaDoc errorMessageList) {
93         return returnProblem(ModelService.RESPOND_ERROR, errorMessage, errorMessageList, null, null);
94     }
95
96     /** A small routine used all over to improve code efficiency, make a result map with the message and the error response code */
97     public static Map JavaDoc returnError(List JavaDoc errorMessageList) {
98         return returnProblem(ModelService.RESPOND_ERROR, null, errorMessageList, null, null);
99     }
100
101     public static Map JavaDoc returnFailure(String JavaDoc errorMessage) {
102         return returnProblem(ModelService.RESPOND_FAIL, errorMessage, null, null, null);
103     }
104
105      public static Map JavaDoc returnFailure(List JavaDoc errorMessageList) {
106         return returnProblem(ModelService.RESPOND_FAIL, null, errorMessageList, null, null);
107     }
108
109     /** A small routine used all over to improve code efficiency, make a result map with the message and the error response code, also forwards any error messages from the nestedResult */
110     public static Map JavaDoc returnError(String JavaDoc errorMessage, List JavaDoc errorMessageList, Map JavaDoc errorMessageMap, Map JavaDoc nestedResult) {
111         return returnProblem(ModelService.RESPOND_ERROR, errorMessage, errorMessageList, errorMessageMap, nestedResult);
112     }
113
114     public static Map JavaDoc returnProblem(String JavaDoc returnType, String JavaDoc errorMessage, List JavaDoc errorMessageList, Map JavaDoc errorMessageMap, Map JavaDoc nestedResult) {
115         Map JavaDoc result = FastMap.newInstance();
116         result.put(ModelService.RESPONSE_MESSAGE, returnType);
117         if (errorMessage != null) {
118             result.put(ModelService.ERROR_MESSAGE, errorMessage);
119         }
120
121         List JavaDoc errorList = new LinkedList JavaDoc();
122         if (errorMessageList != null) {
123             errorList.addAll(errorMessageList);
124         }
125
126         Map JavaDoc errorMap = FastMap.newInstance();
127         if (errorMessageMap != null) {
128             errorMap.putAll(errorMessageMap);
129         }
130
131         if (nestedResult != null) {
132             if (nestedResult.get(ModelService.ERROR_MESSAGE) != null) {
133                 errorList.add(nestedResult.get(ModelService.ERROR_MESSAGE));
134             }
135             if (nestedResult.get(ModelService.ERROR_MESSAGE_LIST) != null) {
136                 errorList.addAll((List JavaDoc) nestedResult.get(ModelService.ERROR_MESSAGE_LIST));
137             }
138             if (nestedResult.get(ModelService.ERROR_MESSAGE_MAP) != null) {
139                 errorMap.putAll((Map JavaDoc) nestedResult.get(ModelService.ERROR_MESSAGE_MAP));
140             }
141         }
142
143         if (errorList.size() > 0) {
144             result.put(ModelService.ERROR_MESSAGE_LIST, errorList);
145         }
146         if (errorMap.size() > 0) {
147             result.put(ModelService.ERROR_MESSAGE_MAP, errorMap);
148         }
149         return result;
150     }
151
152     /** A small routine used all over to improve code efficiency, make a result map with the message and the success response code */
153     public static Map JavaDoc returnSuccess(String JavaDoc successMessage) {
154         return returnMessage(ModelService.RESPOND_SUCCESS, successMessage);
155     }
156
157     /** A small routine used all over to improve code efficiency, make a result map with the message and the success response code */
158     public static Map JavaDoc returnSuccess() {
159         return returnMessage(ModelService.RESPOND_SUCCESS, null);
160     }
161
162     /** A small routine to make a result map with the message and the response code
163      * NOTE: This brings out some bad points to our message convention: we should be using a single message or message list
164      * and what type of message that is should be determined by the RESPONSE_MESSAGE (and there's another annoyance, it should be RESPONSE_CODE)
165      */

166     public static Map JavaDoc returnMessage(String JavaDoc code, String JavaDoc message) {
167         Map JavaDoc result = FastMap.newInstance();
168         if (code != null) result.put(ModelService.RESPONSE_MESSAGE, code);
169         if (message != null) result.put(ModelService.SUCCESS_MESSAGE, message);
170         return result;
171     }
172
173     /** A small routine used all over to improve code efficiency, get the partyId and does a security check
174      *<b>security check</b>: userLogin partyId must equal partyId, or must have [secEntity][secOperation] permission
175      */

176     public static String JavaDoc getPartyIdCheckSecurity(GenericValue userLogin, Security security, Map JavaDoc context, Map JavaDoc result, String JavaDoc secEntity, String JavaDoc secOperation) {
177         String JavaDoc partyId = (String JavaDoc) context.get("partyId");
178         Locale JavaDoc locale = getLocale(context);
179         if (partyId == null || partyId.length() == 0) {
180             partyId = userLogin.getString("partyId");
181         }
182
183         // partyId might be null, so check it
184
if (partyId == null || partyId.length() == 0) {
185             result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR);
186             String JavaDoc errMsg = UtilProperties.getMessage(ServiceUtil.resource, "serviceUtil.party_id_missing", locale) + ".";
187             result.put(ModelService.ERROR_MESSAGE, errMsg);
188             return partyId;
189         }
190
191         // <b>security check</b>: userLogin partyId must equal partyId, or must have PARTYMGR_CREATE permission
192
if (!partyId.equals(userLogin.getString("partyId"))) {
193             if (!security.hasEntityPermission(secEntity, secOperation, userLogin)) {
194                 result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR);
195                 String JavaDoc errMsg = UtilProperties.getMessage(ServiceUtil.resource, "serviceUtil.no_permission_to_operation", locale) + ".";
196                 result.put(ModelService.ERROR_MESSAGE, errMsg);
197                 return partyId;
198             }
199         }
200         return partyId;
201     }
202
203     public static void setMessages(HttpServletRequest JavaDoc request, String JavaDoc errorMessage, String JavaDoc eventMessage, String JavaDoc defaultMessage) {
204         if (UtilValidate.isNotEmpty(errorMessage))
205             request.setAttribute("_ERROR_MESSAGE_", errorMessage);
206
207         if (UtilValidate.isNotEmpty(eventMessage))
208             request.setAttribute("_EVENT_MESSAGE_", eventMessage);
209
210         if (UtilValidate.isEmpty(errorMessage) && UtilValidate.isEmpty(eventMessage) && UtilValidate.isNotEmpty(defaultMessage))
211             request.setAttribute("_EVENT_MESSAGE_", defaultMessage);
212
213     }
214
215     public static void getMessages(HttpServletRequest JavaDoc request, Map JavaDoc result, String JavaDoc defaultMessage) {
216         getMessages(request, result, defaultMessage, null, null, null, null, null, null);
217     }
218
219     public static void getMessages(HttpServletRequest JavaDoc request, Map JavaDoc result, String JavaDoc defaultMessage,
220                                    String JavaDoc msgPrefix, String JavaDoc msgSuffix, String JavaDoc errorPrefix, String JavaDoc errorSuffix, String JavaDoc successPrefix, String JavaDoc successSuffix) {
221         String JavaDoc errorMessage = ServiceUtil.makeErrorMessage(result, msgPrefix, msgSuffix, errorPrefix, errorSuffix);
222         String JavaDoc successMessage = ServiceUtil.makeSuccessMessage(result, msgPrefix, msgSuffix, successPrefix, successSuffix);
223         setMessages(request, errorMessage, successMessage, defaultMessage);
224     }
225
226     public static String JavaDoc getErrorMessage(Map JavaDoc result) {
227         StringBuffer JavaDoc errorMessage = new StringBuffer JavaDoc();
228
229         if (result.get(ModelService.ERROR_MESSAGE) != null) errorMessage.append((String JavaDoc) result.get(ModelService.ERROR_MESSAGE));
230
231         if (result.get(ModelService.ERROR_MESSAGE_LIST) != null) {
232             List JavaDoc errors = (List JavaDoc) result.get(ModelService.ERROR_MESSAGE_LIST);
233             Iterator JavaDoc errorIter = errors.iterator();
234             while (errorIter.hasNext()) {
235                 // NOTE: this MUST use toString and not cast to String because it may be a MessageString object
236
String JavaDoc curMessage = errorIter.next().toString();
237                 if (errorMessage.length() > 0) {
238                     errorMessage.append(", ");
239                 }
240                 errorMessage.append(curMessage);
241             }
242         }
243
244         return errorMessage.toString();
245     }
246
247     public static String JavaDoc makeErrorMessage(Map JavaDoc result, String JavaDoc msgPrefix, String JavaDoc msgSuffix, String JavaDoc errorPrefix, String JavaDoc errorSuffix) {
248         if (result == null) {
249             Debug.logWarning("A null result map was passed", module);
250             return null;
251         }
252         String JavaDoc errorMsg = (String JavaDoc) result.get(ModelService.ERROR_MESSAGE);
253         List JavaDoc errorMsgList = (List JavaDoc) result.get(ModelService.ERROR_MESSAGE_LIST);
254         Map JavaDoc errorMsgMap = (Map JavaDoc) result.get(ModelService.ERROR_MESSAGE_MAP);
255         StringBuffer JavaDoc outMsg = new StringBuffer JavaDoc();
256
257         if (errorMsg != null) {
258             if (msgPrefix != null) outMsg.append(msgPrefix);
259             outMsg.append(errorMsg);
260             if (msgSuffix != null) outMsg.append(msgSuffix);
261         }
262
263         outMsg.append(makeMessageList(errorMsgList, msgPrefix, msgSuffix));
264
265         if (errorMsgMap != null) {
266             Iterator JavaDoc mapIter = errorMsgMap.entrySet().iterator();
267
268             while (mapIter.hasNext()) {
269                 Map.Entry JavaDoc entry = (Map.Entry JavaDoc) mapIter.next();
270
271                 outMsg.append(msgPrefix);
272                 outMsg.append(entry.getKey());
273                 outMsg.append(": ");
274                 outMsg.append(entry.getValue());
275                 outMsg.append(msgSuffix);
276             }
277         }
278
279         if (outMsg.length() > 0) {
280             StringBuffer JavaDoc strBuf = new StringBuffer JavaDoc();
281
282             if (errorPrefix != null) strBuf.append(errorPrefix);
283             strBuf.append(outMsg.toString());
284             if (errorSuffix != null) strBuf.append(errorSuffix);
285             return strBuf.toString();
286         } else {
287             return null;
288         }
289     }
290
291     public static String JavaDoc makeSuccessMessage(Map JavaDoc result, String JavaDoc msgPrefix, String JavaDoc msgSuffix, String JavaDoc successPrefix, String JavaDoc successSuffix) {
292         if (result == null) {
293             return "";
294         }
295         String JavaDoc successMsg = (String JavaDoc) result.get(ModelService.SUCCESS_MESSAGE);
296         List JavaDoc successMsgList = (List JavaDoc) result.get(ModelService.SUCCESS_MESSAGE_LIST);
297         StringBuffer JavaDoc outMsg = new StringBuffer JavaDoc();
298
299         outMsg.append(makeMessageList(successMsgList, msgPrefix, msgSuffix));
300
301         if (successMsg != null) {
302             if (msgPrefix != null) outMsg.append(msgPrefix);
303             outMsg.append(successMsg);
304             if (msgSuffix != null) outMsg.append(msgSuffix);
305         }
306
307         if (outMsg.length() > 0) {
308             StringBuffer JavaDoc strBuf = new StringBuffer JavaDoc();
309             if (successPrefix != null) strBuf.append(successPrefix);
310             strBuf.append(outMsg.toString());
311             if (successSuffix != null) strBuf.append(successSuffix);
312             return strBuf.toString();
313         } else {
314             return null;
315         }
316     }
317
318     public static String JavaDoc makeMessageList(List JavaDoc msgList, String JavaDoc msgPrefix, String JavaDoc msgSuffix) {
319         StringBuffer JavaDoc outMsg = new StringBuffer JavaDoc();
320         if (msgList != null && msgList.size() > 0) {
321             Iterator JavaDoc iter = msgList.iterator();
322             while (iter.hasNext()) {
323                 String JavaDoc curMsg = iter.next().toString();
324                 if (msgPrefix != null) outMsg.append(msgPrefix);
325                 outMsg.append(curMsg);
326                 if (msgSuffix != null) outMsg.append(msgSuffix);
327             }
328         }
329         return outMsg.toString();
330     }
331
332     public static Map JavaDoc purgeOldJobs(DispatchContext dctx, Map JavaDoc context) {
333         String JavaDoc sendPool = ServiceConfigUtil.getSendPool();
334         int daysToKeep = ServiceConfigUtil.getPurgeJobDays();
335         GenericDelegator delegator = dctx.getDelegator();
336
337         Timestamp JavaDoc now = UtilDateTime.nowTimestamp();
338         Calendar JavaDoc cal = Calendar.getInstance();
339         cal.setTimeInMillis(now.getTime());
340         cal.add(Calendar.DAY_OF_YEAR, daysToKeep * -1);
341         Timestamp JavaDoc purgeTime = new Timestamp JavaDoc(cal.getTimeInMillis());
342
343         // create the conditions to query
344
EntityCondition pool = new EntityExpr("poolId", EntityOperator.EQUALS, sendPool);
345
346         List JavaDoc finExp = UtilMisc.toList(new EntityExpr("finishDateTime", EntityOperator.NOT_EQUAL, null));
347         finExp.add(new EntityExpr("finishDateTime", EntityOperator.LESS_THAN, purgeTime));
348
349         List JavaDoc canExp = UtilMisc.toList(new EntityExpr("cancelDateTime", EntityOperator.NOT_EQUAL, null));
350         canExp.add(new EntityExpr("cancelDateTime", EntityOperator.LESS_THAN, purgeTime));
351
352         EntityCondition cancelled = new EntityConditionList(canExp, EntityOperator.AND);
353         EntityCondition finished = new EntityConditionList(finExp, EntityOperator.AND);
354
355         EntityCondition doneCond = new EntityConditionList(UtilMisc.toList(cancelled, finished), EntityOperator.OR);
356         EntityCondition mainCond = new EntityConditionList(UtilMisc.toList(doneCond, pool), EntityOperator.AND);
357
358         // configure the find options
359
EntityFindOptions findOptions = new EntityFindOptions();
360         findOptions.setResultSetType(EntityFindOptions.TYPE_SCROLL_INSENSITIVE);
361         findOptions.setMaxRows(1000);
362
363         // always suspend the current transaction; use the one internally
364
Transaction JavaDoc parent = null;
365         try {
366             if (TransactionUtil.getStatus() != TransactionUtil.STATUS_NO_TRANSACTION) {
367                 parent = TransactionUtil.suspend();
368             }
369
370             // lookup the jobs - looping 1000 at a time to avoid problems with cursors
371
// also, using unique transaction to delete as many as possible even with errors
372
boolean noMoreResults = false;
373             boolean beganTx1 = false;
374             while (!noMoreResults) {
375                 // current list of records
376
List JavaDoc curList = null;
377                 try {
378                     // begin this transaction
379
beganTx1 = TransactionUtil.begin();
380
381                     EntityListIterator foundJobs = delegator.findListIteratorByCondition("JobSandbox", mainCond, null, null, null, findOptions);
382                     curList = foundJobs.getPartialList(1, 1000);
383                     foundJobs.close();
384
385                 } catch (GenericEntityException e) {
386                     Debug.logError(e, "Cannot obtain job data from datasource", module);
387                     try {
388                         TransactionUtil.rollback(beganTx1, e.getMessage(), e);
389                     } catch (GenericTransactionException e1) {
390                         Debug.logWarning(e1, module);
391                     }
392                     return ServiceUtil.returnError(e.getMessage());
393                 } finally {
394                     try {
395                         TransactionUtil.commit(beganTx1);
396                     } catch (GenericTransactionException e) {
397                         Debug.logWarning(e, module);
398                     }
399                 }
400
401                 // remove each from the list in its own transaction
402
if (curList != null && curList.size() > 0) {
403                     // list of runtime data IDs to attempt to delete
404
List JavaDoc runtimeToDelete = FastList.newInstance();
405                     
406                     Iterator JavaDoc curIter = curList.iterator();
407                     while (curIter.hasNext()) {
408                         GenericValue job = (GenericValue) curIter.next();
409                         String JavaDoc jobId = job.getString("jobId");
410                         boolean beganTx2 = false;
411                         try {
412                             beganTx2 = TransactionUtil.begin();
413                             job.remove();
414                         } catch (GenericEntityException e) {
415                             Debug.logInfo("Cannot remove job data for ID: " + jobId, module);
416                             try {
417                                 TransactionUtil.rollback(beganTx2, e.getMessage(), e);
418                             } catch (GenericTransactionException e1) {
419                                 Debug.logWarning(e1, module);
420                             }
421                         } finally {
422                             try {
423                                 TransactionUtil.commit(beganTx2);
424                             } catch (GenericTransactionException e) {
425                                 Debug.logWarning(e, module);
426                             }
427                         }
428                     }
429
430                     // delete the runtime data - in a new transaction for each delete
431
// we do this so that the ones which cannot be deleted to not cause
432
// the entire group to rollback; some may be attached to multiple jobs.
433
if (runtimeToDelete.size() > 0) {
434                         Iterator JavaDoc delIter = runtimeToDelete.iterator();
435                         while (delIter.hasNext()) {
436                             String JavaDoc runtimeId = (String JavaDoc) delIter.next();
437                             boolean beganTx3 = false;
438                             try {
439                                 beganTx3 = TransactionUtil.begin();
440                                 delegator.removeByAnd("RuntimeData", UtilMisc.toMap("runtimeDataId", runtimeId));
441
442                             } catch (GenericEntityException e) {
443                                 Debug.logInfo("Cannot remove runtime data for ID: " + runtimeId, module);
444                                 try {
445                                     TransactionUtil.rollback(beganTx3, e.getMessage(), e);
446                                 } catch (GenericTransactionException e1) {
447                                     Debug.logWarning(e1, module);
448                                 }
449                             } finally {
450                                 try {
451                                     TransactionUtil.commit(beganTx3);
452                                 } catch (GenericTransactionException e) {
453                                     Debug.logWarning(e, module);
454                                 }
455                             }
456                         }
457                     }
458                 } else {
459                     noMoreResults = true;
460                 }
461             }
462         } catch (GenericTransactionException e) {
463             Debug.logError(e, "Unable to suspend transaction; cannot purge jobs!", module);
464             return ServiceUtil.returnError(e.getMessage());
465         } finally {
466             if (parent != null) {
467                 try {
468                     TransactionUtil.resume(parent);
469                 } catch (GenericTransactionException e) {
470                     Debug.logWarning(e, module);
471                 }
472             }
473         }
474
475         return ServiceUtil.returnSuccess();
476     }
477
478     public static Map JavaDoc cancelJob(DispatchContext dctx, Map JavaDoc context) {
479         GenericDelegator delegator = dctx.getDelegator();
480         Security security = dctx.getSecurity();
481         GenericValue userLogin = (GenericValue) context.get("userLogin");
482         Locale JavaDoc locale = getLocale(context);
483
484         if (!security.hasPermission("SERVICE_INVOKE_ANY", userLogin)) {
485             String JavaDoc errMsg = UtilProperties.getMessage(ServiceUtil.resource, "serviceUtil.no_permission_to_run", locale) + ".";
486             return ServiceUtil.returnError(errMsg);
487         }
488
489         String JavaDoc jobId = (String JavaDoc) context.get("jobId");
490         Map JavaDoc fields = UtilMisc.toMap("jobId", jobId);
491
492         GenericValue job = null;
493         try {
494             job = delegator.findByPrimaryKey("JobSandbox", fields);
495             if (job != null) {
496                 job.set("cancelDateTime", UtilDateTime.nowTimestamp());
497                 job.set("statusId", "SERVICE_CANCELLED");
498                 job.store();
499             }
500         } catch (GenericEntityException e) {
501             Debug.logError(e, module);
502             String JavaDoc errMsg = UtilProperties.getMessage(ServiceUtil.resource, "serviceUtil.unable_to_cancel_job", locale) + " : " + fields;
503             return ServiceUtil.returnError(errMsg);
504         }
505
506         Timestamp JavaDoc cancelDate = job.getTimestamp("cancelDateTime");
507         if (cancelDate != null) {
508             Map JavaDoc result = ServiceUtil.returnSuccess();
509             result.put("cancelDateTime", cancelDate);
510             return result;
511         } else {
512             String JavaDoc errMsg = UtilProperties.getMessage(ServiceUtil.resource, "serviceUtil.unable_to_cancel_job", locale) + " : " + job;
513             return ServiceUtil.returnError(errMsg);
514         }
515     }
516
517     public static Map JavaDoc cancelJobRetries(DispatchContext dctx, Map JavaDoc context) {
518         GenericDelegator delegator = dctx.getDelegator();
519         Security security = dctx.getSecurity();
520         GenericValue userLogin = (GenericValue) context.get("userLogin");
521         Locale JavaDoc locale = getLocale(context);
522         if (!security.hasPermission("SERVICE_INVOKE_ANY", userLogin)) {
523             String JavaDoc errMsg = UtilProperties.getMessage(ServiceUtil.resource, "serviceUtil.no_permission_to_run", locale) + ".";
524             return ServiceUtil.returnError(errMsg);
525         }
526
527         String JavaDoc jobId = (String JavaDoc) context.get("jobId");
528         Map JavaDoc fields = UtilMisc.toMap("jobId", jobId);
529
530         GenericValue job = null;
531         try {
532             job = delegator.findByPrimaryKey("JobSandbox", fields);
533             if (job != null) {
534                 job.set("maxRetry", new Long JavaDoc(0));
535                 job.store();
536             }
537         } catch (GenericEntityException e) {
538             Debug.logError(e, module);
539             String JavaDoc errMsg = UtilProperties.getMessage(ServiceUtil.resource, "serviceUtil.unable_to_cancel_job_retries", locale) + " : " + fields;
540             return ServiceUtil.returnError(errMsg);
541         }
542
543         Timestamp JavaDoc cancelDate = job.getTimestamp("cancelDateTime");
544         if (cancelDate != null) {
545             return ServiceUtil.returnSuccess();
546         } else {
547             String JavaDoc errMsg = UtilProperties.getMessage(ServiceUtil.resource, "serviceUtil.unable_to_cancel_job_retries", locale) + " : " + job;
548             return ServiceUtil.returnError(errMsg);
549         }
550     }
551
552     public static GenericValue getUserLogin(DispatchContext dctx, Map JavaDoc context, String JavaDoc runAsUser) {
553         GenericValue userLogin = (GenericValue) context.get("userLogin");
554         GenericDelegator delegator = dctx.getDelegator();
555         if (runAsUser != null) {
556             try {
557                 GenericValue runAs = delegator.findByPrimaryKeyCache("UserLogin", UtilMisc.toMap("userLoginId", runAsUser));
558                 if (runAs != null) {
559                     userLogin = runAs;
560                 }
561             } catch (GenericEntityException e) {
562                 Debug.logError(e, module);
563             }
564         }
565         return userLogin;
566     }
567
568     private static Locale JavaDoc getLocale(Map JavaDoc context) {
569         Locale JavaDoc locale = (Locale JavaDoc) context.get("locale");
570         if (locale == null) {
571             locale = Locale.getDefault();
572         }
573         return locale;
574     }
575 }
576
Popular Tags