View Javadoc

1   /*
2    * $Header: /cvsroot/jdbforms/dbforms/src/org/dbforms/event/classic/UpdateEvent.java,v 1.31 2006/01/25 16:35:23 hkollmann Exp $
3    * $Revision: 1.31 $
4    * $Date: 2006/01/25 16:35:23 $
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  import org.dbforms.interfaces.DbEventInterceptorData;
33  import org.dbforms.interfaces.IDbEventInterceptor;
34  
35  import org.dbforms.util.*;
36  
37  import java.io.*;
38  
39  import java.sql.*;
40  
41  import java.util.*;
42  
43  import javax.servlet.http.*;
44  
45  
46  
47  /***
48   * DOCUMENT ME!
49   *
50   * @author Joe Peer
51   *
52   * @deprecated <p>
53   */
54  public class UpdateEvent extends AbstractValidationEvent {
55     static Log logCat = LogFactory.getLog(UpdateEvent.class.getName()); // logging category for this class
56  
57     /***
58      * Creates a new UpdateEvent object.
59      *
60      * @param tableId DOCUMENT ME!
61      * @param keyId DOCUMENT ME!
62      * @param request DOCUMENT ME!
63      * @param config DOCUMENT ME!
64      */
65     public UpdateEvent(Integer            tableId,
66                        String             keyId,
67                        HttpServletRequest request,
68                        DbFormsConfig      config) {
69        super(tableId.intValue(), keyId, request, config);
70     }
71  
72  
73     /***
74      * Creates a new UpdateEvent object.
75      *
76      * @param action DOCUMENT ME!
77      * @param request DOCUMENT ME!
78      * @param config DOCUMENT ME!
79      */
80     public UpdateEvent(String             action,
81                        HttpServletRequest request,
82                        DbFormsConfig      config) {
83        super(StringUtil.getEmbeddedStringAsInteger(action, 2, '_'),
84              StringUtil.getEmbeddedString(action, 3, '_'), request, config);
85     }
86  
87     /***
88      * DOCUMENT ME!
89      *
90      * @return DOCUMENT ME!
91      */
92     public FieldValues getFieldValues() {
93        String s = ParseUtil.getParameter(getRequest(),
94                                          Constants.FIELDNAME_OVERRIDEFIELDTEST
95                                          + getTable().getId());
96        boolean flag = "true".equalsIgnoreCase(s);
97  
98        return getFieldValues(flag);
99     }
100 
101 
102    /***
103     * DOCUMENT ME!
104     *
105     * @param con DOCUMENT ME!
106     *
107     * @throws SQLException DOCUMENT ME!
108     * @throws MultipleValidationException DOCUMENT ME!
109     * @throws IllegalArgumentException DOCUMENT ME!
110     */
111    public void processEvent(Connection con) throws SQLException, MultipleValidationException {
112       // Apply given security contraints (as defined in dbforms-config.xml)
113       if (!hasUserPrivileg(GrantedPrivileges.PRIVILEG_UPDATE)) {
114          String s = MessageResourcesInternal.getMessage("dbforms.events.update.nogrant",
115                                                         getRequest().getLocale(),
116                                                         new String[] {
117                                                            getTable()
118                                                               .getName()
119                                                         });
120          throw new SQLException(s);
121       }
122 
123       // which values do we find in request
124       FieldValues fieldValues = getFieldValues();
125 
126       if (fieldValues.size() == 0) {
127          logCat.info("no parameters to update found");
128 
129          return;
130       }
131 
132       // in order to process an update, we need the key of the dataset to update
133       //
134       // new since version 0.9:
135       // key format: FieldID ":" Length ":" Value
136       // example: if key id = 121 and field id=2 then keyValueStr contains "2:3:121"
137       //
138       // if the key consists of more than one fields, the key values are seperated through "-"
139       // example: value of field 1=12, value of field 3=1992, then we'll get "1:2:12-3:4:1992"
140       String keyValuesStr = getKeyValues();
141 
142       if (Util.isNull(keyValuesStr)) {
143          logCat.error("At least one key is required per table, check your dbforms-config.xml");
144 
145          return;
146       }
147 
148       DbEventInterceptorData interceptorData = new DbEventInterceptorData(getRequest(),
149                                                                getConfig(), con, getTable());
150       interceptorData.setAttribute(DbEventInterceptorData.FIELDVALUES, fieldValues);
151       interceptorData.setAttribute(DbEventInterceptorData.KEYVALUES, keyValuesStr);
152 
153       // process the interceptors associated to this table
154       int operation = getTable()
155                          .processInterceptors(IDbEventInterceptor.PRE_UPDATE,
156                                               interceptorData);
157 
158       if ((operation == IDbEventInterceptor.GRANT_OPERATION)
159                 && (fieldValues.size() > 0)) {
160          // End of interceptor processing
161          // now we start building the UPDATE statement
162          // 20021031-HKK: Moved into table
163          PreparedStatement ps = con.prepareStatement(getTable().getUpdateStatement(fieldValues, keyValuesStr));
164 
165          // now we provide the values
166          // first, we provide the "new" values for fields
167          Iterator iter = fieldValues.elements();
168          int      col = 1;
169 
170          while (iter.hasNext()) {
171             FieldValue fv = (FieldValue) iter.next();
172 
173             if (fv != null) {
174                Field  curField  = fv.getField();
175                int    fieldType = curField.getType();
176                Object value     = null;
177 
178                if (fieldType == FieldTypes.BLOB) {
179                   // in case of a BLOB we supply the FileHolder object to SqlUtils for further operations
180                   logCat.info("we are looking for fileholder with name: f_"
181                               + getTable().getId() + "_" + getKeyId() + "_"
182                               + curField.getId());
183                   value = fv.getFileHolder();
184                   logCat.info("and found a value=" + value);
185                } else if (fieldType == FieldTypes.DISKBLOB) {
186                   FileHolder fileHolder = fv.getFileHolder();
187                   String     fileName = fileHolder.getFileName();
188 
189                   // check if we need to store it encoded or not
190                   if (curField.hasEncodedSet()) {
191                      // encode fileName
192                      int    dotIndex = fileName.lastIndexOf('.');
193                      String suffix = (dotIndex != -1)
194                                      ? fileName.substring(dotIndex)
195                                      : "";
196                      fileHolder.setFileName(UniqueIDGenerator.getUniqueID()
197                                             + suffix);
198 
199                      // a diskblob gets stored to db as an ordinary string (it's only the reference!)
200                      value = fileHolder.getFileName();
201                   } else {
202                      // a diskblob gets stored to db as an ordinary string	 (it's only the reference!)
203                      value = fileName;
204                   }
205                } else {
206                   // in case of simple db types we just supply a string representing the value of the fields
207                   value = fv.getFieldValueAsObject();
208                }
209 
210                JDBCDataHelper.fillWithData(ps, fv.getField().getEscaper(), col,
211                                            value, fieldType,
212                                            getTable().getBlobHandlingStrategy());
213                col++;
214             }
215          }
216 
217          getTable()
218             .populateWhereClauseWithKeyFields(keyValuesStr, ps, col);
219 
220          // we are now ready to execute the query
221          ps.executeUpdate();
222          ps.close(); // #JP Jun 27, 2001
223 
224          iter = fieldValues.keys();
225 
226          while (iter.hasNext()) {
227             String fieldName = (String) iter.next();
228             Field  curField = getTable()
229                                  .getFieldByName(fieldName);
230 
231             if (curField != null) {
232                int    fieldType = curField.getType();
233 
234                String directory = null;
235 
236                try {
237                   directory = DbFormsConfigRegistry.instance().lookup().replaceVariables(curField.getDirectory());
238                } catch (Exception e) {
239                   throw new SQLException(e.getMessage());
240                }
241 
242                if (fieldType == FieldTypes.DISKBLOB) {
243                   // check if directory-attribute was provided
244                   if (directory == null) {
245                      throw new IllegalArgumentException("directory-attribute needed for fields of type DISKBLOB");
246                   }
247 
248                   // instanciate file object for that dir
249                   File dir = new File(directory);
250 
251                   // Check saveDirectory is truly a directory
252                   if (!dir.isDirectory()) {
253                      throw new IllegalArgumentException("Not a directory: "
254                                                         + directory);
255                   }
256 
257                   // Check saveDirectory is writable
258                   if (!dir.canWrite()) {
259                      throw new IllegalArgumentException("Not writable: "
260                                                         + directory);
261                   }
262 
263                   // dir is ok so lets store the filepart
264                   FileHolder fileHolder = ParseUtil.getFileHolder(getRequest(),
265                                                                   "f_"
266                                                                   + getTable().getId()
267                                                                   + "_"
268                                                                   + getKeyId()
269                                                                   + "_"
270                                                                   + curField
271                                                                     .getId());
272 
273                   if (fileHolder != null) {
274                      try {
275                         fileHolder.writeBufferToFile(dir);
276 
277                         //filePart.getInputStream().close();
278                         logCat.info("fin + closedy");
279                      } catch (IOException ioe) {
280                         //#checkme: this would be a good place for rollback in database!!
281                         throw new SQLException("could not store file '"
282                                                + fileHolder.getFileName()
283                                                + "' to dir '" + directory + "'");
284                      }
285                   } else {
286                      logCat.info("uh! empty fileHolder");
287                   }
288                }
289             }
290          }
291 
292          // finally, we process interceptor again (post-update)
293          // process the interceptors associated to this table
294          getTable()
295             .processInterceptors(IDbEventInterceptor.POST_UPDATE, interceptorData);
296       }
297 
298       // End of interceptor processing
299    }
300 }