Statistics
| Revision:

root / trunk / extensions / extArcims / src / es / prodevelop / cit / gvsig / arcims / fmap / drivers / ArcImsInMemoryAttsTableDriver.java @ 8110

History | View | Annotate | Download (16.2 KB)

1
package es.prodevelop.cit.gvsig.arcims.fmap.drivers;
2

    
3

    
4
import java.awt.Dimension;
5
import java.io.IOException;
6
import java.sql.Connection;
7
import java.sql.DriverManager;
8
import java.sql.SQLException;
9
import java.sql.Types;
10
import java.util.ArrayList;
11
import java.util.HashMap;
12

    
13
import org.apache.log4j.Logger;
14
import org.gvsig.remoteClient.arcims.utils.FieldInformation;
15

    
16
import com.hardcode.driverManager.DriverLoadException;
17
import com.hardcode.gdbms.engine.data.DataSource;
18
import com.hardcode.gdbms.engine.data.DataSourceFactory;
19
import com.hardcode.gdbms.engine.data.driver.DriverException;
20
import com.hardcode.gdbms.engine.data.driver.ObjectDriver;
21
import com.hardcode.gdbms.engine.instruction.EvaluationException;
22
import com.hardcode.gdbms.engine.instruction.SemanticException;
23
import com.hardcode.gdbms.engine.values.*;
24
import com.hardcode.gdbms.parser.ParseException;
25
import com.iver.cit.gvsig.fmap.layers.FBitSet;
26

    
27
public class ArcImsInMemoryAttsTableDriver {
28
        
29
        
30
        private String tableName = "";
31
        // private String dataBName = "";
32
        private String idOriginalFieldName = "";
33
        private String idSqlFieldName = "";
34
        
35
        // private String rowIndexFieldName = "INMEMORYROWNUMBER";
36
        private int idFieldInd = -1;
37
        private FBitSet requested;
38
        
39
        private ArrayList sqlColumnNames = new ArrayList();
40
        private ArrayList originalColumnNames = new ArrayList();
41
        
42
        // private ArrayList originalColumnNames = new ArrayList();
43
        private ArrayList columnTypes = new ArrayList();
44
        // private int theRowCount = 0;
45
        private int theFieldCount = 0;
46
        private HashMap idToIndex;
47
        private static Logger logger = Logger.getLogger(FMapFeatureArcImsDriver.class.getName());
48
        
49
        private Dimension lastRequest = new Dimension(-1, -1);
50
        
51
        // ------------------------------------------------
52
        private ArrayList data = new ArrayList();
53
        private ArrayList id = new ArrayList();
54
        // ------------------------------------------------
55
        // private ArcImsAttributesTableCachee attsCache;
56
        // private static Logger logger = Logger.getLogger(FMapFeatureArcImsDriver.class.getName());
57
        
58
        public ArcImsInMemoryAttsTableDriver(String tb_name, ArrayList colnames, ArrayList coltypes) {
59
                // super();
60
                tableName = tb_name;
61
                // dataBName = dbName;
62
                idFieldInd = getIdColumnInd(coltypes);
63
                
64
                idOriginalFieldName = (String) colnames.get(idFieldInd);
65
                idSqlFieldName = replaceUnwantedCharacters((String) colnames.get(idFieldInd));
66
                
67
                requested = new FBitSet();
68
                for (int i=0; i<colnames.size(); i++) {
69
                        sqlColumnNames.add(replaceUnwantedCharacters((String) colnames.get(i) ));
70
                        originalColumnNames.add(colnames.get(i));
71
                        columnTypes.add(coltypes.get(i));
72
                        theFieldCount++;
73
                }
74
                
75
                idToIndex = new HashMap();
76
        }
77
    /**
78
     * user = "as", password = "", dbName = ?
79
     * 
80
     * @see com.hardcode.gdbms.engine.data.driver.DBDriver#getConnection(java.lang.String,
81
     *      int, java.lang.String, java.lang.String, java.lang.String)
82
     */
83
//    public Connection getConnection(String host, int port, String _dbName,
84
//            String _user, String _password) throws SQLException {
85
//                
86
////            if (driverException != null) {
87
////                throw new RuntimeException(driverException);
88
////            }
89
//            String connectionString = "jdbc:hsqldb:mem:" + dataBName;
90
//            Connection c = DriverManager.getConnection(connectionString, "sa", "");
91
//            return c;
92
//        }
93
        
94
//    public Connection getConnection() throws SQLException {
95
//            return getConnection("", 0, "", "", "");
96
//        }
97
        
98
    /**
99
     * @see com.hardcode.driverManager.Driver#getName()
100
     */
101
    public String getName() {
102
        return "ArcIMS in-memory attributes data driver";
103
    }
104
    
105
    public void open(String sql) throws SQLException {
106
//            open(getConnection(), sql);
107
    }
108
    
109
    public void execute(String sql) throws SQLException {
110
//            execute(getConnection(), sql);
111
    }
112
    
113
        public String getDbName() {
114
                return "No database";
115
        }
116
        
117
        public int getIdFieldInd() {
118
                return idFieldInd;
119
        }
120
        
121
        public String getIdFieldName() {
122
                return idSqlFieldName;
123
        }
124
        
125
        // public void addRow(DataSourceFactory dsf, Value[] values) throws DriverException {
126
        public void addRow(Value[] values, boolean filled) throws DriverException {
127
                
128
                if (values.length < theFieldCount) {
129
                        logger.error("Cannot add row with length < field count. ");
130
                        return;
131
                }
132

    
133
                if (values[idFieldInd].toString().compareTo("") != 0) {
134
                        // not null value
135
                        int theid = ((IntValue) values[idFieldInd]).intValue();
136
                        idToIndex.put(new Integer(theid), new Integer(data.size()));
137
                }
138

    
139
                requested.set(data.size(), filled);
140
                data.add(values);
141

    
142
//                String fieldNames = "";
143
//                for (int i=0; i < (values.length + 1); i++) {
144
//                        fieldNames = fieldNames + ((String) columnNames.get(i)) + ", "; 
145
//                }
146
//                fieldNames = fieldNames.substring(0, fieldNames.length() - 2);
147
//                // + ArcImsSqlUtils.rowIndexFieldName;
148
//                
149
//                String fieldValues = "";
150
//                for (int i=0; i<values.length; i++) {
151
//                        fieldValues = fieldValues + getValueInSqlFormat(values[i]) + ", "; 
152
//                }
153
//                fieldValues = fieldValues + getRowCount();
154
//                
155
//                String sqlStr = "insert into " + tableName + " (";
156
//                sqlStr = sqlStr + fieldNames + ") values (";
157
//                sqlStr = sqlStr + fieldValues + ")";
158
//                /*
159
//                * INSERT INTO Table1 (Column1, Column2, Column3?)
160
//                * VALUES (Value1, Value2, Value3?)
161
//                */
162
//                try {
163
//                        // dsf.executeSQL(sqlStr, DataSourceFactory.AUTOMATIC_OPENING);
164
//                        execute(sqlStr);
165
//                        theRowCount++;
166
//                } catch (Exception e) {
167
//                        DriverException de = new DriverException(e.getMessage());
168
//                        throw de;
169
//                }
170
        }
171
        
172
        // public void deleteRow(DataSourceFactory dsf, int i) throws DriverException {
173
        public void deleteRow(int i) throws DriverException {
174
                /*
175
                 DELETE FROM Table1 WHERE Some_Column = Some_Value
176
                 */
177
                logger.warn("deleteRow was invoqued, i = " + i);
178
                
179
                int theid = getRowId(i);
180
                idToIndex.remove(new Integer(theid));
181

    
182
                requested.set(i, false);
183
                data.set(i, null);
184
                
185
//                String sqlStr = "delete from " + tableName + " where ";
186
//                sqlStr = sqlStr + rowIndexFieldName + " = ";
187
//                sqlStr = sqlStr + i;
188
//                /*
189
//                * INSERT INTO Table1 (Column1, Column2, Column3?)
190
//                * VALUES (Value1, Value2, Value3?)
191
//                */
192
//                try {
193
//                        // dsf.executeSQL(sqlStr, DataSourceFactory.AUTOMATIC_OPENING);
194
//                        execute(sqlStr);
195
//                        theRowCount--;
196
//                } catch (Exception e) {
197
//                        DriverException de = new DriverException(e.getMessage());
198
//                        throw de;
199
//                }
200
        }
201
        
202
//        private String getValueInSqlFormat(Value v) {
203
//                String tmp = v.getStringValue(internalValueWriter);
204
////                if (v instanceof StringValue) {
205
////                        tmp = "'" + tmp + "'";
206
////                }
207
//                return tmp;
208
//        }
209
        
210
        private boolean isEmptyRow(int n) {
211
                return (data.get(n) == null);
212
        }
213
        
214
        public int getRowId(int row) throws DriverException {
215
                Integer rowid = (Integer) id.get(row);
216
                return rowid.intValue();
217
//                Value[] therow = (Value []) data.get(row);
218
//                return ((IntValue) therow[idFieldInd]).intValue();
219
                // return ((Integer) indexToId.get(new Integer(row))).intValue();
220
        }
221
        
222
        public int getRowIndex(int id) throws DriverException {
223
                // logger.debug("Searching for id: " + id);
224
                return ((Integer) idToIndex.get(new Integer(id))).intValue();
225
        }
226
        
227
//        public int getRowId(DataSourceFactory dsf, int row) throws DriverException {
228
//                /*
229
//                 SELECT * FROM Customers WHERE LastName = 'Smith'
230
//                 */
231
//                String sqlStr = "select " + idFieldName + " from " + tableName + " where ";
232
//                sqlStr = sqlStr + rowIndexFieldName + " = ";
233
//                sqlStr = sqlStr + row + ";";
234
//                /*
235
//                * INSERT INTO Table1 (Column1, Column2, Column3?)
236
//                * VALUES (Value1, Value2, Value3?)
237
//                */
238
//                DataSource ds = null;
239
//                try {
240
//                        
241
//                        ds = dsf.executeSQL(sqlStr, DataSourceFactory.AUTOMATIC_OPENING);
242
//                        // int respind = ds.getFieldIndexByName(idFieldName);
243
//                        IntValue resp = (IntValue) ds.getFieldValue(0, 0);
244
//                        return resp.intValue();
245
//                } catch (Exception e) {
246
//                        DriverException de = new DriverException(e.getMessage());
247
//                        throw de;
248
//                }
249
//        }
250
//        
251
//        public int getRowIndex(DataSourceFactory dsf, int id) throws DriverException {
252
//                String sqlStr = "select " + rowIndexFieldName + " from " + tableName + " where ";
253
//                sqlStr = sqlStr + idFieldName + " = ";
254
//                sqlStr = sqlStr + id + ";";
255
//                /*
256
//                * INSERT INTO Table1 (Column1, Column2, Column3?)
257
//                * VALUES (Value1, Value2, Value3?)
258
//                */
259
//                DataSource ds = null;
260
//                try {
261
//                        ds = dsf.executeSQL(sqlStr, DataSourceFactory.AUTOMATIC_OPENING);
262
//
263
//                        System.err.println("getRowIndex of id = " + id);
264
//                        System.err.println(ds.getAsString());
265
//                        System.err.println("------------------------------");
266
//                        // int respind = ds.getFieldIndexByName(idFieldName);
267
//                        IntValue resp = (IntValue) ds.getFieldValue(0, 0);
268
//                        return resp.intValue();
269
//                } catch (Exception e) {
270
//                        DriverException de = new DriverException(e.getMessage());
271
//                        throw de;
272
//                }
273
//        }
274
        
275
        public boolean isNonRequestedRow(int rowind) {
276
                // TODO Auto-generated method stub
277
                return (! requested.get(rowind));
278
        }
279
        
280
        // public void updateRow(DataSourceFactory dsf, Value[] new_row, String[] fld_q) throws DriverException {
281
        // TODO so far, this method is called with
282
        // a full field query (except rowindex)
283
        public void updateRow(Value[] upd_row, String[] fld_q, int rowind) throws DriverException {
284

    
285
                if (! isEmptyRow(rowind)) {
286
                        int newid = 0;
287
                        int oldid = getRowId(rowind);
288
                        boolean done = false;
289

    
290
                        for (int i = 0; i < fld_q.length; i++) {
291
                                if (fld_q[i].compareTo(idSqlFieldName) == 0) {
292
                                        newid = ((IntValue) upd_row[i]).intValue();
293
                                        done = true;
294
                                }
295
                        }
296
                        if (done) {
297
                                idToIndex.remove(new Integer(oldid));
298
                                idToIndex.put(new Integer(newid), new Integer(rowind));
299
                        }
300
                }
301

    
302
                Value[] newrow = new Value[theFieldCount];
303
                
304
                if (data.get(rowind) == null) {
305
                        data.set(rowind, newrow);
306
                } else {
307
                        newrow = (Value []) data.get(rowind);
308
                }
309
                
310
                if (fld_q[0].compareTo("#ALL#") == 0) {
311
                        for (int i=0; i<upd_row.length; i++) {
312
                                newrow[i] = upd_row[i];
313
                        }
314
                } else {
315
                        int fldind = 0;
316
                        for (int i=0; i<fld_q.length; i++) {
317
                                String sqlname = replaceUnwantedCharacters(fld_q[i]);
318
                                fldind = getFieldIndexByName(sqlname);
319
                                newrow[fldind] = upd_row[i];
320
                        }
321
                }
322
                
323
//                data.set()
324
//                String[] fld_query = null;
325
//                if (fld_q[0].compareTo("#ALL#") == 0) {
326
//                        
327
//                        int count = getFieldCount() - 1;
328
//                        fld_query = new String[count];
329
//                        for (int i=0; i<count; i++) {
330
//                                fld_query[i] = getFieldName(i);
331
//                        }
332
//                        
333
//                        
334
//                } else {
335
//                        fld_query = new String[fld_q.length];
336
//                        for (int i=0; i<fld_q.length; i++) {
337
//                                fld_query[i] = ArcImsSqlUtils.getSqlCompliantFieldName(fld_q[i]);
338
//                        }
339
//                }
340
//                
341
//                IntValue id = null;
342
//                for (int i=0; i<fld_query.length; i++) {
343
//                        if (fld_query[i].compareTo(idFieldName) == 0) {
344
//                                id = (IntValue) new_row[i];
345
//                        }
346
//                }
347
//                if (id == null) {
348
//                        DriverException de = new DriverException("id_not_found");
349
//                        throw de;
350
//                }
351
//                int intid = id.intValue();
352
//                
353
//                String sqlStr = "update " + tableName + " set ";
354
//                String nthFieldName, nthFieldValue;
355
//                for (int i=0; i<fld_query.length; i++) {
356
//                        nthFieldName = fld_query[i];
357
//                        nthFieldValue = this.getValueInSqlFormat(new_row[i]);
358
//                        sqlStr = sqlStr + nthFieldName + " = ";
359
//                        sqlStr = sqlStr + nthFieldValue + ", ";
360
//                }
361
//                sqlStr = sqlStr.substring(0, sqlStr.length() - 2);
362
//                sqlStr = sqlStr + " where " + idFieldName + " = " + intid + ";";
363
//                try {
364
//                        // dsf.executeSQL(sqlStr, DataSourceFactory.AUTOMATIC_OPENING);
365
//                        execute(sqlStr);
366
//                } catch (Exception e) {
367
//                        DriverException de = new DriverException(e.getMessage());
368
//                        throw de;
369
//                }
370
        }
371
        
372
        public int getFieldIndexByName(String arg0) throws DriverException {
373
//                String arg00 = ArcImsSqlUtils.getSqlCompliantFieldName(arg0);
374
                if (arg0 == null) {
375
                        logger.error("Somebody asked for the index of a null field ");
376
                        return -1;
377
                }
378
                for (int i=0; i<sqlColumnNames.size(); i++) {
379
                        if (((String) sqlColumnNames.get(i)).compareTo(arg0) == 0) {
380
                                return i;
381
                        }
382
                }
383
                logger.error("Field not found ");
384
                return -1;
385
        }
386
        
387
        public Value[] getRow(DataSourceFactory dsf, int n) throws DriverException {
388
                return (Value []) data.get(n);
389
//                String sqlStr = "select * from " + tableName + " where ";
390
//                sqlStr = sqlStr + rowIndexFieldName + " = " + n + ";";
391
//
392
//                try {
393
//                        DataSource ds =
394
//                                dsf.executeSQL(sqlStr, DataSourceFactory.AUTOMATIC_OPENING);
395
//                        // int respind = ds.getFieldIndexByName(idFieldName);
396
//                        int count = ds.getFieldCount();
397
//                        Value[] resp = new Value[count];
398
//                        for (int i=0; i<count; i++) {
399
//                                resp[i] = ds.getFieldValue(0, i);
400
//                        }
401
//                        return resp;
402
//                } catch (Exception e) {
403
//                        DriverException de = new DriverException(e.getMessage());
404
//                        throw de;
405
//                }
406
        }
407
        
408
//        public String getRowIndexFieldName() {
409
//                return rowIndexFieldName;
410
//        }
411
        
412
        public void setRequested(int n, boolean req) {
413
                requested.set(n, req);
414
        }
415
        
416
        public void addTheseAsRequested(FBitSet fbs) {
417
                requested.or(fbs);
418
        }
419
        
420
        public long getRowCount() {
421
                return (long) data.size();
422
        }
423
        
424
        public int getFieldCount() {
425
                return theFieldCount;
426
        }
427
        
428
        public String getFieldName(int i) {
429
                return (String) sqlColumnNames.get(i);
430
        }
431
        
432
        public int getFieldType(int i) {
433
                return ((Integer) columnTypes.get(i)).intValue();
434
        }
435
        
436
//        public void addInIndexToIdHashMap(int rwcount, int i) {
437
//                indexToId.put(new Integer(rwcount), new Integer (i));
438
//        }
439
        
440
        public void addInIdToIndexHashMap(int i, int rwcount) {
441
                idToIndex.put(new Integer (i), new Integer(rwcount));
442
        }
443
        
444
//        public String getColumnName(int i) {
445
//                return (String) columnNames.get(i);
446
//        }
447

    
448
//        public void increaseRowCount(boolean req) {
449
//                requested.set(data.size(), req);
450
//                theRowCount++;
451
//        }
452
        
453
        public void addAsRequested(FBitSet fbs) {
454
                requested.or(fbs);
455
        }
456

    
457
        public FBitSet getThisAndNonRequestedUpTo(int _thisone, int total) {
458
                
459
                int thisone = _thisone;
460
                int rowcount = (int) getRowCount();
461
                
462
                if (_thisone >= rowcount) {
463
                        thisone = _thisone % rowcount;
464
                }
465
                
466
                FBitSet fbs = new FBitSet();
467
                fbs.set(thisone);
468
                if (total < 2) return fbs;
469
                
470
                int othersMustBeSet = total - 1;
471
                int checkind;
472
                
473
                for (int j=1; j<rowcount; j++) {
474
                        // checkind = (i + j) % noOfRows;
475
                        checkind = (thisone + j) % rowcount;
476
                        if (isNonRequestedRow(checkind)) {
477
                                fbs.set(checkind);
478
                                othersMustBeSet--;
479
                        }
480
                        if (othersMustBeSet == 0) break;
481
                }
482
                return fbs;
483
        }
484
        
485
        public void addEmptyRowWithId(Value idval, String idcolname) {
486
                data.add(null);
487
                id.add(new Integer( ((IntValue) idval).intValue() ));
488
        }
489
        
490
        public Value getFieldValue(long row, int colind) {
491
                
492
                // printLastAndUpdate(row, colind);
493
                
494
                if (row >= getRowCount() || (row < 0)) {
495
                        logger.error("Row index out of limits ");
496
                        return null;
497
                }
498

    
499
                Value[] therow = (Value []) data.get((int) row);
500

    
501
                if (therow == null) {
502
                        logger.error("Tried to get non available value (?) ");
503
                        return null;
504
                }
505
                if ((colind >= therow.length) || (colind < 0)) {
506
                        logger.error("Field index out of limits ");
507
                        return null;
508
                }
509
                if (therow[colind] == null) {
510
                        logger.warn("In order to avoid returning element [ " + row +  ", " + colind + " ] (which is null), returned ValueFactory.createNullValue()");
511
                        return ValueFactory.createNullValue();
512
                } else {
513
                        return therow[colind];
514
                }
515
        }
516
        
517
        private void printLastAndUpdate(long row, int colind) {
518
                logger.debug("Last request: [ " + lastRequest.height + " , " + lastRequest.width + " ]");
519
                lastRequest.height = (int) row;
520
                lastRequest.width = colind;
521
                logger.debug("Current request: [ " + lastRequest.height + " , " + lastRequest.width + " ]");
522
        }
523
        //        public Value getCachedValue(int row, int attind) {
524
//                return attsCache.getAttribute(row, attind);
525
//        }
526
//        
527
//        public void setCachedValue(int row, int attind, Value v) {
528
//                attsCache.addToCache(row, attind, v);
529
//        }
530
        public int getIdColumnInd(ArrayList col_Types) {
531
                
532
                int coltype, idindex = -1;
533
                for (int i=0; i<col_Types.size(); i++) {
534
                        coltype = ((Integer) col_Types.get(i)).intValue();
535
                        if (coltype == FieldInformation.ID) {
536
                                idindex = i;
537
                                break;
538
                        }
539
                }
540
                if (idindex == -1) {
541
                        logger.error("ID not found ");
542
                }
543
                return idindex;
544
        }
545
        
546
        public String getTableName() {
547
                return tableName;
548
        }
549
        
550
        public static String replaceUnwantedCharacters(String str) {
551
                String resp = str;
552
                resp = resp.replace('.', '_');
553
                resp = resp.replace('#', 'z');
554
                
555
                return resp;
556
        }
557

    
558
        public String getOriginalFieldName(int idcolindex) {
559
                return (String) originalColumnNames.get(idcolindex);
560
        }
561
        
562
        public String getSqlFieldName(int idcolindex) {
563
                return (String) sqlColumnNames.get(idcolindex);
564
        }
565
        
566

    
567
}