KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jspPhoneBook > data > PersonQuery


1
2 /*-----------------------------------------------------------------------------
3  * Enhydra Java Application Server
4  * Copyright 1997-2000 Lutris Technologies, Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  * notice, this list of conditions and the following disclaimer in
14  * the documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  * must display the following acknowledgement:
17  * This product includes Enhydra software developed by Lutris
18  * Technologies, Inc. and its contributors.
19  * 4. Neither the name of Lutris Technologies nor the names of its contributors
20  * may be used to endorse or promote products derived from this software
21  * without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY LUTRIS TECHNOLOGIES AND CONTRIBUTORS ``AS IS''
24  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED. IN NO EVENT SHALL LUTRIS TECHNOLOGIES OR CONTRIBUTORS BE
27  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGE.
34  *-----------------------------------------------------------------------------
35  * phoneList.data/PersonQuery.java
36  *-----------------------------------------------------------------------------
37  */

38
39 package jspPhoneBook.data;
40
41 import org.enhydra.dods.DODS;
42 import com.lutris.dods.builder.generator.query.*;
43 import com.lutris.appserver.server.sql.*;
44 import org.enhydra.dods.cache.LRUCache;
45 import org.enhydra.dods.cache.DataStructCache;
46 import org.enhydra.dods.cache.QueryCache;
47 import org.enhydra.dods.cache.QueryCacheItem;
48 import org.enhydra.dods.cache.QueryResult;
49 import org.enhydra.dods.cache.DataStructShell;
50 import org.enhydra.dods.cache.DOShell;
51 import org.enhydra.dods.cache.Condition;
52 import org.enhydra.dods.statistics.Statistics;
53 import org.enhydra.dods.cache.CacheConstants;
54 import org.enhydra.dods.statistics.*;
55 import com.lutris.logging.LogChannel;
56 import com.lutris.logging.Logger;
57 import com.lutris.appserver.server.sql.standard.StandardDBTransaction;
58
59 import java.sql.*;
60 import java.util.*;
61 import java.math.*;
62 import java.util.Date JavaDoc; // when I say Date, I don't mean java.sql.Date
63

64 /**
65  * PersonQuery is used to query the person table in the database.<BR>
66  * It returns objects of type PersonDO.
67  * <P>
68  * General usage:
69  * <P>
70  * In DODS:
71  * Create a Data Object named "Dog",
72  * and create an Attribute named "Name",
73  * and set that Attribute to "Can be queried."
74  * DODS will then generate the method DogQuery.setQueryName().
75  * <P>
76  * In your Business Layer, prepare the query:<BR>
77  * <P><PRE>
78  * DogQuery dq = new DogQuery();
79  * dq.setQueryName("Rex")
80  * if ( Rex is a reserved name )
81  * dq.requireUniqueInstance();
82  * </PRE>
83  * Then, get the query results one of two ways:
84  * <P>
85  * #1:<PRE>
86  * String names = "";
87  * DogDO[] dogs = dq.getDOArray();
88  * for ( int i = 0; i < dogs.length; i++ ) {
89  * names += dogs[i].getName() + " ";
90  * }
91  * </PRE>
92  * or #2:<PRE>
93  * String names = "";
94  * DogDO dog;
95  * while ( null != ( dog = dq.getNextDO() ) ) {
96  * names += dog.getName() + " ";
97  * }
98  * </PRE>
99  * <P>
100  * Note: If <CODE>requireUniqueInstance()</CODE> was called,
101  * then <CODE>getDOArray()</CODE> or <CODE>getNextDO()</CODE>
102  * will throw an exception if more than one "Rex" was found.
103  * <P>
104  * Note: Results of the query will come from the Data Object cache if:
105  * - The cache is available.
106  * - Matches were found in the cache.
107  * - No other tables (Data Objects of other types) were involved
108  * in the query.
109  * This can happen if you extend the <CODE>DogQuery</CODE> class
110  * and you make calls to the <CODE>QueryBuilder</CODE> object
111  * to add SQL involving other tables.
112  * If any of these conditions is not true,
113  * then any results from the query will come from the database.
114  * <P>
115  * To reuse the query object, call:
116  * <P><PRE>
117  * dq.reset();
118  * </PRE>
119  * @author EnhydraTeam
120  * @version $Revision: 1.1 $
121  */

122 public class PersonQuery implements Query {
123
124     private QueryBuilder builder;
125
126     /**
127      * logical name of the database for which PersonQuery object has been created
128      */

129     private String JavaDoc logicalDatabase;
130
131     private ResultSet resultSet = null;
132     private boolean uniqueInstance = false;
133     private boolean loadData = false;
134     private PersonDO[] DOs = null;
135     private int arrayIndex = -1;
136     private boolean needToRun = true;
137     private LinkedHashMap cacheHits = null;
138     private boolean isQueryByOId = false;
139     private boolean hasNonOidCond = false;
140     private boolean hitDb = false;
141     private boolean userHitDb = false;
142     private int maxDBrows = 0;
143     private boolean orderRelevant = true; // true if order of query results is relavant, otherwise false
144
private QueryCacheItem queryItem = null;
145     private String JavaDoc currentHandle = null;
146     private HashMap refs = new HashMap();
147         private int iCurrentFetchSize = -1;
148         private int iCurrentQueryTimeout = 0;
149     private DBTransaction transaction = null;
150
151     /**
152      * Public constructor.
153          *
154
155      */

156     public PersonQuery() {
157
158         builder = new QueryBuilder( "person", "person.*" );
159
160         String JavaDoc dbName = PersonDO.get_logicalDBName();
161         try {
162             String JavaDoc vendor = DODS.getDatabaseManager().logicalDatabaseType(dbName);
163             if (vendor != null) {
164                 builder.setDatabaseVendor(vendor);
165                 logicalDatabase = dbName;
166             } else {
167                 builder.setDatabaseVendor();
168                 logicalDatabase = DODS.getDatabaseManager().getDefaultDB();
169             }
170         } catch (Exception JavaDoc e) {
171             builder.setDatabaseVendor();
172             logicalDatabase = DODS.getDatabaseManager().getDefaultDB();
173         }
174         builder.setUserStringAppendWildcard( false );
175         builder.setUserStringTrim( false );
176         reset();
177     }
178
179     /**
180      * Public constructor.
181          *
182      * @param dbTrans current database transaction
183      */

184     public PersonQuery(DBTransaction dbTrans) {
185
186         builder = new QueryBuilder( "person", "person.*" );
187
188         String JavaDoc dbName = null;
189         if(dbTrans!=null)
190             dbName = dbTrans.getDatabaseName();
191         else
192             dbName = PersonDO.get_logicalDBName();
193         try {
194             transaction = dbTrans;
195             String JavaDoc vendor = DODS.getDatabaseManager().logicalDatabaseType(dbName);
196             if (vendor != null) {
197                 builder.setDatabaseVendor(vendor);
198                 logicalDatabase = dbName;
199             } else {
200                 builder.setDatabaseVendor();
201                 logicalDatabase = DODS.getDatabaseManager().getDefaultDB();
202             }
203         } catch (Exception JavaDoc e) {
204             builder.setDatabaseVendor();
205             logicalDatabase = DODS.getDatabaseManager().getDefaultDB();
206         }
207         builder.setUserStringAppendWildcard( false );
208         builder.setUserStringTrim( false );
209         reset();
210     }
211
212
213
214     /**
215      * Return logical name of the database that PersonQuery object uses
216      *
217      * @return param logical database name
218      *
219      */

220     public String JavaDoc getLogicalDatabase() {
221         return logicalDatabase;
222     }
223
224     /**
225      * Change logical database to another logical database (which name is dbName)
226      *
227      * @param dbName the logical name of the database
228      *
229      */

230     public void setLogicalDatabase(String JavaDoc dbName) throws SQLException, DatabaseManagerException {
231         String JavaDoc vendor = DODS.getDatabaseManager().logicalDatabaseType(dbName);
232         if (vendor != null) {
233             builder.setDatabaseVendor(vendor);
234             logicalDatabase = dbName;
235         } else {
236             builder.setDatabaseVendor();
237             logicalDatabase = DODS.getDatabaseManager().getDefaultDB();
238         }
239         reset();
240     }
241
242
243
244     // WebDocWf extension for unique query results without SQL DISTINCT
245
// The following lines has been added:
246
private boolean unique = false;
247
248     /**
249      * Set the unique flag of the query
250      *
251      * @param newUnique The unique flag for the query
252      *
253      * WebDocWf extension
254      *
255      */

256     public void setUnique(boolean newUnique) { unique = newUnique; }
257
258     /**
259      * Get the unique flag of the query
260      *
261      * @return The unique flag of the query
262      *
263      * WebDocWf extension
264      *
265      */

266     public boolean getUnique() { return unique; }
267
268     // WebDocWf extension for skipping the n first rows of the result
269
// The following lines has been added:
270
private int readSkip = 0;
271
272     /**
273      * Set the readSkip number of the query
274      *
275      * @param newreadSkip The number of results to skip
276      *
277      * WebDocWf extension
278      *
279      */

280     public void setReadSkip(int newReadSkip) {
281       readSkip = newReadSkip;
282     }
283
284     /**
285      * Get the readSkip number of the query
286      *
287      * @return The number of rows which are skipped
288      *
289      * WebDocWf extension
290      *
291      */

292     public int getReadSkip() { return readSkip; }
293
294     // WebDocWf extension for select rowcount limit
295
// The following lines has been added:
296
private int databaseLimit = 0;
297
298     /**
299      * Set the database limit of the query
300      *
301      * @param newLimit The limit for the query
302      *
303      * WebDocWf extension
304      *
305      */

306     public void setDatabaseLimit(int newLimit) {
307       databaseLimit = newLimit;
308     }
309
310     /**
311      * Get the database limit of the query
312      *
313      * @return The database limit of the query
314      *
315      * WebDocWf extension
316      *
317      */

318     public int getDatabaseLimit() { return databaseLimit; }
319
320     private boolean databaseLimitExceeded = false;
321
322     /**
323      * Get the database limit exceeded flag of the query.
324      *
325      * @return The database limit exceeded flag of the query
326      * True if there would have been more rows than the limit, otherwise false.
327      *
328      * WebDocWf extension
329      */

330     public boolean getDatabaseLimitExceeded() { return databaseLimitExceeded; }
331     // end of WebDocWf extension for select rowcount limit
332

333     /**
334      * Set that all queries go to database, not to cache.
335      */

336     public void hitDatabase() { userHitDb = true; }
337
338     // WebDocWf extension for extended wildcard support
339
// The following rows have been added:
340

341     /**
342      * Set user string wildcard.
343      *
344      * @param newUserStringWildcard New user string wildcard.
345      *
346      * WebDocWf extension
347      */

348     public void setUserStringWildcard(String JavaDoc newUserStringWildcard) {
349         builder.setUserStringWildcard( newUserStringWildcard );
350     }
351
352     /**
353      * Set user string single wildcard.
354      *
355      * @param newUserStringSingleWildcard New user string single wildcard.
356      *
357      * WebDocWf extension
358      */

359     public void setUserStringSingleWildcard(String JavaDoc newUserStringSingleWildcard) {
360         builder.setUserStringSingleWildcard( newUserStringSingleWildcard );
361     }
362
363     /**
364      * Set user string single wildcard escape.
365      *
366      * @param newUserStringSingleWildcardEscape New user string single wildcard escape.
367      *
368      * WebDocWf extension
369      */

370     public void setUserStringSingleWildcardEscape(String JavaDoc newUserStringSingleWildcardEscape) {
371         builder.setUserStringSingleWildcardEscape( newUserStringSingleWildcardEscape );
372     }
373
374     /**
375      * Set user string wildcard escape.
376      *
377      * @param newUserStringWildcardEscape New user string wildcard escape.
378      *
379      * WebDocWf extension
380      */

381     public void setUserStringWildcardEscape(String JavaDoc newUserStringWildcardEscape) {
382         builder.setUserStringWildcardEscape( newUserStringWildcardEscape );
383     }
384
385     /**
386      * Set user string append wildcard.
387      *
388      * @param userStringAppendWildcard New user string append wildcard.
389      *
390      * WebDocWf extension
391      */

392     public void setUserStringAppendWildcard(boolean userStringAppendWildcard ) {
393         builder.setUserStringAppendWildcard( userStringAppendWildcard );
394     }
395
396      /**
397      * Set user string trim.
398      *
399      * @param userStringTrim New user string trim.
400      *
401      * WebDocWf extension
402      */

403     public void setUserStringTrim(boolean userStringTrim ) {
404         builder.setUserStringTrim( userStringTrim );
405     }
406
407     /**
408      * Get user string wildcard.
409      *
410      * @return User string wildcard.
411      *
412      * WebDocWf extension
413      */

414     public String JavaDoc getUserStringWildcard() {
415         return builder.getUserStringWildcard();
416     }
417
418     /**
419      * Get user string single wildcard.
420      *
421      * @return User string single wildcard.
422      *
423      * WebDocWf extension
424      */

425     public String JavaDoc getUserStringSingleWildcard() {
426         return builder.getUserStringSingleWildcard();
427     }
428
429     /**
430      * Get user string single wildcard escape.
431      *
432      * @return User string single wildcard escape.
433      *
434      * WebDocWf extension
435      */

436     public String JavaDoc getUserStringSingleWildcardEscape() {
437         return builder.getUserStringSingleWildcardEscape();
438     }
439
440     /**
441      * Get user string wildcard escape.
442      *
443      * @return User string wildcard escape.
444      *
445      * WebDocWf extension
446      */

447     public String JavaDoc getUserStringWildcardEscape() {
448         return builder.getUserStringWildcardEscape();
449     }
450
451     /**
452      * Get user string append wildcard.
453      *
454      * @return User string append wildcard.
455      *
456      * WebDocWf extension
457      */

458     public boolean getUserStringAppendWildcard() {
459         return builder.getUserStringAppendWildcard();
460     }
461
462     /**
463      * Get user string trim.
464      *
465      * @return User string trim.
466      *
467      * WebDocWf extension
468      */

469     public boolean getUserStringTrim() {
470         return builder.getUserStringTrim();
471     }
472     // end of WebDocWf extension for extended wildcard support
473

474     /**
475      * Perform the query on the database, and prepare the
476      * array of returned DO objects.
477      *
478      * @exception DataObjectException If a database access error occurs.
479      * @exception NonUniqueQueryException If too many rows were found.
480      */

481     private void getQueryByOIds(Vector DOs)
482     throws DataObjectException {
483         if (DOs.size() == 0)
484             return;
485         PersonDO DO = null;
486         DOShell shell = null;
487         PersonQuery tmpQuery = null;
488         Date JavaDoc startQueryTime = new Date JavaDoc();
489         long queryTime = 0;
490         for (int i=0; i<DOs.size(); i++) {
491             shell = (DOShell)DOs.elementAt(i);
492             tmpQuery = new PersonQuery(transaction);
493             try {
494              tmpQuery.setQueryHandle( shell.handle );
495              tmpQuery.requireUniqueInstance();
496
497              DO = tmpQuery.getNextDO();
498              if ( null == DO )
499                     throw new DataObjectException("PersonDO DO not found for id=" + shell.handle );
500             } catch ( Exception JavaDoc e ) {
501                throw new DataObjectException( "Duplicate ObjectId" );
502             }
503             shell.dataObject = DO;
504         }
505         Date JavaDoc stopQueryTime = new Date JavaDoc();
506         queryTime = stopQueryTime.getTime() - startQueryTime.getTime();
507         PersonDO.statistics.updateQueryByOIdAverageTime((new Long JavaDoc(queryTime)).intValue(),DOs.size());
508     }
509
510
511
512     /**
513      * Perform the query on the database, and prepare the
514      * array of returned DO objects.
515      *
516      * @exception DataObjectException If a database access error occurs.
517      * @exception NonUniqueQueryException If too many rows were found.
518      */

519     private void runQuery()
520     throws DataObjectException, NonUniqueQueryException {
521         needToRun = false;
522         arrayIndex = -1;
523         DBQuery dbQuery = null;
524         Date JavaDoc startQueryTime = new Date JavaDoc();
525         long queryTime = 0;
526         boolean readDOs = false;
527         boolean canUseQueryCache = true;
528         CacheStatistics stat = null;
529         boolean resultsFromQCache = false;
530         QueryCacheItem queryCachedItem = null;
531
532         if ((transaction!=null) &&
533         (transaction instanceof com.lutris.appserver.server.sql.standard.StandardDBTransaction)) {
534         if(((com.lutris.appserver.server.sql.standard.StandardDBTransaction)transaction).getAutoWrite()) try {
535             transaction.write();
536         } catch (SQLException sqle) {
537             sqle.printStackTrace();
538             throw new DataObjectException("Couldn't write transaction: "+sqle);
539         }
540         ((com.lutris.appserver.server.sql.standard.StandardDBTransaction)transaction).dontAggregateDOModifications();
541         }
542
543         try {
544             QueryResult results = null;
545             DOShell shell = null;
546             if (isQueryByOId && !hasNonOidCond) { // query by OId
547
results = new QueryResult();
548                 if (currentHandle != null) {
549                     if(transaction!=null && _tr_(transaction).getTransactionCache()!=null && !loadData) {
550                          PersonDO DO= (PersonDO)_tr_(transaction).getTransactionCache().getDOByHandle(currentHandle);
551                          if(DO!=null){
552                             shell = new DOShell(DO);
553                             results.DOs.add(shell);
554                             resultsFromQCache = true;
555                          }
556                          else
557                             resultsFromQCache = false;
558                     }
559                     if(!resultsFromQCache) { // DO isn't found in the transaction cache
560
PersonDataStruct DS = (PersonDataStruct)PersonDO.cache.getDataStructByHandle(currentHandle);
561                         if (DS != null) { // DO is found in the cache
562
PersonDO DO = (PersonDO)PersonDO.createExisting(DS.get_OId(), transaction);
563                           shell = new DOShell(DO);
564                           results.DOs.add(shell);
565                           resultsFromQCache = true;
566                          }else{ // DO isn't found in the cache
567
if (PersonDO.cache.isFull())
568                                  resultsFromQCache = false;
569                          }
570                     }
571                 }//currentHandle != null
572
}
573             else { // other queries
574
if ((PersonDO.cache.isFull()) && (!hitDb)) {
575                       resultsFromQCache = true;
576                 }
577                 else {
578                  if (PersonDO.cache.getLevelOfCaching() == CacheConstants.QUERY_CACHING) {
579                     if (hitDb) { // statistics about complex query
580
stat = null;
581                           stat = PersonDO.statistics.getCacheStatistics(CacheConstants.COMPLEX_QUERY_CACHE);
582                           if (stat!= null){
583                              stat.incrementCacheAccessNum(1);
584                           }
585                       }else{ // statistics about simple query
586
stat = null;
587                           stat = PersonDO.statistics.getCacheStatistics(CacheConstants.SIMPLE_QUERY_CACHE);
588                           if (stat!= null){
589                              stat.incrementCacheAccessNum(1);
590                           }
591                      }
592                  }
593                  if(transaction != null)
594                     canUseQueryCache = !transaction.preventCacheQueries();
595                   if ((PersonDO.cache.getLevelOfCaching() == CacheConstants.QUERY_CACHING) && canUseQueryCache) {
596                         String JavaDoc queryID = builder.getSQLwithParms(); //unique representation of query
597
int resNum = 0;
598                         int evaluateNo = 0;
599                        if (hitDb)
600                           queryCachedItem = ((QueryCache)PersonDO.cache).getComplexQueryCacheItem(logicalDatabase, queryID);
601                        else
602                           queryCachedItem = ((QueryCache)PersonDO.cache).getSimpleQueryCacheItem(logicalDatabase, queryID);
603                         queryItem.setQueryId(queryID); // queryItem defined as private template attribute
604
if (queryCachedItem == null) { // query doesn't exist
605
if ((!builder.isMultiTableJoin()) || PersonDO.isAllReadOnly()) {
606                                if (hitDb)
607                                      ((QueryCache)PersonDO.cache).addComplexQuery(queryItem); // register complex query
608
else
609                                       ((QueryCache)PersonDO.cache).addSimpleQuery(queryItem); // register simple query
610
}
611                         }else{ // query found
612
if ( !(isOrderRelevant() && queryCachedItem.isModifiedQuery()) ) {
613                                 if (hitDb) { // statistics about complex cache
614
stat = null;
615                                  stat = PersonDO.statistics.getCacheStatistics(CacheConstants.COMPLEX_QUERY_CACHE);
616                                  if (stat!= null){
617                                      stat.incrementCacheHitsNum(1);
618                                  }
619                                }else{ // statistics about simple cache
620
stat = null;
621                                  stat = PersonDO.statistics.getCacheStatistics(CacheConstants.SIMPLE_QUERY_CACHE);
622                                  if (stat!= null){
623                                     stat.incrementCacheHitsNum(1);
624                                  }
625                                  }
626
627                               int limitOfRes;
628                               if (databaseLimit == 0)
629                                  limitOfRes = 0;
630                               else
631                                  limitOfRes = readSkip+databaseLimit+1;
632                               if (! unique) {
633                                  if (hitDb)
634                                    results = ((QueryCache)PersonDO.cache).getComplexQueryResults(logicalDatabase, queryID, limitOfRes, maxDBrows);
635                                  else
636                                    results = ((QueryCache)PersonDO.cache).getSimpleQueryResults(logicalDatabase, queryID, limitOfRes, maxDBrows);
637                               }else{ // (! unique)
638
if (hitDb)
639                                     results = ((QueryCache)PersonDO.cache).getComplexQueryResults(logicalDatabase, queryID, limitOfRes, maxDBrows, true);
640                                  else
641                                     results = ((QueryCache)PersonDO.cache).getSimpleQueryResults(logicalDatabase, queryID, limitOfRes, maxDBrows, true);
642                               } // (! unique)
643
if (results != null) {
644  //sinisa 06.08.2003.
645
results = getCachedResults(results);
646                                  resNum = results.DOs.size();
647                                  if (databaseLimit != 0) { // databaseLimitExceeded begin
648
if (resNum == readSkip+databaseLimit+1) {
649                                          resNum--;
650                                          databaseLimitExceeded = true;
651                                          results.DOs.remove(readSkip+databaseLimit);
652                                      }else{
653                                          if ( (resNum == readSkip+databaseLimit) && (!queryCachedItem.isCompleteResult()) )
654                                               databaseLimitExceeded = true;
655                                      }
656                                  } // databaseLimitExceeded end
657
if ( (databaseLimit!=0 &&(resNum == (readSkip+databaseLimit))) || (maxDBrows!=0 && (resNum + results.skippedUnique) == maxDBrows) || (queryCachedItem.isCompleteResult()) ) {
658                                           int lazyTime = PersonDO.statistics.getQueryByOIdAverageTime()*results.lazy.size();
659                                          if (lazyTime <= queryCachedItem.getTime()) {
660                                               resultsFromQCache = true;
661                                                getQueryByOIds(results.lazy); // gets cached query results from database
662
}else
663                                         databaseLimitExceeded = false;
664                                      }else
665                                      databaseLimitExceeded = false;
666                               } // (results != null)
667

668                         } // !(isOrderRelevant() && queryCachedItem.isModifiedQuery())
669
} // query found
670
} // if QUERY_CACHING
671
} // full caching
672
} // other queries
673
if (( userHitDb) || (!resultsFromQCache)) { // go to database
674

675                         dbQuery = PersonDO.createQuery(transaction);
676
677                 results = new QueryResult();
678                 int resultCount=0;
679                    boolean bHasMoreResults = false;
680           if (( (PersonDO.getConfigurationAdministration().getTableConfiguration().isLazyLoading()) || isCaching()) && (!builder.getPreventPrimaryKeySelect()) && !loadData) {
681                  builder.resetSelectedFields();
682                    builder.setSelectClause("person."+PersonDO.get_OIdColumnName()+", person."+PersonDO.get_versionColumnName());
683                }
684                else
685                 builder.setSelectClause( "person.*");
686                    dbQuery.query( this ); // invokes executeQuery
687

688
689                    if (! unique) {
690                     while ( (bHasMoreResults = resultSet.next()) && (databaseLimit==0 || (results.DOs.size()<databaseLimit)) ) {
691                            PersonDO newDO;
692                            PersonDataStruct newDS;
693
694                     if (( (PersonDO.getConfigurationAdministration().getTableConfiguration().isLazyLoading()) || isCaching()) && (!builder.getPreventPrimaryKeySelect()) && !loadData) {
695                            newDO = PersonDO.createExisting ( new ObjectId(resultSet.getBigDecimal(CoreDO.get_OIdColumnName())) , refs, transaction);
696                                                    newDO.set_Version(resultSet.getInt(PersonDO.get_versionColumnName()));
697                         } else
698                             newDO = PersonDO.createExisting ( resultSet , refs, transaction);
699                             if(transaction==null) {
700                              if(newDO!=null && newDO.isTransactionCheck()) {
701                                 String JavaDoc trace="";
702                                 StackTraceElement JavaDoc[] traceElements= (new Throwable JavaDoc()).getStackTrace();
703                                 for(int i=0; i < traceElements.length; i++)
704                                     trace+=traceElements[i].toString()+"\n";
705                                 DODS.getLogChannel().write(Logger.WARNING, "DO without transaction context is created : Database: "+newDO.get_OriginDatabase()+" PersonDO class, oid: "+newDO.get_OId()+", version: "+newDO.get_Version()+" \n"+trace);
706                              }
707                           }
708     
709                         if (queryItem != null) {
710                             queryItem.add((PersonDataStruct)newDO.originalData_get());
711                         }
712                         if (( (PersonDO.getConfigurationAdministration().getTableConfiguration().isLazyLoading()) || isCaching()) && (!builder.getPreventPrimaryKeySelect()) && !loadData)
713                          {}
714                         else
715                            newDS =PersonDO.addToCache((PersonDataStruct)newDO.originalData_get());
716     
717                                 if (resultCount >= readSkip) {
718                                     shell = new DOShell(newDO);
719                                     results.DOs.add(shell);
720                                 }
721                                 resultCount++;
722     
723                     } // while
724
} // (!unique)
725

726                 else { // (! unique)
727
HashSet hsResult = new HashSet(readSkip+databaseLimit);
728                     while((bHasMoreResults = resultSet.next()) && (databaseLimit==0 || (results.DOs.size()<databaseLimit)) ) {
729                         PersonDO newDO;
730                         PersonDataStruct newDS;
731
732                     if (( (PersonDO.getConfigurationAdministration().getTableConfiguration().isLazyLoading()) || isCaching()) && (!builder.getPreventPrimaryKeySelect()) && !loadData) {
733                            newDO = PersonDO.createExisting ( new ObjectId(resultSet.getBigDecimal(CoreDO.get_OIdColumnName())) , refs, transaction);
734                                                    newDO.set_Version(resultSet.getInt(PersonDO.get_versionColumnName()));
735                         } else
736                               newDO = PersonDO.createExisting ( resultSet , refs , transaction);
737                             if(transaction==null) {
738                                 if(newDO!=null && newDO.isTransactionCheck()) {
739                                    String JavaDoc trace="";
740                                    StackTraceElement JavaDoc[] traceElements= (new Throwable JavaDoc()).getStackTrace();
741                                    for(int i=0; i < traceElements.length; i++)
742                                         trace+=traceElements[i].toString()+"\n";
743                                    DODS.getLogChannel().write(Logger.WARNING, "DO without transaction context is created : Database: "+newDO.get_OriginDatabase()+" PersonDO class, oid: "+newDO.get_OId()+", version: "+newDO.get_Version()+" \n"+trace);
744                                 }
745                               }
746
747                         if (queryItem != null) {
748                             queryItem.add((PersonDataStruct)newDO.originalData_get());
749                         }
750                         if (( (PersonDO.getConfigurationAdministration().getTableConfiguration().isLazyLoading()) || isCaching()) && (!builder.getPreventPrimaryKeySelect()) && !loadData)
751                          {
752                         } else
753                            newDS = PersonDO.addToCache((PersonDataStruct)newDO.originalData_get());
754
755                                 if (!hsResult.contains(newDO.get_Handle())) {
756                                     hsResult.add(newDO.get_Handle());
757                                     if (resultCount >= readSkip) {
758
759                                         shell = new DOShell(newDO);
760                                         results.DOs.add(shell);
761                                     }
762                                     resultCount++;
763                                 }
764
765                     } // while
766
} // else (! unique)
767

768                 if ((results.DOs.size()==databaseLimit)&& bHasMoreResults) {
769                     resultSet.close();
770                     databaseLimitExceeded = true;
771                 }
772         if (maxDBrows > 0) {
773                     if (!bHasMoreResults) {
774                       if ((databaseLimit > 0) && databaseLimit < maxDBrows )
775                           queryItem.setCompleteResult(true);
776           }
777         }
778                 else {
779                   if (!bHasMoreResults)
780                       queryItem.setCompleteResult(true);
781                 }
782                 Date JavaDoc stopQueryTime = new Date JavaDoc();
783                 queryTime = stopQueryTime.getTime() - startQueryTime.getTime();
784                 if (queryItem != null) {
785                     queryItem.setTime((new Long JavaDoc(queryTime)).intValue());
786                         if (queryCachedItem != null) {
787                           if ( queryItem.isCompleteResult() || (queryCachedItem.isModifiedQuery() && isOrderRelevant()) || (queryCachedItem.getResultNum() < queryItem.getResultNum()) ) {
788                                         if ((!builder.isMultiTableJoin()) || PersonDO.isAllReadOnly() ) {
789                     if (hitDb) {
790                         ((QueryCache)PersonDO.cache).addComplexQuery(queryItem);
791                     }
792                     else {
793                         ((QueryCache)PersonDO.cache).addSimpleQuery(queryItem);
794                     }
795                                     } // !builder.isMultiTableJoin()
796

797                                       }
798                           else {
799                             if ( (queryCachedItem.getResultNum() < (readSkip + databaseLimit) ) && (queryCachedItem.getResultNum() < maxDBrows) ) {
800                                  queryCachedItem.setCompleteResult(true);
801                    }
802                           }
803                           if ( (queryItem.getResultNum() < (readSkip + databaseLimit) ) && (queryItem.getResultNum() < maxDBrows) )
804                                 queryItem.setCompleteResult(true);
805                         } // (queryCachedItem != null)
806
} // (queryItem != null)
807
int maxExecuteTime = PersonDO.cache.getTableConfiguration().getMaxExecuteTime();
808                     if (maxExecuteTime > 0 && queryTime > maxExecuteTime)
809                         DODS.getLogChannel().write(Logger.WARNING, "sql = " + builder.getSQLwithParms()+" execute time = "+queryTime + "max table execute time = "+maxExecuteTime);
810             }
811             else { // ( userHitDb) || (!resultsFromQCache)
812
if (PersonDO.cache.isFull()&& (!hitDb)) {
813                  results = new QueryResult();
814                   if (readSkip<cacheHits.size()) {
815                         Vector vect = new Vector(cacheHits.values());
816                         results.DOs = new Vector();
817                         PersonDO DO = null;
818                         PersonDataStruct DS = null;
819                         String JavaDoc cachePrefix = getLogicalDatabase()+".";
820                         int i = readSkip;
821                         while (i < vect.size() && ((databaseLimit==0) || (i<=readSkip+databaseLimit))) {
822                             boolean findInTransactionCache = false;
823                             DS = (PersonDataStruct)vect.get(i);
824                             if(transaction!=null && _tr_(transaction).getTransactionCache()!=null && !loadData) {
825                                DO = (PersonDO)_tr_(transaction).getTransactionCache().getDOByHandle(cachePrefix+DS.get_OId().toString());
826                                if(DO != null)
827                                 findInTransactionCache = true;
828                             }
829                             if(!findInTransactionCache){
830                                 DO = (PersonDO)PersonDO.createExisting(DS.get_OId(), transaction);
831                             }
832                             
833                                     results.DOs.add(DO);
834
835                         i++;
836                         }
837                         readDOs = true;
838                     }
839
840                     if ((databaseLimit != 0) && (results.DOs.size() == databaseLimit+1)) {
841                       databaseLimitExceeded = true;
842                       results.DOs.remove(databaseLimit);
843                    }
844
845                 } //if full
846

847             } // ( userHitDb) || (!resultsFromQCache)
848
// end of WebDocWf extension
849
if ( results.DOs.size() > 1 && uniqueInstance )
850                 throw new NonUniqueQueryException("Too many rows returned from database" );
851             DOs = new PersonDO [ results.DOs.size() ];
852             PersonDataStruct orig;
853             if (readDOs) {
854                 for ( int i = 0; i < results.DOs.size(); i++ ) {
855                     DOs[i] = (PersonDO)results.DOs.elementAt(i);
856                 }
857             }
858             else {
859                 for ( int i = 0; i < results.DOs.size(); i++ ) {
860                     DOs[i] = (PersonDO)((DOShell)results.DOs.elementAt(i)).dataObject;
861                 }
862             }
863             arrayIndex = 0;
864             if (isQueryByOId && !hasNonOidCond) {
865                PersonDO.statistics.incrementQueryByOIdNum();
866                PersonDO.statistics.updateQueryByOIdAverageTime((new Long JavaDoc(queryTime)).intValue(),1);
867             }
868             else {
869                PersonDO.statistics.incrementQueryNum();
870                 PersonDO.statistics.updateQueryAverageTime((new Long JavaDoc(queryTime)).intValue());
871             }
872         } catch ( SQLException se ) {
873             if (null == se.getSQLState() ) {
874                 throw new DataObjectException("Unknown SQLException", se );
875             }
876             if ( se.getSQLState().startsWith("02") && se.getErrorCode() == 100 ) {
877                 throw new DataObjectException("Update or delete DO is out of synch", se );
878             } else if ( se.getSQLState().equals("S1000") && se.getErrorCode() == -268) {
879                 throw new DataObjectException("Integrity constraint violation", se );
880             } else {
881                 throw new DataObjectException( "Data Object Error", se );
882             }
883         } catch ( ObjectIdException oe ) {
884             throw new DataObjectException( "Object ID Error", oe );
885         } catch ( DatabaseManagerException de ) {
886             throw new DataObjectException( "Database connection Error", de );
887         }
888         finally {
889             if (( null != dbQuery )&&(null== transaction))
890                 dbQuery.release();
891         }
892     }
893
894     /**
895      * Limit the number of rows (DOs) returned.
896      * NOTE: When setting a limit on rows returned by a query,
897      * you usually want to use a call to an addOrderBy method
898      * to cause the most interesting rows to be returned first.
899
900      * However, the DO cache does not yet support the Order By operation.
901      * Using the addOrderBy method forces the query to hit the database.
902      * So, setMaxRows also forces the query to hit the database.
903
904      *
905      * @param maxRows Max number of rows (DOs) returned.
906      *
907      * @exception DataObjectException If a database access error occurs.
908      * @exception NonUniqueQueryException If too many rows were found.
909      */

910     public void setMaxRows( int maxRows )
911     throws DataObjectException, NonUniqueQueryException {
912
913     maxDBrows = maxRows;
914         builder.setMaxRows( maxRows );
915     }
916
917     /**
918      * Return limit of rows (DOs) returned.
919      * @return Max number of rows (DOs) returned.
920      *
921      */

922     public int getMaxRows() {
923     return maxDBrows;
924     }
925     /**
926      * Returns attribute orderRelevant.
927      *
928      * @return true if order of query results is relavant, otherwise false.
929      */

930     public boolean isOrderRelevant() {
931     return orderRelevant;
932     }
933
934     /**
935      * Sets attribute orderRelevant.
936      *
937      * @param newOrderRelavant new value of attribute orderRelavant.
938      */

939     public void setOrderRelevant(boolean newOrderRelevant) {
940     orderRelevant = newOrderRelevant;
941     }
942
943
944     /**
945      * Return QueryResult with read DOs or DataStructs from caches.
946      *
947      * @return QueryResult .
948      *
949      * @exception DataObjectException If a database access error occurs.
950      */

951     public QueryResult getCachedResults(QueryResult result) throws DataObjectException {
952         Vector tempVec = result.DOs;
953         if (tempVec == null)
954             return null;
955         result.DOs = new Vector();
956         result.lazy = new Vector();
957         DOShell shell = null;
958         PersonDO cacheDO = null;
959         PersonDataStruct cacheDS = null;
960         String JavaDoc handle = "";
961         String JavaDoc cachePrefix=getLogicalDatabase()+".";
962
963         for(int i=0; i < tempVec.size(); i++) {
964
965             if(tempVec.get(i)!=null) {
966                 cacheDO = null;
967                 cacheDS = null;
968                 handle=(String JavaDoc)tempVec.get(i);
969                 shell = new DOShell(handle);
970                 if(transaction!=null && _tr_(transaction).getTransactionCache()!=null && !loadData) {
971                     try {
972                         cacheDO = (PersonDO)_tr_(transaction).getTransactionCache().getDOByHandle(cachePrefix+handle);
973                     } catch (Exception JavaDoc e) {
974                     }
975                 }
976                 if (cacheDO == null){
977                     cacheDS = (PersonDataStruct)PersonDO.cache.getDataStructByHandle(cachePrefix+handle);
978                     if(cacheDS!=null) {
979                         try {
980                             cacheDO = (PersonDO)PersonDO.createExisting(cacheDS.get_OId(), transaction);
981                         } catch (Exception JavaDoc e) {
982                     }
983                 }
984                }
985                 if (cacheDO == null){
986                     result.lazy.add(shell);
987                 }
988                 else {
989                     shell.dataObject = cacheDO;
990                 }
991                 result.DOs.add(shell);
992           }
993         } //for
994
return result;
995     }
996
997
998
999     /**
1000     * Return array of DOs constructed from ResultSet returned by query.
1001     *
1002     * @return Array of DOs constructed from ResultSet returned by query.
1003     *
1004     * @exception DataObjectException If a database access error occurs.
1005     * @exception NonUniqueQueryException If too many rows were found.
1006     */

1007    public PersonDO[] getDOArray()
1008    throws DataObjectException, NonUniqueQueryException {
1009        if ( needToRun )
1010            runQuery();
1011        return DOs;
1012    }
1013
1014    /**
1015     * Return successive DOs from array built from ResultSet returned by query.
1016     *
1017     * @return DOs from array built from ResultSet returned by query.
1018     *
1019     * @exception DataObjectException If a database access error occurs.
1020     * @exception NonUniqueQueryException If too many rows were found.
1021     */

1022    public PersonDO getNextDO()
1023    throws DataObjectException, NonUniqueQueryException {
1024        if ( needToRun )
1025            runQuery();
1026        if ( null == DOs ) {
1027            /* This should never happen.
1028             * runQuery() should either throw an exception
1029             * or create an array of DOs, possibly of zero length.
1030             */

1031            return null;
1032        }
1033        if ( arrayIndex < DOs.length )
1034            return DOs[ arrayIndex++ ];
1035        return null;
1036    }
1037
1038
1039    /**
1040     * Set the OID to query.
1041     * WARNING! This method assumes that table <CODE>person</CODE>
1042     * has a column named <CODE>"oid"</CODE>.
1043     * This method is called from the DO classes to retrieve an object by id.
1044     *
1045     * @param oid The object id to query.
1046     */

1047    public void setQueryOId(ObjectId oid) {
1048        // Remove from cacheHits any DO that does not meet this
1049
// setQuery requirement.
1050
String JavaDoc handle = getLogicalDatabase()+ "." +oid.toString();
1051        if (PersonDO.cache.isFull()) {
1052            PersonDataStruct DS = (PersonDataStruct)cacheHits.get(handle);
1053                cacheHits = new LinkedHashMap();
1054            if (DS != null) {
1055                cacheHits.put(handle,DS);
1056            }
1057        }
1058            if (isQueryByOId) { // query by OId already has been invoked
1059

1060              hasNonOidCond = true; // this is not simple query by oid: has at least two conditions for oids
1061

1062
1063            } else { // (isQueryByOid)
1064
currentHandle = handle;
1065        }
1066                isQueryByOId = true;
1067        try {
1068            Condition cond = new Condition(PersonDataStruct.COLUMN_OID,handle,"=");
1069         queryItem.addCond(cond);
1070    }
1071    catch (Exception JavaDoc e){
1072        }
1073        // Also prepare the SQL needed to query the database
1074
// in case there is no cache, or the query involves other tables.
1075
builder.addWhere( PersonDO.PrimaryKey, oid.toBigDecimal(), QueryBuilder.EQUAL );
1076    }
1077
1078    /**
1079     * Set the object handle to query.
1080     * This is a variant of setQueryOId().
1081     *
1082     * @param handle The string version of the id to query.
1083     */

1084    public void setQueryHandle(String JavaDoc handle)
1085    throws ObjectIdException {
1086        ObjectId oid = new ObjectId( handle );
1087        setQueryOId( oid );
1088    }
1089
1090
1091    /**
1092     * Set "unique instance" assertion bit.
1093     * The first call to the next() method will throw an exception
1094     * if more than one object was found.
1095     */

1096    public void requireUniqueInstance() {
1097        uniqueInstance = true;
1098    }
1099
1100    /**
1101     * Set loadData parameter. if parameter is set to true, Query select t.* is performed.
1102     * @param newValue boolean (true/false)
1103     */

1104    public void setLoadData(boolean newValue) {
1105        loadData = newValue;
1106    }
1107
1108    /**
1109     * Return true if Query is prepared for select t1.* statement. Otherwise return false.
1110     * @return boolean (true/false)
1111     */

1112    public boolean getLoadData() {
1113        if(loadData)
1114           return true;
1115        else
1116           return ((PersonDO.getConfigurationAdministration().getTableConfiguration().isLazyLoading()) || isCaching());
1117    }
1118
1119    /**
1120     * Reset the query parameters.
1121     */

1122    public void reset() {
1123        if (PersonDO.cache.isFull()) {
1124            cacheHits = new LinkedHashMap(PersonDO.cache.getCacheContent());
1125        }
1126        DOs = null;
1127        uniqueInstance = false;
1128        needToRun = true;
1129        isQueryByOId = false;
1130        hasNonOidCond = false;
1131        loadData=false;
1132        builder.reset();
1133        if (PersonDO.cache.getLevelOfCaching() == CacheConstants.QUERY_CACHING) {
1134            queryItem = ((QueryCache)PersonDO.cache).newQueryCacheItemInstance(logicalDatabase);
1135        }
1136    }
1137
1138    /**
1139     * Return the appropriate QueryBuilder flag for selecting
1140     * exact matches (SQL '=') or inexact matches (SQL 'matches').
1141     *
1142     * @return boolean True if it is exact match, otherwise false.
1143     *
1144     */

1145    private boolean exactFlag( boolean exact ) {
1146        return exact ? QueryBuilder.EXACT_MATCH : QueryBuilder.NOT_EXACT;
1147    }
1148
1149    //
1150
// Implementation of Query interface
1151
//
1152

1153    /**
1154     * Method to query objects from the database.
1155     * The following call in runQuery()
1156     * dbQuery.query( this );
1157     * causes the dbQuery object to invoke
1158     * executeQuery()
1159     *
1160     * @param conn Handle to database connection.
1161     *
1162     * @return ResultSet with the results of the query.
1163     *
1164     * @exception java.sql.SQLException If a database access error occurs.
1165     */

1166    public ResultSet executeQuery(DBConnection conn)
1167    throws SQLException {
1168        builder.setCurrentFetchSize(iCurrentFetchSize);
1169        builder.setCurrentQueryTimeout(iCurrentQueryTimeout);
1170        resultSet = builder.executeQuery( conn );
1171        return resultSet;
1172    }
1173
1174    /**
1175     * WARNING! This method is disabled.
1176     * It's implementation is forced by the Query interface.
1177     * This method is disabled for 2 reasons:
1178     * 1) the getDOArray() and getNextDO() methods are better
1179     * because they return DOs instead of JDBC objects.
1180     * 2) the createExisting() method throws an exception
1181     * that we cannot reasonably handle here,
1182     * and that we cannot throw from here.
1183     *
1184     * @param rs JDBC result set from which the next object
1185     * will be instantiated.
1186     *
1187     * @exception java.sql.SQLException
1188     * If a database access error occurs.
1189     * @exception com.lutris.appserver.server.sql.ObjectIdException
1190     * If an invalid object id was queried from the database.
1191     */

1192    public Object JavaDoc next(ResultSet rs)
1193    throws SQLException, ObjectIdException {
1194        // TODO: It would be nice to throw an unchecked exception here
1195
// (an exception that extends RuntimeException)
1196
// that would be guaranteed to appear during application testing.
1197
throw new ObjectIdException("next() should not be used. Use getNextDO() instead." );
1198        //return null;
1199
}
1200
1201
1202    // WebDocWf extension for extended wildcard support
1203
// The following lines have been added:
1204
/**
1205     * Convert a String with user wildcards into a string with DB wildcards
1206     *
1207     * @param userSearchValue The string with user wildcards
1208     *
1209     * @return The string with DB wildcards
1210     *
1211     * WebDocWf extension
1212     *
1213     */

1214    public String JavaDoc convertUserSearchValue( String JavaDoc userSearchValue ) {
1215        return builder.convertUserSearchValue( userSearchValue );
1216    }
1217
1218    /**
1219     * Check whether a string contains DB wildcards
1220     *
1221     * @param dbSearchValue The string with possible DB wildcards
1222     *
1223     * @return Whether a string contains DB wildcards
1224     *
1225     * WebDocWf extension
1226     *
1227     */

1228    public boolean containsWildcards( String JavaDoc dbSearchValue ) {
1229        return builder.containsWildcards( dbSearchValue );
1230    }
1231    // end of WebDocWf extension for extended wildcard support
1232

1233    // WebDocWf extension for query row counter
1234
// The following lines have been added:
1235
/**
1236     * Get the rowcount of the query
1237     * If possible, do it without reading all rows
1238     *
1239     * @return The row count
1240     *
1241     * WebDocWf extension
1242     *
1243     */

1244    public int getCount()
1245    throws NonUniqueQueryException, DataObjectException, SQLException, DatabaseManagerException {
1246        int rowCount=0;
1247        if (needToRun && databaseLimit==0) {
1248            rowCount = selectCount();
1249        } else {
1250            if (needToRun) runQuery();
1251                rowCount = DOs.length;
1252        }
1253        return rowCount;
1254    }
1255
1256    /**
1257     * Set reference objects
1258     *
1259     */

1260    protected void setRefs(HashMap queryRefs) {
1261        refs = queryRefs;
1262    }
1263
1264    /**
1265     * Set fetch size for this query
1266     *
1267     */

1268    public void set_FetchSize (int iCurrentFetchSizeIn) {
1269         iCurrentFetchSize = iCurrentFetchSizeIn;
1270     }
1271
1272   /**
1273    * reads the current fetchsize for this query
1274    * @return the current fetchsize; if -1 the no fetchsize is defined, defaultFetchSize will be use if defined
1275    */

1276   public int get_FetchSize() {
1277       return (iCurrentFetchSize < 0)? builder.getDefaultFetchSize() : iCurrentFetchSize;
1278   }
1279
1280   /**
1281    * reads the current queryTimeout for this query
1282    * @return the current queryTimeout;
1283    */

1284   public int get_QueryTimeout() {
1285       return iCurrentQueryTimeout;
1286   }
1287   
1288   /**
1289    * set the current queryTimeout for this query
1290    * @return the current queryTimeout;
1291    */

1292   public void set_QueryTimeout(int iQueryTimeoutIn) {
1293       iCurrentQueryTimeout = (iCurrentQueryTimeout < 0)? builder.getDefaultQueryTimeout() : iCurrentQueryTimeout;
1294   }
1295   
1296   
1297    /**
1298     * Get the rowcount of the query by using count(*) in the DB
1299     *
1300     * @return The row count
1301     *
1302     * WebDocWf extension
1303     *
1304     */

1305    public int selectCount()
1306    throws SQLException, DatabaseManagerException {
1307        int rowCount=0;
1308        String JavaDoc tempClause = builder.getSelectClause();
1309        builder.setSelectClause(" count(*) as \"counter\" ");
1310        DBQuery dbQuery;
1311
1312            dbQuery = PersonDO.createQuery(transaction);
1313        dbQuery.query(this);
1314        resultSet.next();
1315        rowCount=resultSet.getInt("counter");
1316        resultSet.close();
1317                if (transaction == null)
1318            dbQuery.release();
1319        builder.close();
1320        resultSet = null;
1321        builder.setSelectClause(tempClause);
1322        return rowCount;
1323    }
1324    // end of WebDocWf extension for query row counter
1325

1326    /**
1327     * Return true if some caching for this table is enabled.
1328     * @return (true/false)
1329     */

1330
1331   private boolean isCaching() {
1332      double cachePercentage = PersonDO.cache.getCachePercentage();
1333      double usedPercentage = 0;
1334      if(cachePercentage == -1)
1335         return false;
1336      else if(cachePercentage == 0)
1337         return true;
1338      else {
1339       try {
1340          usedPercentage = PersonDO.getConfigurationAdministration().getStatistics().getCacheStatistics(CacheConstants.DATA_CACHE).getUsedPercents();
1341        } catch (Exception JavaDoc ex) {
1342               return false;
1343        }
1344         if(usedPercentage > PersonDO.cache.getCachePercentage()*100)
1345            return true;
1346         else
1347            return false;
1348      }
1349   }
1350
1351   private static StandardDBTransaction _tr_(DBTransaction dbt) {
1352      return (StandardDBTransaction)dbt;
1353   }
1354
1355    
1356    /**
1357     * Set the firstName to query, with a QueryBuilder comparison operator.
1358     *
1359     * @param x The firstName of the person to query.
1360     * @param cmp_op QueryBuilder comparison operator to use.
1361     *
1362     * @exception DataObjectException If a database access error occurs.
1363     * @exception QueryException If comparison operator is inappropriate
1364     * (e.g. CASE_SENSITIVE_CONTAINS on an integer field).
1365     */

1366
1367    
1368    public void setQueryFirstName(String JavaDoc x, String JavaDoc cmp_op )
1369    throws DataObjectException, QueryException {
1370    
1371    String JavaDoc cachePrefix = getLogicalDatabase()+".";
1372        
1373        hasNonOidCond = true;
1374        Condition cond = new Condition(PersonDataStruct.COLUMN_FIRSTNAME,x,cmp_op);
1375        queryItem.addCond(cond);
1376        // WebDocWf extension for extended wildcard support
1377
// The following lines have been added:
1378
if (cmp_op.equals(QueryBuilder.CASE_INSENSITIVE_MATCH) || cmp_op.equals(QueryBuilder.CASE_SENSITIVE_MATCH) || cmp_op.equals(QueryBuilder.USER_CASE_SENSITIVE_MATCH) || cmp_op.equals(QueryBuilder.USER_CASE_INSENSITIVE_MATCH)) {
1379            hitDb = true;
1380        } else {
1381            // end of WebDocWf extension for extended wildcard support
1382

1383            if (PersonDO.cache.isFull()) {
1384                // Remove from cacheHits any DOs that do not meet this
1385
// setQuery requirement.
1386
PersonDO DO = null;
1387                PersonDataStruct DS = null;
1388                for ( Iterator iter = (new HashSet(cacheHits.values())).iterator(); iter.hasNext();) {
1389                      try {
1390                        boolean findInTransactionCache = false;
1391                        DS = (PersonDataStruct)iter.next();
1392                        if(transaction!=null && _tr_(transaction).getTransactionCache()!=null) {
1393                            DO = (PersonDO)_tr_(transaction).getTransactionCache().getDOByHandle(cachePrefix+DS.get_OId().toString());
1394                            if(DO != null)
1395                                findInTransactionCache = true;
1396                        }
1397                        if(!findInTransactionCache){
1398                            DO = (PersonDO)PersonDO.createExisting(DS.get_OId(), transaction);
1399                        }
1400                       }catch (Exception JavaDoc ex) {
1401                          System.out.println("Error in query member stuff");
1402                       }
1403                       
1404                    String JavaDoc m = DO.getFirstName();
1405                    if(!QueryBuilder.compare( m, x, cmp_op )) {
1406                        try {
1407                            String JavaDoc cacheHandle = DO.get_CacheHandle();
1408                            cacheHits.remove(cacheHandle);
1409                        } catch (DatabaseManagerException e) {
1410                            throw new DataObjectException("Error in loading data object's handle.");
1411                        }
1412                    }
1413                }
1414            }
1415        }
1416        // Also prepares the SQL needed to query the database
1417
// in case there is no cache, or the query involves other tables.
1418
// WebDocWf patch for correct queries in fully cached objects
1419
// The following line has been put under comments:
1420
// if ( partOrLru || hitDb )
1421
// end of WebDocWf patch for correct queries in fully cached objects
1422
builder.addWhere( PersonDO.FirstName, x, cmp_op );
1423    }
1424
1425    /**
1426     * Set the firstName to query, with a QueryBuilder comparison operator.
1427     *
1428     * @param x The firstName of the person to query.
1429     *
1430     * @exception DataObjectException If a database access error occurs.
1431     * @exception QueryException If comparison operator is inappropriate
1432     * (e.g. CASE_SENSITIVE_CONTAINS on an integer field).
1433     */

1434    public void setQueryFirstName(String JavaDoc x)
1435    throws DataObjectException, QueryException {
1436         setQueryFirstName(x, QueryBuilder.EQUAL);
1437    }
1438
1439    /**
1440     * Add firstName to the ORDER BY clause.
1441     * NOTE: The DO cache does not yet support the Order By operation.
1442     * Using the addOrderBy method forces the query to hit the database.
1443     *
1444     * @param direction_flag True for ascending order, false for descending
1445     */

1446    public void addOrderByFirstName(boolean direction_flag) {
1447        hitDb = true;
1448        builder.addOrderByColumn("firstName", (direction_flag) ? "ASC" : "DESC");
1449    }
1450
1451
1452    /**
1453     * Add firstName to the ORDER BY clause. This convenience
1454     * method assumes ascending order.
1455     * NOTE: The DO cache does not yet support the Order By operation.
1456     * Using the addOrderBy method forces the query to hit the database.
1457     */

1458    public void addOrderByFirstName() {
1459        hitDb = true;
1460        builder.addOrderByColumn("firstName","ASC");
1461    }
1462
1463
1464
1465    // WebDocWf extension for extended wildcard support
1466
// The following lines have been added:
1467

1468    /**
1469     * Set the firstName to query with a user wildcard string
1470     *
1471     * @param x The firstName of the person to query with user wildcards
1472     *
1473     * @exception DataObjectException If a database access error occurs.
1474     *
1475     * @deprecated Use comparison operators instead
1476     *
1477     * WebDocWf extension
1478     *
1479     */

1480    public void setUserMatchFirstName( String JavaDoc x )
1481    throws DataObjectException, QueryException {
1482        String JavaDoc y = convertUserSearchValue( x );
1483        setDBMatchFirstName( y );
1484    }
1485
1486
1487
1488    /**
1489     * Set the firstName to query with a DB wildcard string
1490     *
1491     * @param x The firstName of the person to query with DB wildcards
1492     *
1493     * @exception DataObjectException If a database access error occurs.
1494     *
1495     * @deprecated Use comparison operators instead
1496     *
1497     * WebDocWf extension
1498     *
1499     */

1500    public void setDBMatchFirstName(String JavaDoc x )
1501    throws DataObjectException, QueryException {
1502        if (containsWildcards(x) || builder.getUserStringAppendWildcard()) {
1503            builder.addMatchClause( PersonDO.FirstName, x );
1504            hitDb = true;
1505        } else
1506            setQueryFirstName( x, QueryBuilder.EQUAL );
1507    }
1508
1509
1510    // end of WebDocWf extension for extended wildcard support
1511

1512    
1513    /**
1514     * Set the lastName to query, with a QueryBuilder comparison operator.
1515     *
1516     * @param x The lastName of the person to query.
1517     * @param cmp_op QueryBuilder comparison operator to use.
1518     *
1519     * @exception DataObjectException If a database access error occurs.
1520     * @exception QueryException If comparison operator is inappropriate
1521     * (e.g. CASE_SENSITIVE_CONTAINS on an integer field).
1522     */

1523
1524    
1525    public void setQueryLastName(String JavaDoc x, String JavaDoc cmp_op )
1526    throws DataObjectException, QueryException {
1527    
1528    String JavaDoc cachePrefix = getLogicalDatabase()+".";
1529        
1530        hasNonOidCond = true;
1531        Condition cond = new Condition(PersonDataStruct.COLUMN_LASTNAME,x,cmp_op);
1532        queryItem.addCond(cond);
1533        // WebDocWf extension for extended wildcard support
1534
// The following lines have been added:
1535
if (cmp_op.equals(QueryBuilder.CASE_INSENSITIVE_MATCH) || cmp_op.equals(QueryBuilder.CASE_SENSITIVE_MATCH) || cmp_op.equals(QueryBuilder.USER_CASE_SENSITIVE_MATCH) || cmp_op.equals(QueryBuilder.USER_CASE_INSENSITIVE_MATCH)) {
1536            hitDb = true;
1537        } else {
1538            // end of WebDocWf extension for extended wildcard support
1539

1540            if (PersonDO.cache.isFull()) {
1541                // Remove from cacheHits any DOs that do not meet this
1542
// setQuery requirement.
1543
PersonDO DO = null;
1544                PersonDataStruct DS = null;
1545                for ( Iterator iter = (new HashSet(cacheHits.values())).iterator(); iter.hasNext();) {
1546                      try {
1547                        boolean findInTransactionCache = false;
1548                        DS = (PersonDataStruct)iter.next();
1549                        if(transaction!=null && _tr_(transaction).getTransactionCache()!=null) {
1550                            DO = (PersonDO)_tr_(transaction).getTransactionCache().getDOByHandle(cachePrefix+DS.get_OId().toString());
1551                            if(DO != null)
1552                                findInTransactionCache = true;
1553                        }
1554                        if(!findInTransactionCache){
1555                            DO = (PersonDO)PersonDO.createExisting(DS.get_OId(), transaction);
1556                        }
1557                       }catch (Exception JavaDoc ex) {
1558                          System.out.println("Error in query member stuff");
1559                       }
1560                       
1561                    String JavaDoc m = DO.getLastName();
1562                    if(!QueryBuilder.compare( m, x, cmp_op )) {
1563                        try {
1564                            String JavaDoc cacheHandle = DO.get_CacheHandle();
1565                            cacheHits.remove(cacheHandle);
1566                        } catch (DatabaseManagerException e) {
1567                            throw new DataObjectException("Error in loading data object's handle.");
1568                        }
1569                    }
1570                }
1571            }
1572        }
1573        // Also prepares the SQL needed to query the database
1574
// in case there is no cache, or the query involves other tables.
1575
// WebDocWf patch for correct queries in fully cached objects
1576
// The following line has been put under comments:
1577
// if ( partOrLru || hitDb )
1578
// end of WebDocWf patch for correct queries in fully cached objects
1579
builder.addWhere( PersonDO.LastName, x, cmp_op );
1580    }
1581
1582    /**
1583     * Set the lastName to query, with a QueryBuilder comparison operator.
1584     *
1585     * @param x The lastName of the person to query.
1586     *
1587     * @exception DataObjectException If a database access error occurs.
1588     * @exception QueryException If comparison operator is inappropriate
1589     * (e.g. CASE_SENSITIVE_CONTAINS on an integer field).
1590     */

1591    public void setQueryLastName(String JavaDoc x)
1592    throws DataObjectException, QueryException {
1593         setQueryLastName(x, QueryBuilder.EQUAL);
1594    }
1595
1596    /**
1597     * Add lastName to the ORDER BY clause.
1598     * NOTE: The DO cache does not yet support the Order By operation.
1599     * Using the addOrderBy method forces the query to hit the database.
1600     *
1601     * @param direction_flag True for ascending order, false for descending
1602     */

1603    public void addOrderByLastName(boolean direction_flag) {
1604        hitDb = true;
1605        builder.addOrderByColumn("lastName", (direction_flag) ? "ASC" : "DESC");
1606    }
1607
1608
1609    /**
1610     * Add lastName to the ORDER BY clause. This convenience
1611     * method assumes ascending order.
1612     * NOTE: The DO cache does not yet support the Order By operation.
1613     * Using the addOrderBy method forces the query to hit the database.
1614     */

1615    public void addOrderByLastName() {
1616        hitDb = true;
1617        builder.addOrderByColumn("lastName","ASC");
1618    }
1619
1620
1621
1622    // WebDocWf extension for extended wildcard support
1623
// The following lines have been added:
1624

1625    /**
1626     * Set the lastName to query with a user wildcard string
1627     *
1628     * @param x The lastName of the person to query with user wildcards
1629     *
1630     * @exception DataObjectException If a database access error occurs.
1631     *
1632     * @deprecated Use comparison operators instead
1633     *
1634     * WebDocWf extension
1635     *
1636     */

1637    public void setUserMatchLastName( String JavaDoc x )
1638    throws DataObjectException, QueryException {
1639        String JavaDoc y = convertUserSearchValue( x );
1640        setDBMatchLastName( y );
1641    }
1642
1643
1644
1645    /**
1646     * Set the lastName to query with a DB wildcard string
1647     *
1648     * @param x The lastName of the person to query with DB wildcards
1649     *
1650     * @exception DataObjectException If a database access error occurs.
1651     *
1652     * @deprecated Use comparison operators instead
1653     *
1654     * WebDocWf extension
1655     *
1656     */

1657    public void setDBMatchLastName(String JavaDoc x )
1658    throws DataObjectException, QueryException {
1659        if (containsWildcards(x) || builder.getUserStringAppendWildcard()) {
1660            builder.addMatchClause( PersonDO.LastName, x );
1661            hitDb = true;
1662        } else
1663            setQueryLastName( x, QueryBuilder.EQUAL );
1664    }
1665
1666
1667    // end of WebDocWf extension for extended wildcard support
1668

1669    
1670    /**
1671     * Set the phoneNumber to query, with a QueryBuilder comparison operator.
1672     *
1673     * @param x The phoneNumber of the person to query.
1674     * @param cmp_op QueryBuilder comparison operator to use.
1675     *
1676     * @exception DataObjectException If a database access error occurs.
1677     * @exception QueryException If comparison operator is inappropriate
1678     * (e.g. CASE_SENSITIVE_CONTAINS on an integer field).
1679     */

1680
1681    
1682    public void setQueryPhoneNumber(String JavaDoc x, String JavaDoc cmp_op )
1683    throws DataObjectException, QueryException {
1684    
1685    String JavaDoc cachePrefix = getLogicalDatabase()+".";
1686        
1687        hasNonOidCond = true;
1688        Condition cond = new Condition(PersonDataStruct.COLUMN_PHONENUMBER,x,cmp_op);
1689        queryItem.addCond(cond);
1690        // WebDocWf extension for extended wildcard support
1691
// The following lines have been added:
1692
if (cmp_op.equals(QueryBuilder.CASE_INSENSITIVE_MATCH) || cmp_op.equals(QueryBuilder.CASE_SENSITIVE_MATCH) || cmp_op.equals(QueryBuilder.USER_CASE_SENSITIVE_MATCH) || cmp_op.equals(QueryBuilder.USER_CASE_INSENSITIVE_MATCH)) {
1693            hitDb = true;
1694        } else {
1695            // end of WebDocWf extension for extended wildcard support
1696

1697            if (PersonDO.cache.isFull()) {
1698                // Remove from cacheHits any DOs that do not meet this
1699
// setQuery requirement.
1700
PersonDO DO = null;
1701                PersonDataStruct DS = null;
1702                for ( Iterator iter = (new HashSet(cacheHits.values())).iterator(); iter.hasNext();) {
1703                      try {
1704                        boolean findInTransactionCache = false;
1705                        DS = (PersonDataStruct)iter.next();
1706                        if(transaction!=null && _tr_(transaction).getTransactionCache()!=null) {
1707                            DO = (PersonDO)_tr_(transaction).getTransactionCache().getDOByHandle(cachePrefix+DS.get_OId().toString());
1708                            if(DO != null)
1709                                findInTransactionCache = true;
1710                        }
1711                        if(!findInTransactionCache){
1712                            DO = (PersonDO)PersonDO.createExisting(DS.get_OId(), transaction);
1713                        }
1714                       }catch (Exception JavaDoc ex) {
1715                          System.out.println("Error in query member stuff");
1716                       }
1717                       
1718                    String JavaDoc m = DO.getPhoneNumber();
1719                    if(!QueryBuilder.compare( m, x, cmp_op )) {
1720                        try {
1721                            String JavaDoc cacheHandle = DO.get_CacheHandle();
1722                            cacheHits.remove(cacheHandle);
1723                        } catch (DatabaseManagerException e) {
1724                            throw new DataObjectException("Error in loading data object's handle.");
1725                        }
1726                    }
1727                }
1728            }
1729        }
1730        // Also prepares the SQL needed to query the database
1731
// in case there is no cache, or the query involves other tables.
1732
// WebDocWf patch for correct queries in fully cached objects
1733
// The following line has been put under comments:
1734
// if ( partOrLru || hitDb )
1735
// end of WebDocWf patch for correct queries in fully cached objects
1736
builder.addWhere( PersonDO.PhoneNumber, x, cmp_op );
1737    }
1738
1739    /**
1740     * Set the phoneNumber to query, with a QueryBuilder comparison operator.
1741     *
1742     * @param x The phoneNumber of the person to query.
1743     *
1744     * @exception DataObjectException If a database access error occurs.
1745     * @exception QueryException If comparison operator is inappropriate
1746     * (e.g. CASE_SENSITIVE_CONTAINS on an integer field).
1747     */

1748    public void setQueryPhoneNumber(String JavaDoc x)
1749    throws DataObjectException, QueryException {
1750         setQueryPhoneNumber(x, QueryBuilder.EQUAL);
1751    }
1752
1753    /**
1754     * Add phoneNumber to the ORDER BY clause.
1755     * NOTE: The DO cache does not yet support the Order By operation.
1756     * Using the addOrderBy method forces the query to hit the database.
1757     *
1758     * @param direction_flag True for ascending order, false for descending
1759     */

1760    public void addOrderByPhoneNumber(boolean direction_flag) {
1761        hitDb = true;
1762        builder.addOrderByColumn("phoneNumber", (direction_flag) ? "ASC" : "DESC");
1763    }
1764
1765
1766    /**
1767     * Add phoneNumber to the ORDER BY clause. This convenience
1768     * method assumes ascending order.
1769     * NOTE: The DO cache does not yet support the Order By operation.
1770     * Using the addOrderBy method forces the query to hit the database.
1771     */

1772    public void addOrderByPhoneNumber() {
1773        hitDb = true;
1774        builder.addOrderByColumn("phoneNumber","ASC");
1775    }
1776
1777
1778
1779    // WebDocWf extension for extended wildcard support
1780
// The following lines have been added:
1781

1782    /**
1783     * Set the phoneNumber to query with a user wildcard string
1784     *
1785     * @param x The phoneNumber of the person to query with user wildcards
1786     *
1787     * @exception DataObjectException If a database access error occurs.
1788     *
1789     * @deprecated Use comparison operators instead
1790     *
1791     * WebDocWf extension
1792     *
1793     */

1794    public void setUserMatchPhoneNumber( String JavaDoc x )
1795    throws DataObjectException, QueryException {
1796        String JavaDoc y = convertUserSearchValue( x );
1797        setDBMatchPhoneNumber( y );
1798    }
1799
1800
1801
1802    /**
1803     * Set the phoneNumber to query with a DB wildcard string
1804     *
1805     * @param x The phoneNumber of the person to query with DB wildcards
1806     *
1807     * @exception DataObjectException If a database access error occurs.
1808     *
1809     * @deprecated Use comparison operators instead
1810     *
1811     * WebDocWf extension
1812     *
1813     */

1814    public void setDBMatchPhoneNumber(String JavaDoc x )
1815    throws DataObjectException, QueryException {
1816        if (containsWildcards(x) || builder.getUserStringAppendWildcard()) {
1817            builder.addMatchClause( PersonDO.PhoneNumber, x );
1818            hitDb = true;
1819        } else
1820            setQueryPhoneNumber( x, QueryBuilder.EQUAL );
1821    }
1822
1823
1824    // end of WebDocWf extension for extended wildcard support
1825

1826    /**
1827     * Returns the <code>QueryBuilder</code> that this <code>PersonQuery</code>
1828     * uses to construct and execute database queries.
1829     * <code>PersonQuery.setQueryXXX</code> methods use
1830     * the <code>QueryBuilder</code> to
1831     * append SQL expressions to the <code>"WHERE"</code> clause to be executed.
1832     * The <code>QueryBuilder.addEndClause method.</code> can be used to
1833     * append freeform SQL expressions to the <code>WHERE</code> clause,
1834     * e.g. "ORDER BY name".
1835     *
1836     * <b>Notes regarding cache-enabled DO classes:</b>
1837     * DO classes can be cache-enabled.
1838     * If when using a <code>PersonQuery</code>, the application developer
1839     * <b>does not call</b> <code>getQueryBuilder</code>,
1840     * then <code>PersonQuery.setQueryXXX</code> methods
1841     * simply prune the DO cache and return the remaining results.
1842     * However, a <code>QueryBuilder</code> builds
1843     * <CODE>SELECT</CODE> statements for execution by the actual database,
1844     * and never searches the built-in cache for the DO.
1845     * So, if the DO class is cache-enabled, and <code>getQueryBuilder</code>
1846     * is called, this <CODE>PersonQuery</CODE> object ignores the cache
1847     * and hits the actual database.
1848     *
1849     * @return QueryBuilder that is used to construct and execute database queries.
1850     */

1851    public QueryBuilder getQueryBuilder() {
1852         hitDb = true;
1853        return builder;
1854    }
1855
1856    /**
1857     * Insert an <CODE>OR</CODE> between <CODE>WHERE</CODE> clauses.
1858     * Example: find all the persons named Bob or Robert:
1859     * <CODE>
1860     * PersonQuery pq = new PersonQuery();
1861     * pq.setQueryFirstName( "Bob" );
1862     * pq.or();
1863     * pq.setQueryFirstName( "Robert" );
1864     * </CODE>
1865     *
1866     * Note: Calls to <CODE>setQueryXxx</CODE> methods
1867     * are implicitly <CODE>AND</CODE>ed together,
1868     * so the following example will always return nothing:
1869     * <CODE>
1870     * PersonQuery pq = new PersonQuery();
1871     * pq.setQueryFirstName( "Bob" );
1872     * // AND automatically inserted here.
1873     * pq.setQueryFirstName( "Robert" );
1874     * </CODE>
1875
1876     *
1877     * NOTE: The DO cache does not yet support the OR operator.
1878     * Using the or() method forces the query to hit the database.
1879
1880     *
1881     * @see QueryBuilder to construct more elaborate queries.
1882     * @author Jay Gunter
1883     */

1884    public void or() {
1885        hitDb = true;
1886        builder.addWhereOr();
1887    }
1888
1889    /**
1890     * Place an open parenthesis in the <CODE>WHERE</CODE> clause.
1891     * Example usage: find all the Bobs and Roberts who are 5 or 50 years old:
1892     * <CODE>
1893     * PersonQuery pq = new PersonQuery();
1894     * pq.openParen();
1895     * pq.setQueryFirstName( "Bob" );
1896     * pq.or();
1897     * pq.setQueryFirstName( "Robert" );
1898     * pq.closeParen();
1899     * // AND automatically inserted here.
1900     * pq.openParen();
1901     * pq.setQueryAge( 5 );
1902     * pq.or();
1903     * pq.setQueryAge( 50 );
1904     * pq.closeParen();
1905     * </CODE>
1906    
1907     *
1908     * NOTE: The DO cache does not yet support the Open Paren operator.
1909     * Using the openParen() method forces the query to hit the database.
1910    
1911     *
1912     * @see QueryBuilder to construct more elaborate queries.
1913     * @author Jay Gunter
1914     */

1915    public void openParen() {
1916        hitDb = true;
1917        builder.addWhereOpenParen();
1918    }
1919
1920    /**
1921     * Place a closing parenthesis in the <CODE>WHERE</CODE> clause.
1922    
1923     *
1924     * NOTE: The DO cache does not yet support the Close Paren operator.
1925     * Using the closeParen() method forces the query to hit the database.
1926    
1927     *
1928     * @see openParen
1929     * @author Jay Gunter
1930     */

1931    public void closeParen() {
1932        hitDb = true;
1933        builder.addWhereCloseParen();
1934    }
1935}
1936
Popular Tags