KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > daffodilwoods > daffodildb > client > RecordSetBuffer


1 package com.daffodilwoods.daffodildb.client;
2
3 import java.sql.*;
4 import java.util.*;
5
6 import com.daffodilwoods.daffodildb.server.datadictionarysystem.*;
7 import com.daffodilwoods.daffodildb.server.sql99.common.*;
8 import com.daffodilwoods.daffodildb.server.sql99.dql.listenerevents.*;
9 import com.daffodilwoods.daffodildb.server.sql99.dql.resultsetmetadata.*;
10 import com.daffodilwoods.database.resource.*;
11 import com.daffodilwoods.database.utility.*;
12 import com.daffodilwoods.rbtreesizesequence.*;
13
14 /*
15  * Maintains the records of the table acc. for the given selectIterator
16  * Is a buffer for records Fetched
17  * Provides itertator for navigating the records
18  * Provides facility of searching a record for given condition
19  * Provides facility for Updating,deleting and inserting a record
20  */

21
22
23 /*
24  * This functioning of this is dependent on functioning of
25    - <Retriver>
26    - <RBTreeSizeSequenceDiscrete>
27  */

28 public class RecordSetBuffer implements _RecordSetBuffer, RBTreeSizeSequenceUser {
29    /* the number of records to be fetched in one call*/
30
31    int fetchSize = 50;
32
33    /* type of records */
34
35    _SelectIterator selectIterator;
36    private Object JavaDoc[] parameters;
37    private String JavaDoc query;
38
39
40    /* the List in which the records are maintained */
41
42    _AllColumnRowReader rowReader;
43    /* used for retriving records */
44
45    ArrayList recordSetBufferIteratorsList;
46    ArrayList dataOperationListenerList;
47
48    RBTreeSimple recordList;
49    private _ColumnCharacteristics columnCharacteristics;
50    private _SelectColumnCharacteristics scc;
51    RSBKeyComparator comparator;
52
53    private int fetchDirection = 0; // forward -1 backward;
54
private int maxRows = 0; // all rows;
55
private int maxFieldSize = 0; // no data truncation;
56

57    private boolean fetchedAll = false;
58
59
60    private boolean immediate;
61    private _Record insertedRecord;
62
63
64    private boolean flushData = false;
65    private int BUFFERSIZE = 500;
66    private UnFetchStatus unFetchedStatus;
67
68    public RecordSetBuffer() {
69       recordSetBufferIteratorsList = new ArrayList();
70       dataOperationListenerList = new ArrayList();
71       unFetchedStatus = new UnFetchStatus();
72    }
73
74    public void setQuery(String JavaDoc query) {
75       this.query = query;
76    }
77
78    public String JavaDoc getQuery() {
79       return query;
80    }
81
82
83
84    public void setFetchDirection(int direction) {
85       this.fetchDirection = direction;
86    }
87
88    public void setMaxRows(int maxRows) {
89       this.maxRows = maxRows;
90    }
91
92    public void setMaxFieldSize(int maxSize) {
93       this.maxFieldSize = maxSize;
94    }
95
96    public _SelectColumnCharacteristics getColumnCharacteristics() {
97       return scc;
98    }
99
100    public void setClientUserSession(_ClientUserSession clientUserSession) {
101    }
102
103    public _SelectIterator getSelectIterator() {
104       return selectIterator;
105    }
106
107    public _RowReader getRowReader() {
108       return rowReader;
109    }
110
111    public String JavaDoc getTable() {
112       return "";
113    }
114
115    public void setParameters(Object JavaDoc[] parameters) {
116       this.parameters = parameters;
117    }
118
119    public Object JavaDoc[] getParameters() {
120       return parameters;
121    }
122
123    public Comparator getComparator() {
124       return comparator;
125    }
126
127    public void addDataOperationListener(DataOperationListener listener) throws DException {
128       dataOperationListenerList.add(listener);
129    }
130
131    public void removeDataOperationListener(DataOperationListener listener) throws DException {
132       boolean flag = dataOperationListenerList.remove(listener);
133    }
134
135    private void fireDataOperation(DataOperation dataOperation) {
136       Object JavaDoc[] listeners = dataOperationListenerList.toArray();
137       if (listeners != null)
138          for (int i = 0; i < listeners.length; i++) {
139             ( (DataOperationListener) listeners[i]).operationPerformed(dataOperation);
140          }
141    }
142
143    private Object JavaDoc insert(Object JavaDoc values) throws DException {
144       if (values == null) {
145          throw new DException("DSE1051", null);
146       }
147       RBTreeLocationId locationId = new RBTreeLocationId(values, comparator.getOrderValues(values));
148       try {
149          recordList.insert(locationId);
150       } catch (Exception JavaDoc ex) {
151          throw new DException("DSE5030", new Object JavaDoc[] {toString()});
152       }
153
154       Object JavaDoc key = recordList.locateNearestKey(locationId);
155       RSBKey rsbKey = new RSBKey(comparator, key, values);
156       if (!fetchedAll) {
157          unFetchedStatus.setFetched(locationId, true);
158          unFetchedStatus.setFetched(locationId, false);
159       }
160       fireDataOperationForInsert(rsbKey);
161       if (rowCount != -1)
162          rowCount++;
163       return rsbKey;
164    }
165
166    /**
167     * deletes the specified record
168     * @ param record : the record to be deleted
169     **/

170    private void delete(RSBKey rsbKey) throws DException {
171       try {
172          RBTreeLocationId locationId = new RBTreeLocationId(rsbKey.values, comparator.getOrderValues(rsbKey.values));
173          Object JavaDoc previousRbTreeKey = recordList.getTreePrevious(rsbKey.rbtreeKey);
174          RBTreeLocationId previousLocationId = null;
175          RBTreeLocationId nextLocationId = null;
176          RSBKey upperKey = previousRbTreeKey == null ? null : new RSBKey(comparator, previousRbTreeKey, (previousLocationId = (RBTreeLocationId) recordList.getObjectAtKey(previousRbTreeKey)).values);
177          Object JavaDoc nextRbTreeKey = recordList.getTreeNext(rsbKey.rbtreeKey);
178          RSBKey lowerKey = nextRbTreeKey == null ? null : new RSBKey(comparator, nextRbTreeKey, (nextLocationId = (RBTreeLocationId) recordList.getObjectAtKey(nextRbTreeKey)).values);
179          recordList.delete(locationId);
180          if (!fetchedAll) {
181             if (!unFetchedStatus.isFetched(locationId, true) && lowerKey != null)
182                if (unFetchedStatus.isFetched(nextLocationId, false))
183                   unFetchedStatus.setFetched(nextLocationId, false);
184             if (!unFetchedStatus.isFetched(locationId, false) && upperKey != null)
185                if (unFetchedStatus.isFetched(previousLocationId, true))
186                   unFetchedStatus.setFetched(previousLocationId, true);
187             unFetchedStatus.remove(locationId);
188          }
189          fireDataOperationForDelete(rsbKey, upperKey, lowerKey);
190          if (rowCount != -1)
191             rowCount--;
192       } catch (SQLException ex) {
193          throw new DException("DSE5029", new Object JavaDoc[] {ex.getMessage()});
194       } catch (DException ex) {
195          throw new DException(ex.getDseCode(), ex.getParameters());
196       }
197    }
198
199    private void moveToNearestKeyIfCurrentInIterators(RSBKey rsbKey) throws SQLException {
200
201       RBTreeLocationId locationId1 = null;
202       try {
203          locationId1 = new RBTreeLocationId(rsbKey.values, comparator.getOrderValues(rsbKey.values));
204       } catch (DException de) {
205          throw new SQLException(de.getMessage());
206       }
207       for (int i = 0; i < recordSetBufferIteratorsList.size(); i++) {
208          RecordSetBufferIterator recordSetBufferIterator = (RecordSetBufferIterator) recordSetBufferIteratorsList.get(i);
209          Object JavaDoc currentKey = recordSetBufferIterator.currentKey;
210          if (currentKey != null)
211             if (currentKey.equals(rsbKey)) {
212                Object JavaDoc nearestKey = recordList.locateNearestKey(locationId1);
213                if (nearestKey == null)
214                   recordSetBufferIterator.currentKey = null;
215                else
216                   recordSetBufferIterator.moveToKey(new RSBKey(comparator, nearestKey, ( (RBTreeLocationId) (recordList.getObjectAtKey(nearestKey))).values));
217             }
218       }
219
220    }
221
222    private void fireDataOperationForDelete(RSBKey rsbKey, RSBKey upperKey, RSBKey lowerKey) throws SQLException, DException {
223
224       DPRecord record = getRecordForKeyInCaseOfDelete(rsbKey);
225       moveToNearestKeyIfCurrentInIterators(rsbKey);
226       DataOperation dataOperation = new DataOperation(this, DataOperation.DELETE, record.getIdentity(),
227           rsbKey, null, null, null);
228       dataOperation.upperKey = upperKey;
229       dataOperation.lowerkey = lowerKey;
230       if (upperKey != null) {
231          dataOperation.upperRecordIdentity = getRecordForKey(upperKey);
232       }
233       if (lowerKey != null) {
234          dataOperation.lowerRcordIdentity = getRecordForKey(lowerKey);
235       }
236       dataOperation.record = record;
237       fireDataOperation(dataOperation);
238    }
239
240    private void fireDataOperationForInsert(RSBKey rsbKey) throws DException {
241       try {
242          DPRecord record = getRecordForKey(rsbKey);
243          DataOperation dataOperation = new DataOperation(this, DataOperation.INSERT, record.getIdentity(), rsbKey, null, null, null);
244          dataOperation.record = record;
245          fireDataOperation(dataOperation);
246       } catch (SQLException ex) {
247          throw new DException("DSE5030", new Object JavaDoc[] {ex.getMessage()});
248       }
249
250    }
251
252    private DPRecord getRecordForKey(RSBKey rsbKey) throws SQLException {
253       DPRecord record = new DPRecord();
254       loadRecordForKey(record, rsbKey);
255
256       return record;
257    }
258
259    private int rowCount = -1;
260    public int getRowCount() throws SQLException {
261       if (rowCount != -1)
262          return rowCount;
263       Object JavaDoc o = getTopKey();
264       int cnt = 0;
265       while (o != null) {
266          cnt++;
267          o = getNextKey(o);
268       }
269       rowCount = cnt;
270       return rowCount;
271
272    }
273
274
275    public _Record getInsertedRecord() throws DException {
276
277       if (!scc.isUpdatable())
278          throw new DException("DSE5031", new Object JavaDoc[] {query}); // cannot update in this type of query.
279
if (insertedRecord != null) {
280          throw new DException("DSE7052", null);
281
282       }
283       Object JavaDoc row = selectIterator.moveToInsertRow();
284       DPRecord record = new DPRecord();
285       record.setBuffer(this);
286       try {
287          record.setValues(row);
288       } catch (SQLException ex) {
289          throw new DException("DSE5032", new Object JavaDoc[] {ex.getMessage()});
290       }
291       record.setInserted(true);
292       insertedRecord = record;
293       return record;
294    }
295
296    /**
297     * calls the <selectIterator.insert>
298     * returns the current key of the recordList
299     **/

300    public Object JavaDoc insertInitiate(String JavaDoc[] columNames, Object JavaDoc[] columnValues) throws DException {
301       throw new UnsupportedOperationException JavaDoc(" this method is to be removed use getInsertedRecord and then insertRow");
302    }
303
304    public Object JavaDoc insertRow() throws DException {
305       if (insertedRecord == null)
306          throw new DException("DSE7053", null);
307       DPRecord dpRecord = (DPRecord) insertedRecord;
308       int[] columns = dpRecord.getUpdatedColumns();
309       Object JavaDoc[] columnValues = dpRecord.getValuesForUpdation();
310       if (columns != null)
311          for (int i = 0; i < columns.length; i++) {
312             if (!scc.isColumnUpdatable(columns[i]))
313                throw new DException("DSE5034", new Object JavaDoc[] {columnCharacteristics.getColumnName(columns[i]), query}); // you ann't update this column
314
}
315
316       Object JavaDoc row = null;
317       try {
318          row = selectIterator.insert(columns, columnValues);
319       } catch (DException ex) {
320          String JavaDoc[] columnNames = columns == null ? null : new String JavaDoc[columns.length];
321          if (columns != null)
322             for (int i = 0; i < columns.length; i++)
323                columnNames[i] = columnCharacteristics.getColumnName(columns[i]);
324          throw ex;
325
326       }
327       Object JavaDoc key = row == null ? null : getKeyAtPrimaryKey(rowReader.getKey(row));
328
329       if (browserType && key == null && row != null) {
330          key = insert(row);
331       }
332       insertedRecord = null;
333       return key;
334    }
335
336    /**
337     * @ param recordId - is <the conditionMaker> object which is
338     * to be updated
339     * columnName - is the name of the column to be updated
340     * value - is the new value
341     * * Algo :-
342     * 1. calls the <selectIterator.update>
343     * 2. retuns the current key after updation in recordList.
344     **/

345    public void updateRow(_Record record) throws DException, SQLException {
346
347       if (insertedRecord != null && insertedRecord == record)
348          throw new DException("DSE7054", null);
349       DPRecord dpRecord = (DPRecord) record;
350       if (!dpRecord.canUpdate)
351          throw new SQLException(" YOU ARE UPDATING THE RECORD AGAIN WHOSE UPDATION IS GOING ON ");
352       dpRecord.canUpdate = false;
353       try {
354          int[] columns = dpRecord.getUpdatedColumns();
355          if (columns == null) {
356             dpRecord.canUpdate = true;
357             return;
358          }
359          if (immediate && (record != null))
360             throw new DException("DSE7055", null);
361
362          Object JavaDoc[] columnValues = dpRecord.getValuesForUpdation();
363          int noOfColumnsUpdated = columns.length;
364          RSBKey oldKey = (RSBKey) dpRecord.getKey();
365          for (int i = 0; i < noOfColumnsUpdated; i++) {
366             if (!scc.isColumnUpdatable(columns[i]))
367                throw new DException("DSE5034", new Object JavaDoc[] {columnCharacteristics.getColumnName(columns[i]), query}); // you cann't update this column
368
}
369          Object JavaDoc updateRow = null;
370          try {
371             updateRow = selectIterator.update(rowReader.getKey(dpRecord.getValues()), columns, columnValues, dpRecord.getValues());
372          } catch (DException ex) {
373             String JavaDoc[] columnNames = columns == null ? null : new String JavaDoc[columns.length];
374             if (columns != null)
375                for (int i = 0; i < columns.length; i++)
376                   columnNames[i] = columnCharacteristics.getColumnName(columns[i]);
377             throw ex;
378          }
379          if (updateRow == null)
380             throw new DException("DSE1043", null);
381          Object JavaDoc key = getKeyAtPrimaryKey(rowReader.getKey(updateRow)); //getKeyAtRecordIdentity(updateKey);
382
dpRecord.flushUpdateColumnsAndValues();
383          if (key != null) {
384             if (browserType && oldKey.equals(key)) {
385                Object JavaDoc values = ( (RSBKey) key).values;
386                Object JavaDoc[] oldValues = new Object JavaDoc[noOfColumnsUpdated];
387                Object JavaDoc[] newValues = new Object JavaDoc[noOfColumnsUpdated];
388                boolean eventFired = true;
389                for (int i = 0; i < noOfColumnsUpdated; i++) {
390                   oldValues[i] = rowReader.getObject(columns[i], values);
391                   newValues[i] = rowReader.getObject(columns[i], updateRow);
392                   boolean compare = oldValues[i] == null ?
393                       newValues[i] == null ? true : false :
394                       newValues[i] == null ? false :
395                       oldValues[i].equals(newValues[i]);
396                   if (!compare)
397                      eventFired = false;
398                }
399                if (!eventFired) {
400                   updateAndNotifyFrontend( ( (RSBKey) key), columns, newValues, oldValues, updateRow);
401                }
402             }
403             loadRecordForKey( (_Record) dpRecord, key);
404          }
405       } finally {dpRecord.canUpdate = true;
406       }
407
408    }
409
410    private void updateAndNotifyFrontend(RSBKey rsbKey, int[] columnIndexes, Object JavaDoc[] newValues, Object JavaDoc[] oldValues, Object JavaDoc newRow) throws DException {
411       try {
412          Object JavaDoc rbtreeKey = rsbKey.rbtreeKey;
413          Object JavaDoc values = rsbKey.values;
414          DPRecord record = new DPRecord();
415          record.setBuffer(this);
416          record.setKey(rsbKey);
417          record.setValues(values);
418          rowReader.setObjects(values, newRow, columnIndexes);
419          DataOperation dataOperation = new DataOperation(this, DataOperation.UPDATE,
420              record.getIdentity(), rsbKey, columnIndexes, oldValues, newValues);
421          dataOperation.record = record;
422          fireDataOperation(dataOperation);
423       } catch (SQLException sq) {
424          throw new RuntimeException JavaDoc(sq.getMessage());
425       }
426    }
427
428    /**
429     * @ param deleteRecord- is <DPRecord> object which is
430     * to be deleted
431     * Algo :-
432     * 1. calls the <selectIterator.delete>
433     * 2. retuns the nearest key in recordList.
434     **/

435
436
437    public Object JavaDoc deleteRow(_Record deleteRecord) throws DException {
438       if (insertedRecord != null && insertedRecord == deleteRecord)
439          throw new DException("DSE5037", null);
440       DPRecord record = (DPRecord) deleteRecord;
441       Object JavaDoc values = record.getValues();
442       Object JavaDoc keys = rowReader.getKey(values);
443       try {
444          selectIterator.delete(keys);
445       } catch (DException ex) {
446          throw ex;
447
448       }
449       RBTreeLocationId locationId = new RBTreeLocationId(values, comparator.getOrderValues(values));
450       Object JavaDoc deletedKey = getKeyAtPrimaryKey(keys);
451       if (browserType && deletedKey != null) {
452          delete( (RSBKey) deletedKey);
453       }
454       Object JavaDoc nearestKey = recordList.locateNearestKey(locationId);
455       Object JavaDoc newKey = nearestKey == null ? null : new RSBKey(comparator, nearestKey, ( (RBTreeLocationId) recordList.getObjectAtKey(nearestKey)).values);
456       return newKey;
457    }
458
459    /**
460     * return an iterator for nagivation.
461     **/

462    public _RecordSetBufferIterator getIterator() throws SQLException {
463       RecordSetBufferIterator recordSetBufferIterator = new RecordSetBufferIterator();
464       recordSetBufferIterator.setRecordSetBuffer(this);
465       recordSetBufferIteratorsList.add(recordSetBufferIterator);
466       return recordSetBufferIterator;
467    }
468
469    public RBTreeSimple getRecordList() {
470       return recordList;
471    }
472
473    public _Record getRecord() {
474
475       DPRecord record = new DPRecord();
476       return (_Record) record;
477
478    }
479
480    /* set the number of records to be fetched at a time*/
481    public void setFetchSize(int fetchSize) {
482       this.fetchSize = fetchSize;
483    }
484
485    public Object JavaDoc getIdentityForKey(Object JavaDoc key) throws DException {
486
487       if (key == null) {
488          throw new DException("DSE550", null);
489       }
490       try {
491          return getRecordForKey( (RSBKey) key);
492       } catch (SQLException ex) {
493          throw new RuntimeException JavaDoc(ex.getMessage());
494       }
495    }
496
497    public Object JavaDoc getKeyForIdentity(Object JavaDoc recordIdentity) throws DException {
498
499       if (insertedRecord != null && recordIdentity == insertedRecord) {
500          throw new DException(" can't call this method of the inserted Record", null);
501       }
502
503       if (recordIdentity == null || ! (recordIdentity instanceof _Record)) {
504          throw new DException("DSE991", new Object JavaDoc[] {recordIdentity});
505       }
506       return ( (DPRecord) recordIdentity).getKey();
507    }
508
509    private Object JavaDoc getKeyAtPrimaryKey(Object JavaDoc primaryKey) throws DException {
510
511       Object JavaDoc rbtreeKey = getBTreeKeyAtPrimaryKey(primaryKey);
512       if (rbtreeKey == null)
513          return null;
514       return new RSBKey(comparator, rbtreeKey, ( (RBTreeLocationId) recordList.getObjectAtKey(rbtreeKey)).values);
515
516    }
517
518    private Object JavaDoc getBTreeKeyAtPrimaryKey(Object JavaDoc primaryKey) throws DException {
519
520       try {
521          Object JavaDoc key = recordList.getTreeTopKey();
522          while (key != null) {
523             Object JavaDoc values = ( (RBTreeLocationId) recordList.getObjectAtKey(key)).values;
524             Object JavaDoc pk = rowReader.getKey(values);
525
526             if (comparator.getComparator().compare(primaryKey, pk) == 0) {
527                return key;
528             }
529             key = recordList.getTreeNext(key);
530          }
531       } catch (DException e) {
532          e.printStackTrace();
533          throw new DException(e.getDseCode(), e.getParameters());
534       }
535       return null;
536    }
537
538    public Object JavaDoc seek(String JavaDoc clause) throws SQLException {
539       throw new UnsupportedOperationException JavaDoc(" this method will be removed ");
540    }
541
542    public void loadRecordForIdentity(_Record record, Object JavaDoc recordIdentity) throws SQLException {
543
544       try {
545          if (insertedRecord != null && recordIdentity == insertedRecord)
546             throw new DException("DSE5038", null);
547          if (recordIdentity == null || ! (recordIdentity instanceof _Record))
548             throw new DException("DSE992", new Object JavaDoc[] {recordIdentity}).getSqlException(null);
549          DPRecord drecord = (DPRecord) record;
550          drecord.setBuffer(this);
551          DPRecord rec = ( (DPRecord) recordIdentity);
552          drecord.setValues(rec.getValues());
553          drecord.setKey(rec.getKey());
554          drecord.flushUpdateColumnsAndValues();
555       } catch (Exception JavaDoc E) {
556          throw new SQLException(new DException("DSE358", new Object JavaDoc[] {E.getMessage()}).getMessage());
557       }
558
559    }
560
561    public void loadRecordForKey(_Record record, Object JavaDoc key) throws SQLException {
562
563       if (key == null)
564          throw new SQLException(new DException("DSE550", null).getMessage());
565       RBTreeLocationId locaationId = (RBTreeLocationId) recordList.getObjectAtKey( ( (RSBKey) key).rbtreeKey);
566       if (locaationId == null)
567          throw new SQLException(new DException("DSE552", new Object JavaDoc[] {key}).getMessage());
568       DPRecord drecord = (DPRecord) record;
569       drecord.setBuffer(this);
570       try {
571          drecord.setValues( ( (RSBKey) key).values);
572       } catch (ArrayIndexOutOfBoundsException JavaDoc ex) {
573          throw ex;
574       }
575       drecord.setKey(key);
576       drecord.flushUpdateColumnsAndValues();
577    }
578
579    private DPRecord getRecordForKeyInCaseOfDelete(Object JavaDoc key) throws SQLException {
580
581       if (key == null)
582          throw new SQLException(new DException("DSE550", null).getMessage());
583       DPRecord drecord = new DPRecord();
584       drecord.setBuffer(this);
585       drecord.setValues( ( (RSBKey) key).values);
586       drecord.setKey(key);
587       return drecord;
588    }
589
590    public Object JavaDoc getTopKey() throws SQLException {
591       try {
592          Object JavaDoc key = recordList.getTopKey();
593          return key == null ? null : new RSBKey(comparator, key, ( (RBTreeLocationId) recordList.getObjectAtKey(key)).values);
594       } catch (RuntimeException JavaDoc ex) {
595          throw new SQLException(" query : ->[" + query + "] parameters : -> [" + (parameters == null ? null : Arrays.asList(parameters)) + "] error message == " + ex.getMessage());
596       }
597    }
598
599    public Object JavaDoc getNextKey(Object JavaDoc key) throws SQLException {
600       if (key == null)
601          throw new DException("DSE550", null).getSqlException(null);
602       Object JavaDoc nextKey = recordList.getNext( ( (RSBKey) key).rbtreeKey);
603       return nextKey == null ? null : new RSBKey(comparator, nextKey, ( (RBTreeLocationId) recordList.getObjectAtKey(nextKey)).values);
604    }
605
606    public boolean isBottom(Object JavaDoc key) throws SQLException {
607       if (key == null)
608          throw new DException("DSE550", null).getSqlException(null);
609       return getNextKey(key) == null;
610    }
611
612    public boolean isTop(Object JavaDoc key) throws SQLException {
613       if (key == null)
614          throw new DException("DSE550", null).getSqlException(null);
615       return getPreviousKey(key) == null;
616    }
617
618    public Object JavaDoc getPreviousKey(Object JavaDoc key) throws SQLException {
619       if (key == null)
620          throw new DException("DSE550", null).getSqlException(null);
621       Object JavaDoc previousKey = recordList.getPrevious( ( (RSBKey) key).rbtreeKey);
622       return previousKey == null ? null : new RSBKey(comparator, previousKey, ( (RBTreeLocationId) recordList.getObjectAtKey(previousKey)).values);
623    }
624
625    public Object JavaDoc getBottomKey() throws SQLException {
626       Object JavaDoc key = recordList.getBottomKey();
627       return key == null ? null : new RSBKey(comparator, key, ( (RBTreeLocationId) recordList.getObjectAtKey(key)).values);
628    }
629
630    public Object JavaDoc locateNearestKey(Object JavaDoc key) throws SQLException {
631       if (key == null)
632          throw new DException("DSE550", null).getSqlException(null);
633       RSBKey rsbKey = (RSBKey) key;
634       try {
635          RBTreeLocationId locationId = new RBTreeLocationId(rsbKey.values, comparator.getOrderValues(rsbKey.values));
636          Object JavaDoc nearestKey = recordList.locateNearestKey(locationId);
637          return nearestKey == null ? null : new RSBKey(comparator, nearestKey, ( (RBTreeLocationId) recordList.getObjectAtKey(nearestKey)).values);
638       } catch (DException de) {
639          throw new SQLException(de.getMessage());
640       }
641    }
642
643    public long traceDistance(Object JavaDoc locationId1, Object JavaDoc locationId2, int max) {
644       try {
645          Object JavaDoc currentRecordId = locationId1 == null ? null : rowReader.getKey( ( (RBTreeLocationId) locationId1).values);
646          Object JavaDoc blockRecordId = locationId2 == null ? null : rowReader.getKey( ( (RBTreeLocationId) locationId2).values);
647          boolean directionForFetch = max > 0;
648          if (fetchedAll || (unFetchedStatus.isFetched(locationId1, directionForFetch) && unFetchedStatus.isFetched(locationId2, !directionForFetch)))
649             return getTracedDistance(locationId1, locationId2, max);
650
651          int requiredFetchedSizePassed = Math.abs(max);
652          Object JavaDoc[] fetchResults = null; // retriever.fetchRows(currentRecordId,blockRecordId,requiredFetchedSize,directionForFetch);
653
if (currentRecordId == null && directionForFetch) {
654             if (unFetchedStatus.isFetched(locationId2, false))
655                return getTracedDistance(locationId1, locationId2, max);
656             selectIterator.beforeFirst();
657             fetchResults = getRequiredResult(selectIterator.fetchForward(fetchSize), blockRecordId, requiredFetchedSizePassed, directionForFetch);
658          } else if (currentRecordId == null && !directionForFetch) {
659             if (unFetchedStatus.isFetched(locationId2, true))
660                return getTracedDistance(locationId1, locationId2, max);
661             selectIterator.afterLast();
662             fetchResults = getRequiredResult(selectIterator.fetchBackward(fetchSize), blockRecordId, requiredFetchedSizePassed, directionForFetch);
663          } else {
664             if (blockRecordId == null) {
665                if (unFetchedStatus.isFetched(locationId1, directionForFetch))
666                   return getTracedDistance(locationId1, locationId2, max);
667             }
668             int deleteCount = 0;
669             try {
670                selectIterator.moveToRow(currentRecordId);
671             } catch (DException ex) {
672                /** @todo check for dse code in case of invalid key */
673
674                boolean notfound = true;
675                Object JavaDoc nearestKey = recordList.locateNearestKey(locationId1);
676                Object JavaDoc newKey = null;
677                Object JavaDoc newValue = null;
678                while (notfound) {
679                   deleteCount++;
680                   newKey = directionForFetch ? recordList.getTreePrevious(nearestKey) : recordList.getTreeNext(nearestKey);
681                   Object JavaDoc keyToBeDeleted = getKeyAtPrimaryKey(currentRecordId);
682                   delete( (RSBKey) keyToBeDeleted);
683
684                   if (newKey == null) {
685                      locationId1 = null;
686                      currentRecordId = null;
687                      notfound = false;
688                      if (directionForFetch)
689                         selectIterator.beforeFirst();
690                      else
691                         selectIterator.afterLast();
692                      break;
693                   }
694                   locationId1 = recordList.getObjectAtKey(newKey);
695                   currentRecordId = locationId1 == null ? null : rowReader.getKey( ( (RBTreeLocationId) locationId1).values);
696                   try {
697                      selectIterator.moveToRow(currentRecordId);
698                   } catch (DException ex1) {
699                      nearestKey = newKey;
700                      continue;
701                   }
702                   notfound = false;
703                }
704             }
705             fetchResults = directionForFetch
706                 ? getRequiredResult(selectIterator.fetchForward(fetchSize), blockRecordId, requiredFetchedSizePassed, directionForFetch)
707                 : getRequiredResult(selectIterator.fetchBackward(fetchSize), blockRecordId, requiredFetchedSizePassed, directionForFetch);
708          }
709          return appendData(fetchResults, locationId1, locationId2, directionForFetch, requiredFetchedSizePassed == 1 ? fetchSize : requiredFetchedSizePassed);
710       } catch (DException ex) {
711          throw new RuntimeException JavaDoc(ex.getMessage());
712       }
713    }
714
715    private Object JavaDoc[] getRequiredResult(Object JavaDoc[] result, Object JavaDoc blockKey, int max, boolean direction) throws DException {
716
717       if (result == null || (blockKey == null && max < fetchSize))
718          return result;
719       ArrayList requiredResult = new ArrayList();
720       try {
721          if (max > fetchSize) {
722             int len1 = result.length;
723             if (blockKey == null && len1 < fetchSize)
724                return result;
725             while (true) {
726                if (blockKey != null) {
727                   for (int i = 0; i < result.length; i++) {
728                      if (comparator.getComparator().compare(blockKey, rowReader.getKey(result[i])) == 0)
729                         return requiredResult.toArray();
730                      requiredResult.add(result[i]);
731                   }
732                } else {
733                   int len = result.length;
734                   for (int i = 0; i < len; i++)
735                      requiredResult.add(result[i]);
736                   if (len < fetchSize)
737                      return requiredResult.toArray();
738                }
739                int noOfRecords = result.length;
740                Object JavaDoc key = rowReader.getKey(result[noOfRecords - 1]);
741                selectIterator.moveToRow(key);
742                result = direction ? selectIterator.fetchForward(fetchSize)
743                    : selectIterator.fetchBackward(fetchSize);
744                if (result == null)
745                   return requiredResult.toArray();
746             }
747
748          } else {
749             for (int i = 0; i < result.length; i++) {
750                if (comparator.getComparator().compare(blockKey, rowReader.getKey(result[i])) == 0)
751                   return requiredResult.toArray();
752                requiredResult.add(result[i]);
753             }
754
755          }
756          return requiredResult.toArray();
757
758       } finally {
759       }
760
761    }
762
763    private long getTracedDistance(Object JavaDoc locationId1, Object JavaDoc locationId2, int max) {
764       int distance = locationId1 == null || locationId2 == null ? 0 : (max > 0 ? 1 : -1);
765       if (distance != 0) {
766          if (comparator.compare(locationId1, locationId2) != 0) {
767             recordList.add(locationId1, distance, locationId2);
768          } else
769             distance = 0;
770       }
771       long actualDistance = com.daffodilwoods.rbtreesizesequence.utils.sizesequenceutility.RBTreeSizeSequenceUtility.getLong(distance, 0);
772       return actualDistance;
773    }
774
775    private long appendData(Object JavaDoc[] fetchResults, Object JavaDoc currentlocationId, Object JavaDoc blockLocationId, boolean directionForFetch, int requiredFetchSize) {
776       try {
777          int fetchedRecordCount = fetchResults == null ? 0 : fetchResults.length;
778          int atDistance = directionForFetch ? 1 : -1;
779          int actualRowCount = fetchedRecordCount;
780          if (fetchedRecordCount != 0) {
781             RBTreeLocationId previousLocationId = new RBTreeLocationId(fetchResults[0], comparator.getOrderValues(fetchResults[0]));
782             RBTreeLocationId nextLocationId = null;
783             recordList.add(currentlocationId, atDistance, previousLocationId);
784             if (currentlocationId != null)
785                unFetchedStatus.setFetched(currentlocationId, directionForFetch);
786             for (int i = 1; i < fetchedRecordCount; i++) {
787                Object JavaDoc o = comparator.getOrderValues(fetchResults[i]);
788                nextLocationId = new RBTreeLocationId(fetchResults[i], o);
789                recordList.add(previousLocationId, atDistance, nextLocationId);
790                previousLocationId = nextLocationId;
791             }
792             if (fetchedRecordCount < requiredFetchSize) {
793                if (blockLocationId != null) {
794                   recordList.add(previousLocationId, atDistance, blockLocationId);
795                   unFetchedStatus.setFetched(blockLocationId, !directionForFetch);
796                }
797             } else {
798                unFetchedStatus.setFetched(nextLocationId, directionForFetch);
799             }
800          } else {
801             if (currentlocationId != null && blockLocationId != null) {
802                recordList.add(currentlocationId, atDistance, blockLocationId);
803                fetchedRecordCount = atDistance;
804             }
805             if (currentlocationId != null)
806                unFetchedStatus.setFetched(currentlocationId, directionForFetch);
807             if (blockLocationId != null)
808                unFetchedStatus.setFetched(blockLocationId, !directionForFetch);
809
810          }
811          int size = recordList.getSize();
812          if (flushData)
813             if (size > BUFFERSIZE) {
814                if (currentlocationId != null) {
815                   recordList.flushData(currentlocationId, !directionForFetch);
816                   removeKeyFromUnFetchedStatusSetApp(currentlocationId, !directionForFetch);
817                }
818                size = recordList.getSize();
819                if (size > BUFFERSIZE) {
820                   if (blockLocationId != null) {
821                      recordList.flushData(blockLocationId, directionForFetch);
822                      removeKeyFromUnFetchedStatusSetApp(blockLocationId, directionForFetch);
823                   }
824                }
825             }
826          if (unFetchedStatus.size() == 0)
827             fetchedAll = true;
828          return com.daffodilwoods.rbtreesizesequence.utils.sizesequenceutility.RBTreeSizeSequenceUtility.getLong( (currentlocationId != null && blockLocationId != null && actualRowCount != 0 ? fetchedRecordCount + 1 : fetchedRecordCount), requiredFetchSize > fetchSize ? 1 : 0);
829       } catch (DException ex) {
830          throw new RuntimeException JavaDoc(ex.getMessage());
831       } catch (IllegalArgumentException JavaDoc ex) {
832          throw ex;
833       }
834
835    }
836
837    public Object JavaDoc convertIntoParameter() throws SQLException, DException {
838
839       RecordSetBufferIterator recordSetBufferIterator = new RecordSetBufferIterator();
840       recordSetBufferIterator.setRecordSetBuffer(this);
841       if (!recordSetBufferIterator.top())
842          return null;
843       int columnCount = columnCharacteristics.getColumnCount();
844       ArrayList dataList = new ArrayList();
845       if (columnCount == 1) {
846          do {
847             dataList.add(rowReader.getObject(1, ( (RSBKey) recordSetBufferIterator.getKey()).values));
848
849          } while (recordSetBufferIterator.next());
850          return dataList.toArray();
851       }
852       do {
853          dataList.add(getValues( (RSBKey) recordSetBufferIterator.getKey(), columnCount));
854       } while (recordSetBufferIterator.next());
855       Object JavaDoc[][] dataValues = new Object JavaDoc[dataList.size()][columnCount];
856       return dataList.toArray(dataValues);
857
858    }
859
860    private Object JavaDoc[] getValues(RSBKey rsbKey, int columnCount) throws DException {
861       Object JavaDoc values = rsbKey.values;
862       Object JavaDoc[] columnValues = new Object JavaDoc[columnCount];
863       for (int i = 0; i < columnCount; i++)
864          columnValues[i] = rowReader.getObject(i + 1, values);
865       return columnValues;
866    }
867
868    public String JavaDoc toString() {
869       return "RecordSetBuffer:: query -> " + query + " query parameters -> "
870           + (parameters == null ? null : Arrays.asList(parameters).toString()) + " hashcode ->" + hashCode();
871    }
872
873    public boolean canJoin(Object JavaDoc locationId1, Object JavaDoc locationId2) {
874       boolean canJoin = comparator.compare(locationId1, locationId2) == 0;
875       return canJoin;
876    }
877
878    public int getDistance(Object JavaDoc locationId1, Object JavaDoc locationId2) {
879       return Integer.MIN_VALUE;
880    }
881
882    /* done as part of code review using find bugs tool */
883    protected void finalize() {
884       dataOperationListenerList = new ArrayList();
885    }
886
887    class RBTreeLocationId {
888       public Object JavaDoc rowKey;
889       public Object JavaDoc values;
890       int hash = 0;
891       RBTreeLocationId(Object JavaDoc values0, Object JavaDoc rowKey0) {
892          values = values0;
893          rowKey = rowKey0;
894       }
895
896       public int hashCode() {
897          int hashCode = hash;
898          if (hashCode == 0) {
899             if (rowKey != null && (rowKey instanceof Object JavaDoc[])) {
900                Object JavaDoc[] values = (Object JavaDoc[]) rowKey;
901                for (int i = 0; i < values.length; i++)
902                   hashCode += values[i] == null ?
903                       Integer.MIN_VALUE : values[i].hashCode();
904             } else
905                hashCode = rowKey == null ? -1 : rowKey.hashCode();
906          }
907          return hashCode;
908       }
909
910       public int compareTo(Object JavaDoc locationId) {
911          if (! (locationId instanceof RBTreeLocationId)) {
912             return -1;
913          }
914          try {
915             return comparator.getComparator().compare(rowKey, ( (RBTreeLocationId) locationId).rowKey);
916          } catch (DException ex) {
917             throw new RuntimeException JavaDoc(ex.getMessage());
918          }
919       }
920
921       public boolean equals(Object JavaDoc object) {
922          if (! (object instanceof RBTreeLocationId))
923             return false;
924          return compareTo(object) == 0;
925       }
926
927       public String JavaDoc toString() {
928          try {
929             return "<<<" + (values == null ? null : Arrays.asList( (Object JavaDoc[]) values)) + " -- " + ( (rowKey instanceof Object JavaDoc[]) ? Arrays.asList( (Object JavaDoc[]) rowKey) : rowKey) + ">>";
930          } catch (Exception JavaDoc ex) {
931             return "";
932          }
933       }
934    }
935
936    RBTreeLocationId getRBTreeLocationId(Object JavaDoc row, Object JavaDoc rowKey) {
937       return new RBTreeLocationId(row, rowKey);
938    }
939
940    public int getDistanceBetweenKeys(Object JavaDoc key1, Object JavaDoc key2) throws java.sql.SQLException JavaDoc {
941
942       if (recordList instanceof RBTreeSizeSequence) {
943          if (key1 == null || key2 == null)
944             throw new SQLException(new DException("DSE555", new Object JavaDoc[] {key1, key2}).getMessage());
945          RSBKey rsbKey1 = (RSBKey) key1;
946          RSBKey rsbKey2 = (RSBKey) key2;
947          Object JavaDoc locationId1 = null;
948          Object JavaDoc locationId2 = null;
949          try {
950             if (checkKeyExistance) {
951                Object JavaDoc rbTreeKey1 = getBTreeKeyAtPrimaryKey(rowReader.getKey(rsbKey1.values));
952                if (rbTreeKey1 == null)
953                   throw new SQLException(rsbKey1 + " not present in buffer " + this);
954                Object JavaDoc rbTreeKey2 = getBTreeKeyAtPrimaryKey(rowReader.getKey(rsbKey2.values));
955                if (rbTreeKey2 == null)
956                   throw new SQLException(rsbKey2 + " not present in buffer " + this);
957             }
958
959             locationId1 = new RBTreeLocationId(rsbKey1.values, comparator.getOrderValues(rsbKey1.values));
960             locationId2 = new RBTreeLocationId(rsbKey2.values, comparator.getOrderValues(rsbKey2.values));
961          } catch (DException de) {
962             throw new SQLException(de.getMessage());
963          }
964          int returnDis = ( (RBTreeSizeSequence) recordList).getDistance(locationId1, locationId2, true);
965          return returnDis;
966       }
967       throw new SQLException(" not suuported for initailzed object ");
968    }
969
970    public Object JavaDoc getKeyAtDistance(Object JavaDoc key, int distance) throws java.sql.SQLException JavaDoc {
971
972       if (key == null)
973          throw new DException("DSE550", null).getSqlException(null);
974       RSBKey rsbKey1 = (RSBKey) key;
975       Object JavaDoc locationId1 = null;
976       try {
977          locationId1 = new RBTreeLocationId(rsbKey1.values, comparator.getOrderValues(rsbKey1.values));
978       } catch (DException de) {
979          throw new SQLException(de.getMessage());
980       }
981       LocationInformation locationInformation = ( (RBTreeSizeSequence) recordList).getLocationInformation(locationId1, distance);
982       Object JavaDoc locationId = locationInformation.getLocationId();
983       Object JavaDoc rbTreeKey = recordList.locateNearestKey(locationId);
984       int distanceObtained = locationInformation.getDistance();
985       boolean flushData1 = flushData;
986       flushData = false;
987       while (distanceObtained != distance) {
988          Object JavaDoc nextPreviousKey = distance > 0 ? recordList.getNext(rbTreeKey) : recordList.getPrevious(rbTreeKey);
989          if (nextPreviousKey == null)
990             break;
991          distanceObtained = locationInformation.getDistance();
992          locationInformation = ( (RBTreeSizeSequence) recordList).getLocationInformation(locationId1, distance);
993          locationId = locationInformation.getLocationId();
994          rbTreeKey = recordList.locateNearestKey(locationId);
995       }
996       flushData = flushData1;
997       return new RSBKey(comparator, rbTreeKey, ( (RBTreeLocationId) locationId).values);
998    }
999
1000
1001   public void setSelectIterator(_SelectIterator selectIter) throws DException {
1002      this.selectIterator = selectIter;
1003      columnCharacteristics = selectIterator.getColumnCharacteristics();
1004      rowReader = (_AllColumnRowReader) selectIterator.getRowReader();
1005
1006      comparator = new RSBKeyComparator(rowReader.getComparator(), rowReader);
1007      scc = (_SelectColumnCharacteristics) columnCharacteristics;
1008      recordList = new RBTreeSizeSequence(this, 0);
1009   }
1010
1011
1012   public void setUpdateMode(boolean immediate0) {
1013      immediate = immediate0;
1014   }
1015
1016   public _Record getRecordInstance() {
1017      return new DPRecord();
1018   }
1019
1020   public _Record getDummyRecord() throws SQLException {
1021      DummyRecord dummyRecord = new DummyRecord();
1022      dummyRecord.setBuffer(this);
1023      try {
1024         dummyRecord.setValues(rowReader.getBlankRow());
1025      } catch (DException ex) {
1026         throw ex.getSqlException(null);
1027      }
1028      return dummyRecord;
1029   }
1030
1031   public void flushIfInsertedRecord(_Record record) throws DException {
1032      if (insertedRecord != null && insertedRecord == record) {
1033         selectIterator.flushInsertedRecord();
1034         insertedRecord = null;
1035      }
1036   }
1037
1038   public _ExecutionPlan getExecutionPlan() throws DException {
1039      return selectIterator.getExecutionPlan();
1040   }
1041
1042   public ExecutionPlanForBrowser getExecutionPlanForBrowser() throws DException {
1043      return selectIterator.getExecutionPlanForBrowser();
1044   }
1045
1046   public _QueryPlan getQueryPlan() throws DException {
1047      return selectIterator.getQueryPlan();
1048   }
1049
1050   public void flushRecords(Object JavaDoc key, boolean direction) throws DException {
1051      RSBKey rsbKey = (RSBKey) key;
1052      RBTreeLocationId locationId = new RBTreeLocationId(rsbKey.values, rowReader.getKey(rsbKey.values));
1053      recordList.flushData(locationId, direction);
1054      fetchedAll = false;
1055      removeKeyFromUnFetchedStatusSetApp(locationId, direction);
1056   }
1057
1058   public void showData() throws DException {
1059      Object JavaDoc key = recordList.getTopKey();
1060      if (key != null) {
1061         do {
1062            RBTreeLocationId rsbKey = (RBTreeLocationId) recordList.getObjectAtKey(key);
1063         } while ( (key = recordList.getTreeNext(key)) != null);
1064      } else {
1065         ;//// Removed By Program ** System.out.println("......... No Data in the Record Set Buffer .......");
1066
}
1067   }
1068
1069
1070
1071   private void removeKeyFromUnFetchedStatusSetApp(Object JavaDoc locationId, boolean greater) throws DException {
1072      Object JavaDoc[] keys = unFetchedStatus.getKeys();
1073      RBTreeLocationId key = ( (RBTreeLocationId) locationId);
1074      if (keys == null) {
1075         if (unFetchedStatus.isFetched(key, greater))
1076            unFetchedStatus.setFetched(key, greater);
1077         return;
1078      }
1079      if (greater)
1080         for (int i = 0; i < keys.length; i++) {
1081            int comp = key.compareTo(keys[i]);
1082            if (comp < 0) {
1083               unFetchedStatus.remove(keys[i]);
1084            }
1085         }
1086      else
1087         for (int i = 0; i < keys.length; i++) {
1088            int comp = key.compareTo(keys[i]);
1089            if (comp > 0) {
1090               unFetchedStatus.remove(keys[i]);
1091            }
1092
1093         }
1094      if (unFetchedStatus.isFetched(key, greater))
1095         unFetchedStatus.setFetched(key, greater);
1096      fetchedAll = false;
1097   }
1098
1099   private boolean browserType;
1100
1101   public void setListenerMode(boolean browserType0) throws DException {
1102      browserType = browserType0;
1103   }
1104
1105   public void setAutoFlush(boolean flushData0) throws DException {
1106      flushData = flushData0;
1107   }
1108
1109   public void setBufferSize(int bufferSize0) throws DException {
1110      BUFFERSIZE = bufferSize0;
1111   }
1112}
1113
Popular Tags