KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > dbforms > event > classic > UpdateEvent


1 /*
2  * $Header: /cvsroot/jdbforms/dbforms/src/org/dbforms/event/classic/UpdateEvent.java,v 1.25 2004/10/20 10:51:30 hkollmann Exp $
3  * $Revision: 1.25 $
4  * $Date: 2004/10/20 10:51:30 $
5  *
6  * DbForms - a Rapid Application Development Framework
7  * Copyright (C) 2001 Joachim Peer <joepeer@excite.com>
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22  */

23
24 package org.dbforms.event.classic;
25
26 import org.apache.commons.logging.Log;
27 import org.apache.commons.logging.LogFactory;
28
29 import org.dbforms.config.*;
30
31 import org.dbforms.event.*;
32
33 import org.dbforms.util.*;
34
35 import java.io.*;
36
37 import java.sql.*;
38
39 import java.util.*;
40
41 import javax.servlet.http.*;
42
43
44
45 /**
46  * DOCUMENT ME!
47  *
48  * @author Joe Peer
49  *
50  * @deprecated <p>
51  */

52 public class UpdateEvent extends ValidationEvent {
53    static Log logCat = LogFactory.getLog(UpdateEvent.class.getName()); // logging category for this class
54

55    /**
56     * Creates a new UpdateEvent object.
57     *
58     * @param tableId DOCUMENT ME!
59     * @param keyId DOCUMENT ME!
60     * @param request DOCUMENT ME!
61     * @param config DOCUMENT ME!
62     */

63    public UpdateEvent(Integer JavaDoc tableId,
64                       String JavaDoc keyId,
65                       HttpServletRequest request,
66                       DbFormsConfig config) {
67       super(tableId.intValue(), keyId, request, config);
68    }
69
70
71    /**
72     * Creates a new UpdateEvent object.
73     *
74     * @param action DOCUMENT ME!
75     * @param request DOCUMENT ME!
76     * @param config DOCUMENT ME!
77     */

78    public UpdateEvent(String JavaDoc action,
79                       HttpServletRequest request,
80                       DbFormsConfig config) {
81       super(StringUtil.getEmbeddedStringAsInteger(action, 2, '_'),
82             StringUtil.getEmbeddedString(action, 3, '_'), request, config);
83    }
84
85    /**
86     * DOCUMENT ME!
87     *
88     * @return DOCUMENT ME!
89     */

90    public FieldValues getFieldValues() {
91       String JavaDoc s = ParseUtil.getParameter(getRequest(),
92                                         Constants.FIELDNAME_OVERRIDEFIELDTEST
93                                         + getTable().getId());
94       boolean flag = "true".equalsIgnoreCase(s);
95
96       return getFieldValues(flag);
97    }
98
99
100    /**
101     * DOCUMENT ME!
102     *
103     * @param con DOCUMENT ME!
104     *
105     * @throws SQLException DOCUMENT ME!
106     * @throws MultipleValidationException DOCUMENT ME!
107     * @throws IllegalArgumentException DOCUMENT ME!
108     */

109    public void processEvent(Connection con) throws SQLException {
110       // Apply given security contraints (as defined in dbforms-config.xml)
111
if (!hasUserPrivileg(GrantedPrivileges.PRIVILEG_UPDATE)) {
112          String JavaDoc s = MessageResourcesInternal.getMessage("dbforms.events.update.nogrant",
113                                                         getRequest().getLocale(),
114                                                         new String JavaDoc[] {
115                                                            getTable()
116                                                               .getName()
117                                                         });
118          throw new SQLException(s);
119       }
120
121       // which values do we find in request
122
FieldValues fieldValues = getFieldValues();
123
124       if (fieldValues.size() == 0) {
125          logCat.info("no parameters to update found");
126
127          return;
128       }
129
130       // in order to process an update, we need the key of the dataset to update
131
//
132
// new since version 0.9:
133
// key format: FieldID ":" Length ":" Value
134
// example: if key id = 121 and field id=2 then keyValueStr contains "2:3:121"
135
//
136
// if the key consists of more than one fields, the key values are seperated through "-"
137
// example: value of field 1=12, value of field 3=1992, then we'll get "1:2:12-3:4:1992"
138
String JavaDoc keyValuesStr = getKeyValues();
139
140       if (Util.isNull(keyValuesStr)) {
141          logCat.error("At least one key is required per table, check your dbforms-config.xml");
142
143          return;
144       }
145
146       DbEventInterceptorData interceptorData = new DbEventInterceptorData(getRequest(),
147                                                                getConfig(), con, getTable());
148       interceptorData.setAttribute(DbEventInterceptorData.FIELDVALUES, fieldValues);
149       interceptorData.setAttribute(DbEventInterceptorData.KEYVALUES, keyValuesStr);
150
151       // process the interceptors associated to this table
152
int operation = getTable()
153                          .processInterceptors(DbEventInterceptor.PRE_UPDATE,
154                                               interceptorData);
155
156       if ((operation == DbEventInterceptor.GRANT_OPERATION)
157                 && (fieldValues.size() > 0)) {
158          // End of interceptor processing
159
// now we start building the UPDATE statement
160
// 20021031-HKK: Moved into table
161
PreparedStatement ps = con.prepareStatement(getTable().getUpdateStatement(fieldValues));
162
163          // now we provide the values
164
// first, we provide the "new" values for fields
165
Iterator iter = fieldValues.elements();
166          int col = 1;
167
168          while (iter.hasNext()) {
169             FieldValue fv = (FieldValue) iter.next();
170
171             if (fv != null) {
172                Field curField = fv.getField();
173                int fieldType = curField.getType();
174                Object JavaDoc value = null;
175
176                if (fieldType == FieldTypes.BLOB) {
177                   // in case of a BLOB we supply the FileHolder object to SqlUtils for further operations
178
logCat.info("we are looking for fileholder with name: f_"
179                               + getTable().getId() + "_" + getKeyId() + "_"
180                               + curField.getId());
181                   value = fv.getFileHolder();
182                   logCat.info("and found a value=" + value);
183                } else if (fieldType == FieldTypes.DISKBLOB) {
184                   FileHolder fileHolder = fv.getFileHolder();
185                   String JavaDoc fileName = fileHolder.getFileName();
186
187                   // check if we need to store it encoded or not
188
if (curField.hasEncodedSet()) {
189                      // encode fileName
190
int dotIndex = fileName.lastIndexOf('.');
191                      String JavaDoc suffix = (dotIndex != -1)
192                                      ? fileName.substring(dotIndex)
193                                      : "";
194                      fileHolder.setFileName(UniqueIDGenerator.getUniqueID()
195                                             + suffix);
196
197                      // a diskblob gets stored to db as an ordinary string (it's only the reference!)
198
value = fileHolder.getFileName();
199                   } else {
200                      // a diskblob gets stored to db as an ordinary string (it's only the reference!)
201
value = fileName;
202                   }
203                } else {
204                   // in case of simple db types we just supply a string representing the value of the fields
205
value = fv.getFieldValueAsObject();
206                }
207
208                JDBCDataHelper.fillWithData(ps, fv.getField().getEscaper(), col,
209                                            value, fieldType,
210                                            getTable().getBlobHandlingStrategy());
211                col++;
212             }
213          }
214
215          getTable()
216             .populateWhereClauseWithKeyFields(keyValuesStr, ps, col);
217
218          // we are now ready to execute the query
219
ps.executeUpdate();
220          ps.close(); // #JP Jun 27, 2001
221

222          iter = fieldValues.keys();
223
224          while (iter.hasNext()) {
225             String JavaDoc fieldName = (String JavaDoc) iter.next();
226             Field curField = getTable()
227                                  .getFieldByName(fieldName);
228
229             if (curField != null) {
230                int fieldType = curField.getType();
231
232                String JavaDoc directory = null;
233
234                try {
235                   directory = Util.replaceRealPath(curField.getDirectory(),
236                                                    DbFormsConfigRegistry.instance().lookup().getRealPath());
237                } catch (Exception JavaDoc e) {
238                   throw new SQLException(e.getMessage());
239                }
240
241                if (fieldType == FieldTypes.DISKBLOB) {
242                   // check if directory-attribute was provided
243
if (directory == null) {
244                      throw new IllegalArgumentException JavaDoc("directory-attribute needed for fields of type DISKBLOB");
245                   }
246
247                   // instanciate file object for that dir
248
File dir = new File(directory);
249
250                   // Check saveDirectory is truly a directory
251
if (!dir.isDirectory()) {
252                      throw new IllegalArgumentException JavaDoc("Not a directory: "
253                                                         + directory);
254                   }
255
256                   // Check saveDirectory is writable
257
if (!dir.canWrite()) {
258                      throw new IllegalArgumentException JavaDoc("Not writable: "
259                                                         + directory);
260                   }
261
262                   // dir is ok so lets store the filepart
263
FileHolder fileHolder = ParseUtil.getFileHolder(getRequest(),
264                                                                   "f_"
265                                                                   + getTable().getId()
266                                                                   + "_"
267                                                                   + getKeyId()
268                                                                   + "_"
269                                                                   + curField
270                                                                     .getId());
271
272                   if (fileHolder != null) {
273                      try {
274                         fileHolder.writeBufferToFile(dir);
275
276                         //filePart.getInputStream().close();
277
logCat.info("fin + closedy");
278                      } catch (IOException ioe) {
279                         //#checkme: this would be a good place for rollback in database!!
280
throw new SQLException("could not store file '"
281                                                + fileHolder.getFileName()
282                                                + "' to dir '" + directory + "'");
283                      }
284                   } else {
285                      logCat.info("uh! empty fileHolder");
286                   }
287                }
288             }
289          }
290
291          // finally, we process interceptor again (post-update)
292
// process the interceptors associated to this table
293
getTable()
294             .processInterceptors(DbEventInterceptor.POST_UPDATE, interceptorData);
295       }
296
297       // End of interceptor processing
298
}
299 }
300
Popular Tags