KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * $Header: /cvsroot/jdbforms/dbforms/src/org/dbforms/event/classic/InsertEvent.java,v 1.32 2004/10/20 10:51:29 hkollmann Exp $
3  * $Revision: 1.32 $
4  * $Date: 2004/10/20 10:51:29 $
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.Constants;
30 import org.dbforms.config.DbEventInterceptor;
31 import org.dbforms.config.DbEventInterceptorData;
32 import org.dbforms.config.DbFormsConfig;
33 import org.dbforms.config.DbFormsConfigRegistry;
34 import org.dbforms.config.Field;
35 import org.dbforms.config.FieldTypes;
36 import org.dbforms.config.FieldValue;
37 import org.dbforms.config.FieldValues;
38 import org.dbforms.config.GrantedPrivileges;
39 import org.dbforms.config.JDBCDataHelper;
40 import org.dbforms.config.ResultSetVector;
41
42 import org.dbforms.event.ValidationEvent;
43
44 import org.dbforms.util.FileHolder;
45 import org.dbforms.util.MessageResourcesInternal;
46 import org.dbforms.util.ParseUtil;
47 import org.dbforms.util.StringUtil;
48 import org.dbforms.util.UniqueIDGenerator;
49 import org.dbforms.util.Util;
50
51 import java.io.File JavaDoc;
52 import java.io.IOException JavaDoc;
53
54 import java.sql.Connection JavaDoc;
55 import java.sql.PreparedStatement JavaDoc;
56 import java.sql.SQLException JavaDoc;
57
58 import java.util.Iterator JavaDoc;
59 import java.util.Vector JavaDoc;
60
61 import javax.servlet.http.HttpServletRequest JavaDoc;
62
63
64
65 /**
66  * DOCUMENT ME!
67  *
68  * @author Joe Peer
69  *
70  * @deprecated This event prepares and performs a SQL-Insert operation.
71  */

72 public class InsertEvent extends ValidationEvent {
73    /** logging category for this class */
74    static Log logCat = LogFactory.getLog(InsertEvent.class.getName());
75
76    /**
77     * Creates a new InsertEvent object.
78     *
79     * @param tableId DOCUMENT ME!
80     * @param keyId DOCUMENT ME!
81     * @param request DOCUMENT ME!
82     * @param config DOCUMENT ME!
83     */

84    public InsertEvent(Integer JavaDoc tableId,
85                       String JavaDoc keyId,
86                       HttpServletRequest JavaDoc request,
87                       DbFormsConfig config) {
88       super(tableId.intValue(), keyId, request, config);
89    }
90
91
92    /**
93     * Insert actionbutton-strings is as follows: ac_insert_12_root_3 which is
94     * equivalent to: ac_insert : insert action event 12 : table id
95     * root : key 3 : button count used to identify individual
96     * insert buttons
97     *
98     * @param action DOCUMENT ME!
99     * @param request DOCUMENT ME!
100     * @param config DOCUMENT ME!
101     */

102    public InsertEvent(String JavaDoc action,
103                       HttpServletRequest JavaDoc request,
104                       DbFormsConfig config) {
105       super(StringUtil.getEmbeddedStringAsInteger(action, 2, '_'),
106             StringUtil.getEmbeddedString(action, 3, '_'), request, config);
107    }
108
109    /**
110     * Get the hash table containing the form field names and values taken from
111     * the request object. <br>
112     * Example of a request parameter:<br>
113     * <code>name = f_0_insroot_6 value = foo-bar </code>
114     *
115     * @return the hash map containing the names and values taken from the
116     * request object
117     */

118    public FieldValues getFieldValues() {
119       return getFieldValues(true);
120    }
121
122
123    /**
124     * Process this event.
125     *
126     * @param con the jdbc connection object
127     *
128     * @throws SQLException if any data access error occurs
129     * @throws MultipleValidationException if any validation error occurs
130     */

131    public void processEvent(Connection JavaDoc con) throws SQLException JavaDoc {
132       // Applying given security contraints (as defined in dbforms-config xml file)
133
// part 1: check if requested privilge is granted for role
134
if (!hasUserPrivileg(GrantedPrivileges.PRIVILEG_INSERT)) {
135          String JavaDoc s = MessageResourcesInternal.getMessage("dbforms.events.insert.nogrant",
136                                                         getRequest().getLocale(),
137                                                         new String JavaDoc[] {
138                                                            getTable()
139                                                               .getName()
140                                                         });
141          throw new SQLException JavaDoc(s);
142       }
143
144       FieldValues fieldValues = getFieldValues();
145
146       if (fieldValues.size() == 0) {
147          throw new SQLException JavaDoc("no parameters");
148       }
149
150       DbEventInterceptorData interceptorData = new DbEventInterceptorData(getRequest(),
151                                                                getConfig(), con, getTable());
152       interceptorData.setAttribute(DbEventInterceptorData.FIELDVALUES, fieldValues);
153
154       // process the interceptors associated to this table
155
int operation = getTable()
156                          .processInterceptors(DbEventInterceptor.PRE_INSERT,
157                                               interceptorData);
158
159       if ((operation == DbEventInterceptor.GRANT_OPERATION)
160                 && (fieldValues.size() > 0)) {
161          // End of interceptor processing
162
if (!checkSufficentValues(fieldValues)) {
163             throw new SQLException JavaDoc("unsufficent parameters");
164          }
165
166          PreparedStatement JavaDoc ps = con.prepareStatement(getTable().getInsertStatement(fieldValues));
167
168          // now we provide the values;
169
// every key is the parameter name from of the form page;
170
Iterator JavaDoc iter = fieldValues.elements();
171          int col = 1;
172
173          while (iter.hasNext()) {
174             FieldValue fv = (FieldValue) iter.next();
175
176             if (fv != null) {
177                Field curField = fv.getField();
178                logCat.debug("Retrieved curField:" + curField.getName()
179                             + " type:" + curField.getType());
180
181                int fieldType = curField.getType();
182                Object JavaDoc value = null;
183
184                if (fieldType == FieldTypes.BLOB) {
185                   // in case of a BLOB we supply the FileHolder object to SqlUtils for further operations
186
value = fv.getFileHolder();
187                } else if (fieldType == FieldTypes.DISKBLOB) {
188                   // check if we need to store it encoded or not
189
FileHolder fileHolder = fv.getFileHolder();
190                   String JavaDoc fileName = fileHolder.getFileName();
191
192                   if (curField.hasEncodedSet()) {
193                      int dotIndex = fileName.lastIndexOf('.');
194                      String JavaDoc suffix = (dotIndex != -1)
195                                      ? fileName.substring(dotIndex)
196                                      : "";
197                      fileHolder.setFileName(UniqueIDGenerator.getUniqueID()
198                                             + suffix);
199
200                      // a diskblob gets stored to db as an ordinary string (it's only the reference!)
201
value = fileHolder.getFileName();
202                   } else {
203                      // a diskblob gets stored to db as an ordinary string (it's only the reference!)
204
value = fileName;
205                   }
206                } else {
207                   value = fv.getFieldValueAsObject();
208                }
209
210                logCat.info("PRE_INSERT: field=" + curField.getName() + " col="
211                            + col + " value=" + value + " type=" + fieldType);
212                JDBCDataHelper.fillWithData(ps, fv.getField().getEscaper(), col,
213                                            value, fieldType,
214                                            getTable().getBlobHandlingStrategy());
215                col++;
216             }
217          }
218
219          // execute the query & throws an exception if something goes wrong
220
ps.executeUpdate();
221          ps.close(); // #JP Jun 27, 2001
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 JavaDoc(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 JavaDoc dir = new File JavaDoc(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                                                                   + "_ins"
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 JavaDoc ioe) {
279                         //#checkme: this would be a good place for rollback in database!!
280
throw new SQLException JavaDoc("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          //Patch insert nav by Stefano Borghi
292
//Show the last record inserted
293

294          /**
295           * @todo Will not work if key field is autoinc!!
296           */

297          String JavaDoc firstPosition = null;
298          Vector key = getTable()
299                                .getKey();
300          FieldValue[] fvEqual = new FieldValue[key.size()];
301
302          for (int i = 0; i < key.size(); i++) {
303             Field field = (Field) key.elementAt(i);
304             String JavaDoc fieldName = field.getName();
305             FieldValue fv = fieldValues.get(fieldName);
306             String JavaDoc value = null;
307
308             if (fv != null) {
309                value = fv.getFieldValue();
310             }
311
312             FieldValue keyFieldValue = new FieldValue(field, value);
313             fvEqual[i] = keyFieldValue;
314          }
315
316          ResultSetVector resultSetVector = getTable()
317                                               .doConstrainedSelect(fvEqual,
318                                                                    null, null,
319                                                                    null,
320                                                                    Constants.COMPARE_NONE,
321                                                                    1, interceptorData);
322
323          if (resultSetVector != null) {
324             resultSetVector.moveFirst();
325             firstPosition = getTable()
326                                .getPositionString(resultSetVector);
327          }
328
329          getRequest()
330             .setAttribute("firstpos_" + getTable().getId(), firstPosition);
331
332          // finally, we process interceptor again (post-insert)
333
// process the interceptors associated to this table
334
getTable()
335             .processInterceptors(DbEventInterceptor.POST_INSERT, interceptorData);
336       }
337    }
338
339
340    /**
341     * Check if the input hash table has got sufficent parameters.
342     *
343     * @param fieldValues the hash map containing the names and values taken
344     * from the request object
345     *
346     * @return true if the hash table has got sufficent parameters, false
347     * otherwise
348     *
349     * @throws SQLException if any data access error occurs
350     */

351    private boolean checkSufficentValues(FieldValues fieldValues)
352                                  throws SQLException JavaDoc {
353       Vector fields = getTable()
354                          .getFields();
355
356       for (int i = 0; i < fields.size(); i++) {
357          Field field = (Field) fields.elementAt(i);
358
359          // if a field is a key and if it is NOT automatically generated,
360
// then it should be provided by the user
361
if (!field.hasAutoIncSet() && field.hasIsKeySet()) {
362             if (fieldValues.get(field.getName()) == null) {
363                throw new SQLException JavaDoc("Field " + field.getName()
364                                       + " is missing");
365             }
366          }
367          // in opposite, if a field is automatically generated by the RDBMS, we need to
368
else if (field.hasAutoIncSet()) {
369             if (fieldValues.get(field.getName()) != null) {
370                throw new SQLException JavaDoc("Field " + field.getName()
371                                       + " should be calculated by RDBMS, remove it from the form");
372             }
373          }
374
375          // in future we could do some other checks like NOT-NULL conditions,etc.
376
}
377
378       return true;
379    }
380 }
381
Popular Tags