001: /*
002: * $Id: ServiceUtil.java,v 1.10 2003/12/06 23:10:14 ajzeneski Exp $
003: *
004: * Copyright (c) 2001, 2002 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.service;
026:
027: import java.sql.Timestamp;
028: import java.util.*;
029:
030: import javax.servlet.http.HttpServletRequest;
031:
032: import org.ofbiz.base.util.Debug;
033: import org.ofbiz.base.util.UtilDateTime;
034: import org.ofbiz.base.util.UtilMisc;
035: import org.ofbiz.base.util.UtilValidate;
036: import org.ofbiz.entity.GenericDelegator;
037: import org.ofbiz.entity.GenericEntityException;
038: import org.ofbiz.entity.GenericValue;
039: import org.ofbiz.entity.condition.EntityExpr;
040: import org.ofbiz.entity.condition.EntityOperator;
041: import org.ofbiz.entity.condition.EntityCondition;
042: import org.ofbiz.entity.condition.EntityConditionList;
043: import org.ofbiz.security.Security;
044: import org.ofbiz.service.config.ServiceConfigUtil;
045:
046: /**
047: * Generic Service Utility Class
048: *
049: * @author <a href="mailto:jaz@ofbiz.org">Andy Zeneski</a>
050: * @version $Revision: 1.10 $
051: * @since 2.0
052: */
053: public class ServiceUtil {
054:
055: public static final String module = ServiceUtil.class.getName();
056:
057: /** A little short-cut method to check to see if a service returned an error */
058: public static boolean isError(Map results) {
059: return ModelService.RESPOND_ERROR.equals(results
060: .get(ModelService.RESPONSE_MESSAGE));
061: }
062:
063: /** A small routine used all over to improve code efficiency, make a result map with the message and the error response code */
064: public static Map returnError(String errorMessage) {
065: return returnError(errorMessage, null, null, null);
066: }
067:
068: /** A small routine used all over to improve code efficiency, make a result map with the message and the error response code */
069: public static Map returnError(List errorMessageList) {
070: return returnError(null, errorMessageList, null, null);
071: }
072:
073: /** 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 */
074: public static Map returnError(String errorMessage,
075: List errorMessageList, Map errorMessageMap, Map nestedResult) {
076: Map result = new HashMap();
077:
078: result.put(ModelService.RESPONSE_MESSAGE,
079: ModelService.RESPOND_ERROR);
080: if (errorMessage != null) {
081: result.put(ModelService.ERROR_MESSAGE, errorMessage);
082: }
083:
084: List errorList = new LinkedList();
085: if (errorMessageList != null) {
086: errorList.addAll(errorMessageList);
087: }
088:
089: Map errorMap = new HashMap();
090: if (errorMessageMap != null) {
091: errorMap.putAll(errorMessageMap);
092: }
093:
094: if (nestedResult != null) {
095: if (nestedResult.get(ModelService.ERROR_MESSAGE) != null) {
096: errorList.add(nestedResult
097: .get(ModelService.ERROR_MESSAGE));
098: }
099: if (nestedResult.get(ModelService.ERROR_MESSAGE_LIST) != null) {
100: errorList.addAll((List) nestedResult
101: .get(ModelService.ERROR_MESSAGE_LIST));
102: }
103: if (nestedResult.get(ModelService.ERROR_MESSAGE_MAP) != null) {
104: errorMap.putAll((Map) nestedResult
105: .get(ModelService.ERROR_MESSAGE_MAP));
106: }
107: }
108:
109: if (errorList.size() > 0) {
110: result.put(ModelService.ERROR_MESSAGE_LIST, errorList);
111: }
112: if (errorMap.size() > 0) {
113: result.put(ModelService.ERROR_MESSAGE_MAP, errorMap);
114: }
115: return result;
116: }
117:
118: /** A small routine used all over to improve code efficiency, make a result map with the message and the success response code */
119: public static Map returnSuccess(String successMessage) {
120: return returnMessage(ModelService.RESPOND_SUCCESS,
121: successMessage);
122: }
123:
124: /** A small routine used all over to improve code efficiency, make a result map with the message and the success response code */
125: public static Map returnSuccess() {
126: return returnMessage(ModelService.RESPOND_SUCCESS, null);
127: }
128:
129: /** A small routine to make a result map with the message and the response code
130: * NOTE: This brings out some bad points to our message convention: we should be using a single message or message list
131: * and what type of message that is should be determined by the RESPONSE_MESSAGE (and there's another annoyance, it should be RESPONSE_CODE)
132: */
133: public static Map returnMessage(String code, String message) {
134: Map result = new HashMap();
135:
136: if (code != null)
137: result.put(ModelService.RESPONSE_MESSAGE, code);
138: if (message != null)
139: result.put(ModelService.SUCCESS_MESSAGE, message);
140: return result;
141: }
142:
143: /** A small routine used all over to improve code efficiency, get the partyId and does a security check
144: *<b>security check</b>: userLogin partyId must equal partyId, or must have [secEntity][secOperation] permission
145: */
146: public static String getPartyIdCheckSecurity(
147: GenericValue userLogin, Security security, Map context,
148: Map result, String secEntity, String secOperation) {
149: String partyId = (String) context.get("partyId");
150:
151: if (partyId == null || partyId.length() == 0) {
152: partyId = userLogin.getString("partyId");
153: }
154:
155: // partyId might be null, so check it
156: if (partyId == null || partyId.length() == 0) {
157: result.put(ModelService.RESPONSE_MESSAGE,
158: ModelService.RESPOND_ERROR);
159: result.put(ModelService.ERROR_MESSAGE, "Party ID missing");
160: return partyId;
161: }
162:
163: // <b>security check</b>: userLogin partyId must equal partyId, or must have PARTYMGR_CREATE permission
164: if (!partyId.equals(userLogin.getString("partyId"))) {
165: if (!security.hasEntityPermission(secEntity, secOperation,
166: userLogin)) {
167: result.put(ModelService.RESPONSE_MESSAGE,
168: ModelService.RESPOND_ERROR);
169: result
170: .put(ModelService.ERROR_MESSAGE,
171: "You do not have permission to perform this operation for this party");
172: return partyId;
173: }
174: }
175: return partyId;
176: }
177:
178: public static void setMessages(HttpServletRequest request,
179: String errorMessage, String eventMessage,
180: String defaultMessage) {
181: if (UtilValidate.isNotEmpty(errorMessage))
182: request.setAttribute("_ERROR_MESSAGE_", errorMessage);
183:
184: if (UtilValidate.isNotEmpty(eventMessage))
185: request.setAttribute("_EVENT_MESSAGE_", eventMessage);
186:
187: if (UtilValidate.isEmpty(errorMessage)
188: && UtilValidate.isEmpty(eventMessage)
189: && UtilValidate.isNotEmpty(defaultMessage))
190: request.setAttribute("_EVENT_MESSAGE_", defaultMessage);
191:
192: }
193:
194: public static void getMessages(HttpServletRequest request,
195: Map result, String defaultMessage, String msgPrefix,
196: String msgSuffix, String errorPrefix, String errorSuffix,
197: String successPrefix, String successSuffix) {
198: String errorMessage = ServiceUtil.makeErrorMessage(result,
199: msgPrefix, msgSuffix, errorPrefix, errorSuffix);
200: String successMessage = ServiceUtil.makeSuccessMessage(result,
201: msgPrefix, msgSuffix, successPrefix, successSuffix);
202: setMessages(request, errorMessage, successMessage,
203: defaultMessage);
204: }
205:
206: public static String getErrorMessage(Map result) {
207: return (String) result.get(ModelService.ERROR_MESSAGE);
208: }
209:
210: public static String makeErrorMessage(Map result, String msgPrefix,
211: String msgSuffix, String errorPrefix, String errorSuffix) {
212: if (result == null) {
213: Debug.logWarning("A null result map was passed", module);
214: return null;
215: }
216: String errorMsg = (String) result
217: .get(ModelService.ERROR_MESSAGE);
218: List errorMsgList = (List) result
219: .get(ModelService.ERROR_MESSAGE_LIST);
220: Map errorMsgMap = (Map) result
221: .get(ModelService.ERROR_MESSAGE_MAP);
222: StringBuffer outMsg = new StringBuffer();
223:
224: if (errorMsg != null) {
225: if (msgPrefix != null)
226: outMsg.append(msgPrefix);
227: outMsg.append(errorMsg);
228: if (msgSuffix != null)
229: outMsg.append(msgSuffix);
230: }
231:
232: outMsg.append(makeMessageList(errorMsgList, msgPrefix,
233: msgSuffix));
234:
235: if (errorMsgMap != null) {
236: Iterator mapIter = errorMsgMap.entrySet().iterator();
237:
238: while (mapIter.hasNext()) {
239: Map.Entry entry = (Map.Entry) mapIter.next();
240:
241: outMsg.append(msgPrefix);
242: outMsg.append(entry.getKey());
243: outMsg.append(": ");
244: outMsg.append(entry.getValue());
245: outMsg.append(msgSuffix);
246: }
247: }
248:
249: if (outMsg.length() > 0) {
250: StringBuffer strBuf = new StringBuffer();
251:
252: if (errorPrefix != null)
253: strBuf.append(errorPrefix);
254: strBuf.append(outMsg.toString());
255: if (errorSuffix != null)
256: strBuf.append(errorSuffix);
257: return strBuf.toString();
258: } else {
259: return null;
260: }
261: }
262:
263: public static String makeSuccessMessage(Map result,
264: String msgPrefix, String msgSuffix, String successPrefix,
265: String successSuffix) {
266: if (result == null) {
267: return "";
268: }
269: String successMsg = (String) result
270: .get(ModelService.SUCCESS_MESSAGE);
271: List successMsgList = (List) result
272: .get(ModelService.SUCCESS_MESSAGE_LIST);
273: StringBuffer outMsg = new StringBuffer();
274:
275: outMsg.append(makeMessageList(successMsgList, msgPrefix,
276: msgSuffix));
277:
278: if (successMsg != null) {
279: if (msgPrefix != null)
280: outMsg.append(msgPrefix);
281: outMsg.append(successMsg);
282: if (msgSuffix != null)
283: outMsg.append(msgSuffix);
284: }
285:
286: if (outMsg.length() > 0) {
287: StringBuffer strBuf = new StringBuffer();
288:
289: if (successPrefix != null)
290: strBuf.append(successPrefix);
291: strBuf.append(outMsg.toString());
292: if (successSuffix != null)
293: strBuf.append(successSuffix);
294: return strBuf.toString();
295: } else {
296: return null;
297: }
298: }
299:
300: public static String makeMessageList(List msgList,
301: String msgPrefix, String msgSuffix) {
302: StringBuffer outMsg = new StringBuffer();
303:
304: if (msgList != null && msgList.size() > 0) {
305: Iterator iter = msgList.iterator();
306:
307: while (iter.hasNext()) {
308: String curMsg = (String) iter.next();
309:
310: if (msgPrefix != null)
311: outMsg.append(msgPrefix);
312: outMsg.append(curMsg);
313: if (msgSuffix != null)
314: outMsg.append(msgSuffix);
315: }
316: }
317: return outMsg.toString();
318: }
319:
320: public static Map purgeOldJobs(DispatchContext dctx, Map context) {
321: String sendPool = ServiceConfigUtil.getSendPool();
322: int daysToKeep = ServiceConfigUtil.getPurgeJobDays();
323: GenericDelegator delegator = dctx.getDelegator();
324:
325: Timestamp now = UtilDateTime.nowTimestamp();
326: Calendar cal = Calendar.getInstance();
327: cal.setTimeInMillis(now.getTime());
328: cal.add(Calendar.DAY_OF_YEAR, daysToKeep * -1);
329: Timestamp purgeTime = new Timestamp(cal.getTimeInMillis());
330:
331: // create the conditions to query
332: EntityCondition pool = new EntityExpr("poolId",
333: EntityOperator.EQUALS, sendPool);
334:
335: List finExp = UtilMisc.toList(new EntityExpr("finishDateTime",
336: EntityOperator.NOT_EQUAL, null));
337: finExp.add(new EntityExpr("finishDateTime",
338: EntityOperator.LESS_THAN, purgeTime));
339:
340: List canExp = UtilMisc.toList(new EntityExpr("cancelDateTime",
341: EntityOperator.NOT_EQUAL, null));
342: canExp.add(new EntityExpr("cancelDateTime",
343: EntityOperator.LESS_THAN, purgeTime));
344:
345: EntityCondition cancelled = new EntityConditionList(canExp,
346: EntityOperator.AND);
347: EntityCondition finished = new EntityConditionList(finExp,
348: EntityOperator.AND);
349:
350: EntityCondition done = new EntityConditionList(UtilMisc.toList(
351: cancelled, finished), EntityOperator.OR);
352: EntityCondition main = new EntityConditionList(UtilMisc.toList(
353: done, pool), EntityOperator.AND);
354:
355: // lookup the jobs
356: List foundJobs = null;
357: try {
358: foundJobs = delegator.findByCondition("JobSandbox", main,
359: null, null);
360: } catch (GenericEntityException e) {
361: Debug.logError(e, "Cannot get jobs to purge");
362: return ServiceUtil.returnError(e.getMessage());
363: }
364:
365: if (foundJobs != null && foundJobs.size() > 0) {
366: Iterator i = foundJobs.iterator();
367: while (i.hasNext()) {
368: GenericValue job = (GenericValue) i.next();
369: try {
370: job.remove();
371: } catch (GenericEntityException e) {
372: Debug.logError(e, "Unable to remove job : " + job,
373: module);
374: }
375: }
376: }
377:
378: return ServiceUtil.returnSuccess();
379: }
380:
381: public static Map cancelJob(DispatchContext dctx, Map context) {
382: GenericDelegator delegator = dctx.getDelegator();
383: Security security = dctx.getSecurity();
384: GenericValue userLogin = (GenericValue) context
385: .get("userLogin");
386: if (!security.hasPermission("SERVICE_INVOKE_ANY", userLogin)) {
387: return ServiceUtil
388: .returnError("You do not have permission to run this service");
389: }
390:
391: String jobName = (String) context.get("jobName");
392: Timestamp runTime = (Timestamp) context.get("runTime");
393: Map fields = UtilMisc.toMap("jobName", jobName, "runTime",
394: runTime);
395:
396: GenericValue job = null;
397: try {
398: job = delegator.findByPrimaryKey("JobSandbox", fields);
399: if (job != null) {
400: job.set("cancelDateTime", UtilDateTime.nowTimestamp());
401: job.store();
402: }
403: } catch (GenericEntityException e) {
404: Debug.logError(e, module);
405: return ServiceUtil.returnError("Unable to cancel job : "
406: + fields);
407: }
408:
409: Timestamp cancelDate = job.getTimestamp("cancelDateTime");
410: if (cancelDate != null) {
411: Map result = ServiceUtil.returnSuccess();
412: result.put("cancelDateTime", cancelDate);
413: return result;
414: } else {
415: return ServiceUtil.returnError("Unable to cancel job : "
416: + job);
417: }
418: }
419: }
|