KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > webtools > GenericWebEvent


1 /*
2  * $Id: GenericWebEvent.java 5462 2005-08-05 18:35:48Z 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 package org.ofbiz.webtools;
25
26 import java.lang.reflect.Field JavaDoc;
27 import java.lang.reflect.Method JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.Locale JavaDoc;
30 import java.util.Map JavaDoc;
31
32 import javax.servlet.http.HttpServletRequest JavaDoc;
33 import javax.servlet.http.HttpServletResponse JavaDoc;
34
35 import org.ofbiz.base.util.Debug;
36 import org.ofbiz.base.util.UtilHttp;
37 import org.ofbiz.base.util.UtilMisc;
38 import org.ofbiz.base.util.UtilProperties;
39 import org.ofbiz.entity.GenericDelegator;
40 import org.ofbiz.entity.GenericEntityException;
41 import org.ofbiz.entity.GenericValue;
42 import org.ofbiz.entity.model.ModelEntity;
43 import org.ofbiz.entity.model.ModelField;
44 import org.ofbiz.entity.model.ModelFieldType;
45 import org.ofbiz.entity.model.ModelReader;
46 import org.ofbiz.security.Security;
47
48 /**
49  * Web Event for doing updates on Generic Entities
50  *
51  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
52  * @version $Rev: 5462 $
53  * @since 2.0
54  */

55 public class GenericWebEvent {
56     
57     public static final String JavaDoc module = GenericWebEvent.class.getName();
58     public static final String JavaDoc err_resource = "WebtoolsErrorUiLabels";
59
60     /** An HTTP WebEvent handler that updates a Generic entity
61      *
62      * @param request The HTTP request object for the current JSP or Servlet request.
63      * @param response The HTTP response object for the current JSP or Servlet request.
64      * @return Returns a String specifying the outcome state of the event. This is used to decide which event
65      * to run next or which view to display. If null no event is run nor view displayed, allowing the event to
66      * call a forward on a RequestDispatcher.
67      */

68     public static String JavaDoc updateGeneric(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
69         String JavaDoc errMsg = "";
70
71         String JavaDoc entityName = request.getParameter("entityName");
72         Locale JavaDoc locale = UtilHttp.getLocale(request);
73
74         if (entityName == null || entityName.length() <= 0) {
75             errMsg = UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.entity_name_not_specified", locale) + ".";
76             request.setAttribute("_ERROR_MESSAGE_", errMsg);
77             Debug.logWarning("[GenericWebEvent.updateGeneric] The entityName was not specified, but is required.", module);
78             return "error";
79         }
80
81         Security security = (Security) request.getAttribute("security");
82         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
83
84         if (security == null) {
85             errMsg = UtilProperties.getMessage(GenericWebEvent.err_resource,"genericWebEvent.security_object_not_found", locale) + ".";
86             request.setAttribute("_ERROR_MESSAGE_", errMsg);
87             Debug.logWarning("[updateGeneric] The security object was not found in the request, please check the control servlet init.", module);
88             return "error";
89         }
90         if (delegator == null) {
91             errMsg = UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.delegator_object_not_found", locale) + ".";
92             request.setAttribute("_ERROR_MESSAGE_", errMsg);
93             Debug.logWarning("[updateGeneric] The delegator object was not found in the request, please check the control servlet init.", module);
94             return "error";
95         }
96
97         ModelReader reader = delegator.getModelReader();
98         ModelEntity entity = null;
99
100         try {
101             entity = reader.getModelEntity(entityName);
102         } catch (GenericEntityException e) {
103             Debug.logError(e, module);
104         }
105
106         String JavaDoc updateMode = request.getParameter("UPDATE_MODE");
107
108         if (updateMode == null || updateMode.length() <= 0) {
109             errMsg = UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.update_mode_not_specified", locale) + ".";
110             request.setAttribute("_ERROR_MESSAGE_", errMsg);
111             Debug.logWarning("[updateGeneric] Update Mode was not specified, but is required; entityName: " + entityName, module);
112             return "error";
113         }
114
115         // check permissions before moving on...
116
if (!security.hasEntityPermission("ENTITY_DATA", "_" + updateMode, request.getSession()) &&
117             !security.hasEntityPermission(entity.getPlainTableName(), "_" + updateMode, request.getSession())) {
118                 Map JavaDoc messageMap = UtilMisc.toMap("updateMode", updateMode, "entityName", entity.getEntityName(), "entityPlainTableName", entity.getPlainTableName());
119                 errMsg = UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.not_sufficient_permissions_01", messageMap, locale);
120                 errMsg += UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.not_sufficient_permissions_02", messageMap, locale) + ".";
121
122                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
123             // not really successful, but error return through ERROR_MESSAGE, so quietly fail
124
return "error";
125         }
126
127         GenericValue findByEntity = delegator.makeValue(entityName, null);
128
129         // get the primary key parameters...
130
Iterator JavaDoc pksIter = entity.getPksIterator();
131         while (pksIter.hasNext()) {
132             ModelField field = (ModelField) pksIter.next();
133
134             ModelFieldType type = null;
135             try {
136                 type = delegator.getEntityFieldType(entity, field.getType());
137             } catch (GenericEntityException e) {
138                 Debug.logWarning(e, module);
139                 Map JavaDoc messageMap = UtilMisc.toMap("fieldType", field.getType());
140                 errMsg += UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.fatal_error_param", messageMap, locale) + ".";
141             }
142
143             String JavaDoc fval = request.getParameter(field.getName());
144             if (fval != null && fval.length() > 0) {
145                 try {
146                     findByEntity.setString(field.getName(), fval);
147                 } catch (Exception JavaDoc e) {
148                     Map JavaDoc messageMap = UtilMisc.toMap("fval", fval);
149                     errMsg = errMsg + "<li>" + field.getColName() + UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.conversion_failed", messageMap, locale) + type.getJavaType() + ".";
150                     Debug.logWarning("[updateGeneric] " + field.getColName() + " conversion failed: \"" + fval + "\" is not a valid " + type.getJavaType() + "; entityName: " + entityName, module);
151                 }
152             }
153         }
154
155         // if this is a delete, do that before getting all of the non-pk parameters and validating them
156
if (updateMode.equals("DELETE")) {
157             // Remove associated/dependent entries from other tables here
158
// Delete actual main entity last, just in case database is set up to do a cascading delete, caches won't get cleared
159
try {
160                 delegator.removeByPrimaryKey(findByEntity.getPrimaryKey());
161             } catch (GenericEntityException e) {
162                 Debug.logWarning(e, module);
163                 errMsg = UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.delete_failed", locale);
164                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
165                 return "error";
166             }
167
168             return "success";
169         }
170
171         // get the non-primary key parameters
172
Iterator JavaDoc nopksIter = entity.getNopksIterator();
173         while (nopksIter.hasNext()) {
174             ModelField field = (ModelField) nopksIter.next();
175
176             ModelFieldType type = null;
177             try {
178                 type = delegator.getEntityFieldType(entity, field.getType());
179             } catch (GenericEntityException e) {
180                 Debug.logWarning(e, module);
181                 Map JavaDoc messageMap = UtilMisc.toMap("fieldType", field.getType());
182                 errMsg += UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.fatal_error_param", messageMap, locale) + ".";
183             }
184             
185             String JavaDoc fval = request.getParameter(field.getName());
186             if (fval != null && fval.length() > 0) {
187                 try {
188                     findByEntity.setString(field.getName(), fval);
189                 } catch (Exception JavaDoc e) {
190                     Map JavaDoc messageMap = UtilMisc.toMap("fval", fval);
191                     errMsg = errMsg + field.getColName() + UtilProperties.getMessage(GenericWebEvent.err_resource,
192                             "genericWebEvent.conversion_failed", messageMap, locale) + type.getJavaType() + ".";
193                     Debug.logWarning("[updateGeneric] " + field.getColName() + " conversion failed: \"" + fval + "\" is not a valid " + type.getJavaType() + "; entityName: " + entityName, module);
194                 }
195             }
196         }
197
198         // if the updateMode is CREATE, check to see if an entity with the specified primary key already exists
199
if (updateMode.equals("CREATE")) {
200             GenericValue tempEntity = null;
201
202             try {
203                 tempEntity = delegator.findByPrimaryKey(findByEntity.getPrimaryKey());
204             } catch (GenericEntityException e) {
205                 Debug.logWarning(e, module);
206                 errMsg = UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.create_failed_by_check", locale);
207
208                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
209                 return "error";
210             }
211             if (tempEntity != null) {
212                 Map JavaDoc messageMap = UtilMisc.toMap("primaryKey", findByEntity.getPrimaryKey().toString());
213                 errMsg = errMsg + entity.getEntityName() + UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.already_exists_pk", messageMap, locale)+ ".";
214                 Debug.logWarning("[updateGeneric] " + entity.getEntityName() + " already exists with primary key: " + findByEntity.getPrimaryKey().toString() + "; please change.", module);
215             }
216         }
217
218         // Validate parameters...
219
Iterator JavaDoc fieldIter = entity.getFieldsIterator();
220         while (fieldIter.hasNext()) {
221             ModelField field = (ModelField) fieldIter.next();
222
223             for (int j = 0; j < field.getValidatorsSize(); j++) {
224                 String JavaDoc curValidate = field.getValidator(j);
225                 Class JavaDoc[] paramTypes = new Class JavaDoc[] {String JavaDoc.class};
226                 Object JavaDoc[] params = new Object JavaDoc[] {findByEntity.get(field.getName()).toString()};
227
228                 String JavaDoc className = "org.ofbiz.base.util.UtilValidate";
229                 String JavaDoc methodName = curValidate;
230
231                 if (curValidate.indexOf('.') > 0) {
232                     className = curValidate.substring(0, curValidate.lastIndexOf('.'));
233                     methodName = curValidate.substring(curValidate.lastIndexOf('.') + 1);
234                 }
235                 Class JavaDoc valClass;
236
237                 try {
238                     ClassLoader JavaDoc loader = Thread.currentThread().getContextClassLoader();
239                     valClass = loader.loadClass(className);
240                 } catch (ClassNotFoundException JavaDoc cnfe) {
241                     Debug.logError("[updateGeneric] Could not find validation class: " + className + "; ignoring.", module);
242                     continue;
243                 }
244                 Method JavaDoc valMethod;
245
246                 try {
247                     valMethod = valClass.getMethod(methodName, paramTypes);
248                 } catch (NoSuchMethodException JavaDoc cnfe) {
249                     Debug.logError("[updateGeneric] Could not find validation method: " + methodName + " of class " + className + "; ignoring.", module);
250                     continue;
251                 }
252
253                 Boolean JavaDoc resultBool;
254
255                 try {
256                     resultBool = (Boolean JavaDoc) valMethod.invoke(null, params);
257                 } catch (Exception JavaDoc e) {
258                     Debug.logError("[updateGeneric] Could not access validation method: " + methodName + " of class " + className + "; returning true.", module);
259                     resultBool = Boolean.TRUE;
260                 }
261
262                 if (!resultBool.booleanValue()) {
263                     Field JavaDoc msgField;
264                     String JavaDoc message;
265
266                     try {
267                         msgField = valClass.getField(curValidate + "Msg");
268                         message = (String JavaDoc) msgField.get(null);
269                     } catch (Exception JavaDoc e) {
270                         Debug.logError("[updateGeneric] Could not find validation message field: " + curValidate + "Msg of class " + className + "; returning generic validation failure message.", module);
271                         message = UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.validation_failed", locale) + ".";
272                     }
273                     errMsg = errMsg + field.getColName() + " " + curValidate + " " + UtilProperties.getMessage(GenericWebEvent.err_resource,
274                             "genericWebEvent.failed", locale) + ": " + message;
275
276                     Debug.logWarning("[updateGeneric] " + field.getColName() + " " + curValidate + " failed: " + message, module);
277                 }
278             }
279         }
280
281         if (errMsg.length() > 0) {
282             errMsg = UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.following_error_occurred", locale) + errMsg;
283             request.setAttribute("_ERROR_MESSAGE_", errMsg);
284             return "error";
285         }
286
287         if (updateMode.equals("CREATE")) {
288             GenericValue value;
289
290             try {
291                 value = delegator.create(findByEntity.getEntityName(), findByEntity.getAllFields());
292             } catch (GenericEntityException e) {
293                 Debug.logWarning(e, module);
294                 value = null;
295             }
296             if (value == null) {
297                 Map JavaDoc messageMap = UtilMisc.toMap("entityName", entity.getEntityName());
298                 errMsg = UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.creation_param_failed", messageMap, locale)+ ": " + findByEntity.toString();
299                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
300                 return "error";
301             }
302         } else if (updateMode.equals("UPDATE")) {
303             GenericValue value = delegator.makeValue(findByEntity.getEntityName(), findByEntity.getAllFields());
304
305             try {
306                 value.store();
307             } catch (GenericEntityException e) {
308                 Debug.logWarning(e, module);
309                 Map JavaDoc messageMap = UtilMisc.toMap("entityName", entity.getEntityName());
310                 errMsg = UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.update_of_param_failed", messageMap, locale)+ ": " + value.toString();
311
312                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
313                 return "error";
314             }
315         } else {
316             Map JavaDoc messageMap = UtilMisc.toMap("updateMode", updateMode);
317             errMsg = UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.update_of_param_failed", messageMap, locale)+ ".";
318                                     
319             request.setAttribute("_ERROR_MESSAGE_", errMsg);
320             Debug.logWarning("updateGeneric: Update Mode specified (" + updateMode + ") was not valid for entity: " + findByEntity.toString(), module);
321             return "error";
322         }
323
324         return "success";
325     }
326 }
327
Popular Tags