KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > entity > jdbc > SqlJdbcUtil


1 /*
2  * $Id: SqlJdbcUtil.java 6095 2005-11-09 01:38:54Z 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.entity.jdbc;
25
26 import java.io.ByteArrayInputStream JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.io.InputStream JavaDoc;
29 import java.io.ObjectInputStream JavaDoc;
30 import java.io.Reader JavaDoc;
31 import java.math.BigDecimal JavaDoc;
32 import java.sql.ResultSet JavaDoc;
33 import java.sql.ResultSetMetaData JavaDoc;
34 import java.sql.SQLException JavaDoc;
35 import java.sql.Clob JavaDoc;
36 import java.util.Collection JavaDoc;
37 import java.util.Iterator JavaDoc;
38 import java.util.List JavaDoc;
39 import java.util.Map JavaDoc;
40 import java.util.Set JavaDoc;
41 import java.util.TreeSet JavaDoc;
42
43 import javolution.util.FastMap;
44
45 import org.ofbiz.base.util.Debug;
46 import org.ofbiz.base.util.ObjectType;
47 import org.ofbiz.base.util.UtilValidate;
48 import org.ofbiz.entity.GenericDataSourceException;
49 import org.ofbiz.entity.GenericEntity;
50 import org.ofbiz.entity.GenericEntityException;
51 import org.ofbiz.entity.GenericModelException;
52 import org.ofbiz.entity.GenericNotImplementedException;
53 import org.ofbiz.entity.GenericValue;
54 import org.ofbiz.entity.condition.EntityConditionParam;
55 import org.ofbiz.entity.condition.OrderByList;
56 import org.ofbiz.entity.config.DatasourceInfo;
57 import org.ofbiz.entity.datasource.GenericDAO;
58 import org.ofbiz.entity.model.ModelEntity;
59 import org.ofbiz.entity.model.ModelField;
60 import org.ofbiz.entity.model.ModelFieldType;
61 import org.ofbiz.entity.model.ModelFieldTypeReader;
62 import org.ofbiz.entity.model.ModelKeyMap;
63 import org.ofbiz.entity.model.ModelViewEntity;
64
65 /**
66  * GenericDAO Utility methods for general tasks
67  *
68  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
69  * @author <a HREF="mailto:chris_maurer@altavista.com">Chris Maurer</a>
70  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
71  * @author <a HREF="mailto:jdonnerstag@eds.de">Juergen Donnerstag</a>
72  * @author <a HREF="mailto:peterm@miraculum.com">Peter Moon</a>
73  * @version $Rev: 6095 $
74  * @since 2.0
75  */

76 public class SqlJdbcUtil {
77     public static final String JavaDoc module = GenericDAO.class.getName();
78     
79     public static final int CHAR_BUFFER_SIZE = 4096;
80
81     /** Makes the FROM clause and when necessary the JOIN clause(s) as well */
82     public static String JavaDoc makeFromClause(ModelEntity modelEntity, DatasourceInfo datasourceInfo) throws GenericEntityException {
83         StringBuffer JavaDoc sql = new StringBuffer JavaDoc(" FROM ");
84
85         if (modelEntity instanceof ModelViewEntity) {
86             ModelViewEntity modelViewEntity = (ModelViewEntity) modelEntity;
87
88             if ("ansi".equals(datasourceInfo.joinStyle) || "ansi-no-parenthesis".equals(datasourceInfo.joinStyle)) {
89                 boolean useParenthesis = true;
90                 if ("ansi-no-parenthesis".equals(datasourceInfo.joinStyle)) {
91                     useParenthesis = false;
92                 }
93
94                 // FROM clause: in this case will be a bunch of joins that correspond with the view-links
95

96                 // BIG NOTE on the JOIN clauses: the order of joins is determined by the order of the
97
// view-links; for more flexible order we'll have to figure something else out and
98
// extend the DTD for the nested view-link elements or something
99

100                 // At this point it is assumed that in each view-link the left hand alias will
101
// either be the first alias in the series or will already be in a previous
102
// view-link and already be in the big join; SO keep a set of all aliases
103
// in the join so far and if the left entity alias isn't there yet, and this
104
// isn't the first one, throw an exception
105
Set JavaDoc joinedAliasSet = new TreeSet JavaDoc();
106
107                 // TODO: at view-link read time make sure they are ordered properly so that each
108
// left hand alias after the first view-link has already been linked before
109

110                 StringBuffer JavaDoc openParens = null;
111                 if (useParenthesis) openParens = new StringBuffer JavaDoc();
112                 StringBuffer JavaDoc restOfStatement = new StringBuffer JavaDoc();
113
114                 for (int i = 0; i < modelViewEntity.getViewLinksSize(); i++) {
115                     // don't put starting parenthesis
116
if (i > 0 && useParenthesis) openParens.append('(');
117
118                     ModelViewEntity.ModelViewLink viewLink = modelViewEntity.getViewLink(i);
119
120                     ModelEntity linkEntity = modelViewEntity.getMemberModelEntity(viewLink.getEntityAlias());
121                     ModelEntity relLinkEntity = modelViewEntity.getMemberModelEntity(viewLink.getRelEntityAlias());
122
123                     // ModelViewEntity.ModelMemberEntity linkMemberEntity = modelViewEntity.getMemberModelMemberEntity(viewLink.getEntityAlias());
124
// ModelViewEntity.ModelMemberEntity relLinkMemberEntity = modelViewEntity.getMemberModelMemberEntity(viewLink.getRelEntityAlias());
125

126                     if (i == 0) {
127                         // this is the first referenced member alias, so keep track of it for future use...
128
restOfStatement.append(makeViewTable(linkEntity, datasourceInfo));
129                         //another possible one that some dbs might need, but not sure of any yet: restOfStatement.append(" AS ");
130
restOfStatement.append(" ");
131                         restOfStatement.append(viewLink.getEntityAlias());
132
133                         joinedAliasSet.add(viewLink.getEntityAlias());
134                     } else {
135                         // make sure the left entity alias is already in the join...
136
if (!joinedAliasSet.contains(viewLink.getEntityAlias())) {
137                             throw new GenericModelException("Tried to link the " + viewLink.getEntityAlias() + " alias to the " + viewLink.getRelEntityAlias() + " alias of the " + modelViewEntity.getEntityName() + " view-entity, but it is not the first view-link and has not been included in a previous view-link. In other words, the left/main alias isn't connected to the rest of the member-entities yet.");
138                         }
139                     }
140                     // now put the rel (right) entity alias into the set that is in the join
141
joinedAliasSet.add(viewLink.getRelEntityAlias());
142
143                     if (viewLink.isRelOptional()) {
144                         restOfStatement.append(" LEFT OUTER JOIN ");
145                     } else {
146                         restOfStatement.append(" INNER JOIN ");
147                     }
148
149                     restOfStatement.append(makeViewTable(relLinkEntity, datasourceInfo));
150                     //another possible one that some dbs might need, but not sure of any yet: restOfStatement.append(" AS ");
151
restOfStatement.append(" ");
152                     restOfStatement.append(viewLink.getRelEntityAlias());
153                     restOfStatement.append(" ON ");
154
155                     StringBuffer JavaDoc condBuffer = new StringBuffer JavaDoc();
156
157                     for (int j = 0; j < viewLink.getKeyMapsSize(); j++) {
158                         ModelKeyMap keyMap = viewLink.getKeyMap(j);
159                         ModelField linkField = linkEntity.getField(keyMap.getFieldName());
160                         if (linkField == null) {
161                             throw new GenericModelException("Invalid field name in view-link key-map for the " + viewLink.getEntityAlias() + " and the " + viewLink.getRelEntityAlias() + " member-entities of the " + modelViewEntity.getEntityName() + " view-entity; the field [" + keyMap.getFieldName() + "] does not exist on the [" + linkEntity.getEntityName() + "] entity.");
162                         }
163                         ModelField relLinkField = relLinkEntity.getField(keyMap.getRelFieldName());
164                         if (relLinkField == null) {
165                             throw new GenericModelException("Invalid related field name in view-link key-map for the " + viewLink.getEntityAlias() + " and the " + viewLink.getRelEntityAlias() + " member-entities of the " + modelViewEntity.getEntityName() + " view-entity; the field [" + keyMap.getRelFieldName() + "] does not exist on the [" + relLinkEntity.getEntityName() + "] entity.");
166                         }
167
168                         if (condBuffer.length() > 0) {
169                             condBuffer.append(" AND ");
170                         }
171                         
172                         condBuffer.append(viewLink.getEntityAlias());
173                         condBuffer.append(".");
174                         condBuffer.append(filterColName(linkField.getColName()));
175
176                         condBuffer.append(" = ");
177
178                         condBuffer.append(viewLink.getRelEntityAlias());
179                         condBuffer.append(".");
180                         condBuffer.append(filterColName(relLinkField.getColName()));
181                     }
182                     if (condBuffer.length() == 0) {
183                         throw new GenericModelException("No view-link/join key-maps found for the " + viewLink.getEntityAlias() + " and the " + viewLink.getRelEntityAlias() + " member-entities of the " + modelViewEntity.getEntityName() + " view-entity.");
184                     }
185                     restOfStatement.append(condBuffer.toString());
186
187                     // don't put ending parenthesis
188
if (i < (modelViewEntity.getViewLinksSize() - 1) && useParenthesis) restOfStatement.append(')');
189                 }
190
191                 if (useParenthesis) sql.append(openParens.toString());
192                 sql.append(restOfStatement.toString());
193
194                 // handle tables not included in view-link
195
Iterator JavaDoc meIter = modelViewEntity.getMemberModelMemberEntities().entrySet().iterator();
196                 boolean fromEmpty = restOfStatement.length() == 0;
197
198                 while (meIter.hasNext()) {
199                     Map.Entry JavaDoc entry = (Map.Entry JavaDoc) meIter.next();
200                     ModelEntity fromEntity = modelViewEntity.getMemberModelEntity((String JavaDoc) entry.getKey());
201
202                     if (!joinedAliasSet.contains((String JavaDoc) entry.getKey())) {
203                         if (!fromEmpty) sql.append(", ");
204                         fromEmpty = false;
205
206                         sql.append(makeViewTable(fromEntity, datasourceInfo));
207                         sql.append(" ");
208                         sql.append((String JavaDoc) entry.getKey());
209                     }
210                 }
211
212
213             } else if ("theta-oracle".equals(datasourceInfo.joinStyle) || "theta-mssql".equals(datasourceInfo.joinStyle)) {
214                 // FROM clause
215
Iterator JavaDoc meIter = modelViewEntity.getMemberModelMemberEntities().entrySet().iterator();
216
217                 while (meIter.hasNext()) {
218                     Map.Entry JavaDoc entry = (Map.Entry JavaDoc) meIter.next();
219                     ModelEntity fromEntity = modelViewEntity.getMemberModelEntity((String JavaDoc) entry.getKey());
220
221                     sql.append(makeViewTable(fromEntity, datasourceInfo));
222                     sql.append(" ");
223                     sql.append((String JavaDoc) entry.getKey());
224                     if (meIter.hasNext()) sql.append(", ");
225                 }
226
227                 // JOIN clause(s): none needed, all the work done in the where clause for theta-oracle
228
} else {
229                 throw new GenericModelException("The join-style " + datasourceInfo.joinStyle + " is not yet supported");
230             }
231         } else {
232             sql.append(modelEntity.getTableName(datasourceInfo));
233         }
234         return sql.toString();
235     }
236
237     /** Makes a WHERE clause String with "<col name>=?" if not null or "<col name> IS null" if null, all AND separated */
238     public static String JavaDoc makeWhereStringFromFields(List JavaDoc modelFields, Map JavaDoc fields, String JavaDoc operator) {
239         return makeWhereStringFromFields(modelFields, fields, operator, null);
240     }
241
242     /** Makes a WHERE clause String with "<col name>=?" if not null or "<col name> IS null" if null, all AND separated */
243     public static String JavaDoc makeWhereStringFromFields(List JavaDoc modelFields, Map JavaDoc fields, String JavaDoc operator, List JavaDoc entityConditionParams) {
244         if (modelFields.size() < 1) {
245             return "";
246         }
247
248         StringBuffer JavaDoc returnString = new StringBuffer JavaDoc("");
249         Iterator JavaDoc iter = modelFields.iterator();
250         while (iter.hasNext()) {
251             Object JavaDoc item = iter.next();
252             Object JavaDoc name = null;
253             ModelField modelField = null;
254             if (item instanceof ModelField) {
255                 modelField = (ModelField) item;
256                 returnString.append(modelField.getColName());
257                 name = modelField.getName();
258             } else {
259                 returnString.append(item);
260                 name = item;
261             }
262
263             Object JavaDoc fieldValue = fields.get(name);
264             if (fieldValue != null && fieldValue != GenericEntity.NULL_FIELD) {
265                 returnString.append('=');
266                 addValue(returnString, modelField, fieldValue, entityConditionParams);
267             } else {
268                 returnString.append(" IS NULL");
269             }
270
271             if (iter.hasNext()) {
272                 returnString.append(' ');
273                 returnString.append(operator);
274                 returnString.append(' ');
275             }
276         }
277
278         return returnString.toString();
279     }
280
281     public static String JavaDoc makeWhereClause(ModelEntity modelEntity, List JavaDoc modelFields, Map JavaDoc fields, String JavaDoc operator, String JavaDoc joinStyle) throws GenericEntityException {
282         StringBuffer JavaDoc whereString = new StringBuffer JavaDoc("");
283
284         if (modelFields != null && modelFields.size() > 0) {
285             whereString.append(makeWhereStringFromFields(modelFields, fields, "AND"));
286         }
287
288         String JavaDoc viewClause = makeViewWhereClause(modelEntity, joinStyle);
289
290         if (viewClause.length() > 0) {
291             if (whereString.length() > 0) {
292                 whereString.append(' ');
293                 whereString.append(operator);
294                 whereString.append(' ');
295             }
296
297             whereString.append(viewClause);
298         }
299
300         if (whereString.length() > 0) {
301             return " WHERE " + whereString.toString();
302         }
303
304         return "";
305     }
306
307     public static String JavaDoc makeViewWhereClause(ModelEntity modelEntity, String JavaDoc joinStyle) throws GenericEntityException {
308         if (modelEntity instanceof ModelViewEntity) {
309             StringBuffer JavaDoc whereString = new StringBuffer JavaDoc();
310             ModelViewEntity modelViewEntity = (ModelViewEntity) modelEntity;
311
312             if ("ansi".equals(joinStyle) || "ansi-no-parenthesis".equals(joinStyle)) {
313                 // nothing to do here, all done in the JOIN clauses
314
} else if ("theta-oracle".equals(joinStyle) || "theta-mssql".equals(joinStyle)) {
315                 boolean isOracleStyle = "theta-oracle".equals(joinStyle);
316                 boolean isMssqlStyle = "theta-mssql".equals(joinStyle);
317
318                 for (int i = 0; i < modelViewEntity.getViewLinksSize(); i++) {
319                     ModelViewEntity.ModelViewLink viewLink = modelViewEntity.getViewLink(i);
320
321                     ModelEntity linkEntity = modelViewEntity.getMemberModelEntity(viewLink.getEntityAlias());
322                     ModelEntity relLinkEntity = modelViewEntity.getMemberModelEntity(viewLink.getRelEntityAlias());
323
324                     if (linkEntity == null) {
325                         throw new GenericEntityException("Link entity not found with alias: " + viewLink.getEntityAlias() + " for entity: " + modelViewEntity.getEntityName());
326                     }
327
328                     if (relLinkEntity == null) {
329                         throw new GenericEntityException("Rel-Link entity not found with alias: " + viewLink.getRelEntityAlias() + " for entity: " + modelViewEntity.getEntityName());
330                     }
331
332                     // ModelViewEntity.ModelMemberEntity linkMemberEntity = modelViewEntity.getMemberModelMemberEntity(viewLink.getEntityAlias());
333
// ModelViewEntity.ModelMemberEntity relLinkMemberEntity = modelViewEntity.getMemberModelMemberEntity(viewLink.getRelEntityAlias());
334

335                     for (int j = 0; j < viewLink.getKeyMapsSize(); j++) {
336                         ModelKeyMap keyMap = viewLink.getKeyMap(j);
337                         ModelField linkField = linkEntity.getField(keyMap.getFieldName());
338                         ModelField relLinkField = relLinkEntity.getField(keyMap.getRelFieldName());
339
340                         if (whereString.length() > 0) {
341                             whereString.append(" AND ");
342                         }
343                         whereString.append(viewLink.getEntityAlias());
344                         whereString.append(".");
345                         whereString.append(filterColName(linkField.getColName()));
346
347                         // check to see whether the left or right members are optional, if so:
348
// oracle: use the (+) on the optional side
349
// mssql: use the * on the required side
350

351                         // NOTE: not testing if original table is optional, ONLY if related table is optional; otherwise things get really ugly...
352
// if (isOracleStyle && linkMemberEntity.getOptional()) whereString.append(" (+) ");
353
if (isMssqlStyle && viewLink.isRelOptional()) whereString.append("*");
354                         whereString.append("=");
355                         // if (isMssqlStyle && linkMemberEntity.getOptional()) whereString.append("*");
356
if (isOracleStyle && viewLink.isRelOptional()) whereString.append(" (+) ");
357
358                         whereString.append(viewLink.getRelEntityAlias());
359                         whereString.append(".");
360                         whereString.append(filterColName(relLinkField.getColName()));
361                    }
362                 }
363             } else {
364                 throw new GenericModelException("The join-style " + joinStyle + " is not supported");
365             }
366
367             if (whereString.length() > 0) {
368                 return "(" + whereString.toString() + ")";
369             }
370         }
371         return "";
372     }
373
374     public static String JavaDoc makeOrderByClause(ModelEntity modelEntity, List JavaDoc orderBy, DatasourceInfo datasourceInfo) throws GenericModelException {
375         return makeOrderByClause(modelEntity, orderBy, false, datasourceInfo);
376     }
377
378     public static String JavaDoc makeOrderByClause(ModelEntity modelEntity, List JavaDoc orderBy, boolean includeTablenamePrefix, DatasourceInfo datasourceInfo) throws GenericModelException {
379         StringBuffer JavaDoc sql = new StringBuffer JavaDoc("");
380         //String fieldPrefix = includeTablenamePrefix ? (modelEntity.getTableName(datasourceInfo) + ".") : "";
381

382         if (orderBy != null && orderBy.size() > 0) {
383             if (Debug.verboseOn()) Debug.logVerbose("Order by list contains: " + orderBy.size() + " entries.", module);
384             OrderByList orderByList = new OrderByList(orderBy);
385             orderByList.checkOrderBy(modelEntity);
386             orderByList.makeOrderByString(sql, modelEntity, includeTablenamePrefix, datasourceInfo);
387         }
388         if (Debug.verboseOn()) Debug.logVerbose("makeOrderByClause: " + sql.toString(), module);
389         return sql.toString();
390     }
391
392     public static String JavaDoc makeViewTable(ModelEntity modelEntity, DatasourceInfo datasourceInfo) throws GenericEntityException {
393         if (modelEntity instanceof ModelViewEntity) {
394             StringBuffer JavaDoc sql = new StringBuffer JavaDoc("(SELECT ");
395             Iterator JavaDoc fieldsIter = modelEntity.getFieldsIterator();
396             if (fieldsIter.hasNext()) {
397                 ModelField curField = (ModelField) fieldsIter.next();
398                 String JavaDoc colname = curField.getColName();
399                 sql.append(colname);
400                 sql.append(" AS ");
401                 sql.append(filterColName(colname));
402                 while (fieldsIter.hasNext()) {
403                     curField = (ModelField) fieldsIter.next();
404                     colname = curField.getColName();
405                     sql.append(", ");
406                     sql.append(colname);
407                     sql.append(" AS ");
408                     sql.append(filterColName(colname));
409                 }
410             }
411             sql.append(makeFromClause(modelEntity, datasourceInfo));
412             String JavaDoc viewWhereClause = makeViewWhereClause(modelEntity, datasourceInfo.joinStyle);
413             if (UtilValidate.isNotEmpty(viewWhereClause)) {
414                 sql.append(" WHERE ");
415                 sql.append(viewWhereClause);
416             }
417             ModelViewEntity modelViewEntity = (ModelViewEntity)modelEntity;
418             String JavaDoc groupByString = modelViewEntity.colNameString(modelViewEntity.getGroupBysCopy(), ", ", "", false);
419             if (UtilValidate.isNotEmpty(groupByString)) {
420                 sql.append(" GROUP BY ");
421                 sql.append(groupByString);
422             }
423
424             sql.append(")");
425             return sql.toString();
426         } else {
427             return modelEntity.getTableName(datasourceInfo);
428         }
429     }
430
431     public static String JavaDoc filterColName(String JavaDoc colName) {
432         return colName.replace('.', '_').replace('(','_').replace(')','_');
433     }
434
435     /* ====================================================================== */
436
437     /* ====================================================================== */
438
439     /**
440      * The elements (ModelFields) of the list are bound to an SQL statement
441      * (SQL-Processor)
442      *
443      * @param sqlP
444      * @param list
445      * @param entity
446      * @throws GenericEntityException
447      */

448     public static void setValues(SQLProcessor sqlP, List JavaDoc list, GenericEntity entity, ModelFieldTypeReader modelFieldTypeReader) throws GenericEntityException {
449         Iterator JavaDoc fieldIter = list.iterator();
450         while (fieldIter.hasNext()) {
451             ModelField curField = (ModelField) fieldIter.next();
452             setValue(sqlP, curField, entity, modelFieldTypeReader);
453         }
454     }
455
456     /**
457      * The elements (ModelFields) of the list are bound to an SQL statement
458      * (SQL-Processor), but values must not be null.
459      *
460      * @param sqlP
461      * @param list
462      * @param dummyValue
463      * @param modelFieldTypeReader
464      * @throws GenericEntityException
465      */

466     public static void setValuesWhereClause(SQLProcessor sqlP, List JavaDoc list, GenericValue dummyValue, ModelFieldTypeReader modelFieldTypeReader) throws GenericEntityException {
467         Iterator JavaDoc fieldIter = list.iterator();
468         while (fieldIter.hasNext()) {
469             ModelField curField = (ModelField) fieldIter.next();
470             // for where clause variables only setValue if not null...
471
if (dummyValue.get(curField.getName()) != null) {
472                 setValue(sqlP, curField, dummyValue, modelFieldTypeReader);
473             }
474         }
475     }
476
477     /**
478      * Get all primary keys from the model entity and bind their values
479      * to the an SQL statement (SQL-Processor)
480      *
481      * @param sqlP
482      * @param modelEntity
483      * @param entity
484      * @param modelFieldTypeReader
485      * @throws GenericEntityException
486      */

487     public static void setPkValues(SQLProcessor sqlP, ModelEntity modelEntity, GenericEntity entity, ModelFieldTypeReader modelFieldTypeReader) throws GenericEntityException {
488         Iterator JavaDoc pksIter = modelEntity.getPksIterator();
489         while (pksIter.hasNext()) {
490             ModelField curField = (ModelField) pksIter.next();
491
492             // for where clause variables only setValue if not null...
493
if (entity.dangerousGetNoCheckButFast(curField) != null) {
494                 setValue(sqlP, curField, entity, modelFieldTypeReader);
495             }
496         }
497     }
498
499     public static void getValue(ResultSet JavaDoc rs, int ind, ModelField curField, GenericEntity entity, ModelFieldTypeReader modelFieldTypeReader) throws GenericEntityException {
500         ModelFieldType mft = modelFieldTypeReader.getModelFieldType(curField.getType());
501
502         if (mft == null) {
503             throw new GenericModelException("definition fieldType " + curField.getType() + " not found, cannot getValue for field " +
504                     entity.getEntityName() + "." + curField.getName() + ".");
505         }
506         String JavaDoc fieldType = mft.getJavaType();
507
508         try {
509             // checking to see if the object is null is really only necessary for the numbers
510
int typeValue = getType(fieldType);
511             ResultSetMetaData JavaDoc rsmd = rs.getMetaData();
512             int colType = rsmd.getColumnType(ind);
513             
514             if (typeValue <= 4 || typeValue >= 11) {
515                 switch (typeValue) {
516                 case 1:
517                     if (java.sql.Types.CLOB == colType) {
518                         // Debug.logInfo("For field " + curField.getName() + " of entity " + entity.getEntityName() + " getString is a CLOB, trying getCharacterStream", module);
519
// if the String is empty, try to get a text input stream, this is required for some databases for larger fields, like CLOBs
520

521                         Clob JavaDoc valueClob = rs.getClob(ind);
522                         Reader JavaDoc valueReader = null;
523                         if (valueClob != null) {
524                             valueReader = valueClob.getCharacterStream();
525                         }
526                         
527                         //Reader valueReader = rs.getCharacterStream(ind);
528
if (valueReader != null) {
529                             char[] inCharBuffer = new char[CHAR_BUFFER_SIZE];
530                             StringBuffer JavaDoc strBuf = new StringBuffer JavaDoc();
531                             int charsRead = 0;
532                             try {
533                                 while ((charsRead = valueReader.read(inCharBuffer, 0, CHAR_BUFFER_SIZE)) > 0) {
534                                     strBuf.append(inCharBuffer, 0, charsRead);
535                                 }
536                                 valueReader.close();
537                             } catch (IOException JavaDoc e) {
538                                 throw new GenericEntityException("Error reading long character stream for field " + curField.getName() + " of entity " + entity.getEntityName(), e);
539                             }
540                             entity.dangerousSetNoCheckButFast(curField, strBuf.toString());
541                         } else {
542                             entity.dangerousSetNoCheckButFast(curField, null);
543                         }
544                     } else {
545                         String JavaDoc value = rs.getString(ind);
546                         entity.dangerousSetNoCheckButFast(curField, value);
547                     }
548                     break;
549
550                 case 2:
551                     entity.dangerousSetNoCheckButFast(curField, rs.getTimestamp(ind));
552                     break;
553
554                 case 3:
555                     entity.dangerousSetNoCheckButFast(curField, rs.getTime(ind));
556                     break;
557
558                 case 4:
559                     entity.dangerousSetNoCheckButFast(curField, rs.getDate(ind));
560                     break;
561
562                 case 11:
563                     Object JavaDoc obj = null;
564                     InputStream JavaDoc binaryInput = null;
565
566                     byte[] fieldBytes = rs.getBytes(ind);
567                     if (fieldBytes != null && fieldBytes.length > 0) {
568                         binaryInput = new ByteArrayInputStream JavaDoc(fieldBytes);
569                     }
570
571                     if (fieldBytes != null && fieldBytes.length <= 0) {
572                         Debug.logWarning("Got bytes back for Object field with length: " + fieldBytes.length + " while getting value : " + curField.getName() + " [" + curField.getColName() + "] (" + ind + "): ", module);
573                     }
574
575                     //alt 1: binaryInput = rs.getBinaryStream(ind);
576
//alt 2: Blob blobLocator = rs.getBlob(ind);
577
//if (blobLocator != null) {
578
// binaryInput = blobLocator.getBinaryStream();
579
//}
580

581                     if (binaryInput != null) {
582                         ObjectInputStream JavaDoc in = null;
583                         try {
584                             in = new ObjectInputStream JavaDoc(binaryInput);
585                             obj = in.readObject();
586                         } catch (IOException JavaDoc ex) {
587                             throw new GenericDataSourceException("Unable to read BLOB data from input stream while getting value : " + curField.getName() + " [" + curField.getColName() + "] (" + ind + "): " + ex.toString(), ex);
588                         } catch (ClassNotFoundException JavaDoc ex) {
589                             throw new GenericDataSourceException("Class not found: Unable to cast BLOB data to an Java object while getting value : " + curField.getName() + " [" + curField.getColName() + "] (" + ind + "): " + ex.toString(), ex);
590                         } finally {
591                             if (in != null) {
592                                 try {
593                                     in.close();
594                                 } catch (IOException JavaDoc e) {
595                                     throw new GenericDataSourceException("Unable to close binary input stream while getting value : " + curField.getName() + " [" + curField.getColName() + "] (" + ind + "): " + e.toString(), e);
596                                 }
597                             }
598                         }
599                     }
600
601                     binaryInput = null;
602                     entity.dangerousSetNoCheckButFast(curField, obj);
603                     break;
604                 case 12:
605                     entity.dangerousSetNoCheckButFast(curField, rs.getBlob(ind));
606                     break;
607                 case 13:
608                     entity.dangerousSetNoCheckButFast(curField, rs.getClob(ind));
609                     break;
610                 case 14:
611                 case 15:
612                     entity.dangerousSetNoCheckButFast(curField, rs.getObject(ind));
613                     break;
614                 }
615             } else {
616                 switch (typeValue) {
617                 case 5:
618                     int intValue = rs.getInt(ind);
619                     if (rs.wasNull()) {
620                         entity.dangerousSetNoCheckButFast(curField, null);
621                     } else {
622                         entity.dangerousSetNoCheckButFast(curField, new Integer JavaDoc(intValue));
623                     }
624                     break;
625
626                 case 6:
627                     long longValue = rs.getLong(ind);
628                     if (rs.wasNull()) {
629                         entity.dangerousSetNoCheckButFast(curField, null);
630                     } else {
631                         entity.dangerousSetNoCheckButFast(curField, new Long JavaDoc(longValue));
632                     }
633                     break;
634
635                 case 7:
636                     float floatValue = rs.getFloat(ind);
637                     if (rs.wasNull()) {
638                         entity.dangerousSetNoCheckButFast(curField, null);
639                     } else {
640                         entity.dangerousSetNoCheckButFast(curField, new Float JavaDoc(floatValue));
641                     }
642                     break;
643
644                 case 8:
645                     double doubleValue = rs.getDouble(ind);
646                     if (rs.wasNull()) {
647                         entity.dangerousSetNoCheckButFast(curField, null);
648                     } else {
649                         entity.dangerousSetNoCheckButFast(curField, new Double JavaDoc(doubleValue));
650                     }
651                     break;
652
653                 case 9:
654                     BigDecimal JavaDoc bigDecimalValue = rs.getBigDecimal(ind);
655                     if (rs.wasNull()) {
656                         entity.dangerousSetNoCheckButFast(curField, null);
657                     } else {
658                         entity.dangerousSetNoCheckButFast(curField, bigDecimalValue);
659                     }
660                     break;
661
662                 case 10:
663                     boolean booleanValue = rs.getBoolean(ind);
664                     if (rs.wasNull()) {
665                         entity.dangerousSetNoCheckButFast(curField, null);
666                     } else {
667                         entity.dangerousSetNoCheckButFast(curField, new Boolean JavaDoc(booleanValue));
668                     }
669                     break;
670                 }
671             }
672         } catch (SQLException JavaDoc sqle) {
673             throw new GenericDataSourceException("SQL Exception while getting value : " + curField.getName() + " [" + curField.getColName() + "] (" + ind + ")", sqle);
674         }
675     }
676
677     public static void setValue(SQLProcessor sqlP, ModelField modelField, GenericEntity entity, ModelFieldTypeReader modelFieldTypeReader) throws GenericEntityException {
678         Object JavaDoc fieldValue = entity.dangerousGetNoCheckButFast(modelField);
679
680         setValue(sqlP, modelField, entity.getEntityName(), fieldValue, modelFieldTypeReader);
681     }
682
683     public static void setValue(SQLProcessor sqlP, ModelField modelField, String JavaDoc entityName, Object JavaDoc fieldValue, ModelFieldTypeReader modelFieldTypeReader) throws GenericEntityException {
684         ModelFieldType mft = modelFieldTypeReader.getModelFieldType(modelField.getType());
685
686         if (mft == null) {
687             throw new GenericModelException("GenericDAO.getValue: definition fieldType " + modelField.getType() + " not found, cannot setValue for field " +
688                     entityName + "." + modelField.getName() + ".");
689         }
690         
691         // if the value is the GenericEntity.NullField, treat as null
692
if (fieldValue == GenericEntity.NULL_FIELD) {
693             fieldValue = null;
694         }
695
696         String JavaDoc fieldType = mft.getJavaType();
697         if (fieldValue != null) {
698             if (!ObjectType.instanceOf(fieldValue, fieldType)) {
699                 // this is only an info level message because under normal operation for most JDBC
700
// drivers this will be okay, but if not then the JDBC driver will throw an exception
701
// and when lower debug levels are on this should help give more info on what happened
702
Class JavaDoc fieldClass = fieldValue.getClass();
703                 String JavaDoc fieldClassName = fieldClass.getName();
704
705                 if (Debug.verboseOn()) Debug.logVerbose("type of field " + entityName + "." + modelField.getName() +
706                         " is " + fieldClassName + ", was expecting " + mft.getJavaType() + "; this may " +
707                         "indicate an error in the configuration or in the class, and may result " +
708                         "in an SQL-Java data conversion error. Will use the real field type: " +
709                         fieldClassName + ", not the definition.", module);
710                 fieldType = fieldClassName;
711             }
712         }
713
714         try {
715             int typeValue = getType(fieldType);
716
717             switch (typeValue) {
718             case 1:
719                 sqlP.setValue((String JavaDoc) fieldValue);
720                 break;
721
722             case 2:
723                 sqlP.setValue((java.sql.Timestamp JavaDoc) fieldValue);
724                 break;
725
726             case 3:
727                 sqlP.setValue((java.sql.Time JavaDoc) fieldValue);
728                 break;
729
730             case 4:
731                 sqlP.setValue((java.sql.Date JavaDoc) fieldValue);
732                 break;
733
734             case 5:
735                 sqlP.setValue((java.lang.Integer JavaDoc) fieldValue);
736                 break;
737
738             case 6:
739                 sqlP.setValue((java.lang.Long JavaDoc) fieldValue);
740                 break;
741
742             case 7:
743                 sqlP.setValue((java.lang.Float JavaDoc) fieldValue);
744                 break;
745
746             case 8:
747                 sqlP.setValue((java.lang.Double JavaDoc) fieldValue);
748                 break;
749
750             case 9:
751                 sqlP.setValue((java.math.BigDecimal JavaDoc) fieldValue);
752                 break;
753
754             case 10:
755                 sqlP.setValue((java.lang.Boolean JavaDoc) fieldValue);
756                 break;
757
758             case 11:
759                 sqlP.setBinaryStream(fieldValue);
760                 break;
761
762             case 12:
763                 sqlP.setValue((java.sql.Blob JavaDoc) fieldValue);
764                 break;
765
766             case 13:
767                 sqlP.setValue((java.sql.Clob JavaDoc) fieldValue);
768                 break;
769
770             case 14:
771                 sqlP.setValue(new java.sql.Date JavaDoc(((java.util.Date JavaDoc) fieldValue).getTime()));
772                 break;
773
774             case 15:
775                 sqlP.setValue((java.util.Collection JavaDoc) fieldValue);
776                 break;
777             }
778         } catch (GenericNotImplementedException e) {
779             throw new GenericNotImplementedException("Not Implemented Exception while setting value on field [" + modelField.getName() + "] of entity " + entityName + ": " + e.toString(), e);
780         } catch (SQLException JavaDoc sqle) {
781             throw new GenericDataSourceException("SQL Exception while setting value on field [" + modelField.getName() + "] of entity " + entityName + ": ", sqle);
782         }
783     }
784
785     protected static Map JavaDoc fieldTypeMap = FastMap.newInstance();
786     static {
787         fieldTypeMap.put("java.lang.String", new Integer JavaDoc(1));
788         fieldTypeMap.put("String", new Integer JavaDoc(1));
789         fieldTypeMap.put("java.sql.Timestamp", new Integer JavaDoc(2));
790         fieldTypeMap.put("Timestamp", new Integer JavaDoc(2));
791         fieldTypeMap.put("java.sql.Time", new Integer JavaDoc(3));
792         fieldTypeMap.put("Time", new Integer JavaDoc(3));
793         fieldTypeMap.put("java.sql.Date", new Integer JavaDoc(4));
794         fieldTypeMap.put("Date", new Integer JavaDoc(4));
795         fieldTypeMap.put("java.lang.Integer", new Integer JavaDoc(5));
796         fieldTypeMap.put("Integer", new Integer JavaDoc(5));
797         fieldTypeMap.put("java.lang.Long", new Integer JavaDoc(6));
798         fieldTypeMap.put("Long", new Integer JavaDoc(6));
799         fieldTypeMap.put("java.lang.Float", new Integer JavaDoc(7));
800         fieldTypeMap.put("Float", new Integer JavaDoc(7));
801         fieldTypeMap.put("java.lang.Double", new Integer JavaDoc(8));
802         fieldTypeMap.put("Double", new Integer JavaDoc(8));
803         fieldTypeMap.put("java.math.BigDecimal", new Integer JavaDoc(9));
804         fieldTypeMap.put("BigDecimal", new Integer JavaDoc(9));
805         fieldTypeMap.put("java.lang.Boolean", new Integer JavaDoc(10));
806         fieldTypeMap.put("Boolean", new Integer JavaDoc(10));
807         
808         fieldTypeMap.put("java.lang.Object", new Integer JavaDoc(11));
809         fieldTypeMap.put("Object", new Integer JavaDoc(11));
810         fieldTypeMap.put("java.sql.Blob", new Integer JavaDoc(12));
811         fieldTypeMap.put("Blob", new Integer JavaDoc(12));
812         fieldTypeMap.put("java.sql.Clob", new Integer JavaDoc(13));
813         fieldTypeMap.put("Clob", new Integer JavaDoc(13));
814
815         fieldTypeMap.put("java.util.Date", new Integer JavaDoc(14));
816
817         // all of these treated as Collection
818
fieldTypeMap.put("java.util.ArrayList", new Integer JavaDoc(15));
819         fieldTypeMap.put("java.util.HashSet", new Integer JavaDoc(15));
820         fieldTypeMap.put("java.util.LinkedHashSet", new Integer JavaDoc(15));
821         fieldTypeMap.put("java.util.LinkedList", new Integer JavaDoc(15));
822     }
823
824     public static int getType(String JavaDoc fieldType) throws GenericNotImplementedException {
825         Integer JavaDoc val = (Integer JavaDoc) fieldTypeMap.get(fieldType);
826
827         if (val == null) {
828             throw new GenericNotImplementedException("Java type " + fieldType + " not currently supported. Sorry.");
829         }
830         return val.intValue();
831     }
832
833     public static void addValueSingle(StringBuffer JavaDoc buffer, ModelField field, Object JavaDoc value, List JavaDoc params) {
834         if (field != null) {
835             buffer.append('?');
836         } else {
837             buffer.append('\'').append(value).append('\'');
838         }
839         if (field != null && params != null) params.add(new EntityConditionParam(field, value));
840     }
841
842     public static void addValue(StringBuffer JavaDoc buffer, ModelField field, Object JavaDoc value, List JavaDoc params) {
843         if (value instanceof Collection JavaDoc) {
844             buffer.append("( ");
845             Iterator JavaDoc it = ((Collection JavaDoc) value).iterator();
846             while (it.hasNext()) {
847                 Object JavaDoc thisValue = it.next();
848                 addValueSingle(buffer, field, thisValue, params);
849                 if (it.hasNext()) buffer.append(", ");
850             }
851             buffer.append(" )");
852         } else {
853             addValueSingle(buffer, field, value, params);
854         }
855     }
856 }
857
Popular Tags