Statistics
| Revision:

root / trunk / extensions / extSDE / src / com / iver / cit / gvsig / fmap / drivers / sde / ArcSdeDriver.java @ 13792

History | View | Annotate | Download (33.7 KB)

1
/*
2
 * Created on 13-may-2005
3
 *
4
 * gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
5
 *
6
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
7
 *
8
 * This program is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU General Public License
10
 * as published by the Free Software Foundation; either version 2
11
 * of the License, or (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21
 *
22
 * For more information, contact:
23
 *
24
 *  Generalitat Valenciana
25
 *   Conselleria d'Infraestructures i Transport
26
 *   Av. Blasco Ib??ez, 50
27
 *   46010 VALENCIA
28
 *   SPAIN
29
 *
30
 *      +34 963862235
31
 *   gvsig@gva.es
32
 *      www.gvsig.gva.es
33
 *
34
 *    or
35
 *
36
 *   IVER T.I. S.A
37
 *   Salamanca 50
38
 *   46005 Valencia
39
 *   Spain
40
 *
41
 *   +34 963163400
42
 *   dac@iver.es
43
 */
44
package com.iver.cit.gvsig.fmap.drivers.sde;
45

    
46
import java.awt.geom.Rectangle2D;
47
import java.sql.Types;
48
import java.util.Hashtable;
49
import java.util.TreeMap;
50
import java.util.Vector;
51

    
52
import com.esri.sde.sdk.client.SeColumnDefinition;
53
import com.esri.sde.sdk.client.SeConnection;
54
import com.esri.sde.sdk.client.SeException;
55
import com.esri.sde.sdk.client.SeExtent;
56
import com.esri.sde.sdk.client.SeFilter;
57
import com.esri.sde.sdk.client.SeLayer;
58
import com.esri.sde.sdk.client.SeObjectId;
59
import com.esri.sde.sdk.client.SeQuery;
60
import com.esri.sde.sdk.client.SeQueryInfo;
61
import com.esri.sde.sdk.client.SeRegisteredColumn;
62
import com.esri.sde.sdk.client.SeRow;
63
import com.esri.sde.sdk.client.SeShape;
64
import com.esri.sde.sdk.client.SeShapeFilter;
65
import com.esri.sde.sdk.client.SeSqlConstruct;
66
import com.esri.sde.sdk.client.SeTable;
67
import com.hardcode.gdbms.driver.exceptions.InitializeWriterException;
68
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
69
import com.hardcode.gdbms.driver.exceptions.ReloadDriverException;
70
import com.hardcode.gdbms.engine.data.DataSourceFactory;
71
import com.hardcode.gdbms.engine.data.driver.ObjectDriver;
72
import com.hardcode.gdbms.engine.data.edition.DataWare;
73
import com.hardcode.gdbms.engine.values.Value;
74
import com.hardcode.gdbms.engine.values.ValueFactory;
75
import com.iver.andami.messages.Messages;
76
import com.iver.andami.messages.NotificationManager;
77
import com.iver.cit.gvsig.fmap.core.FShape;
78
import com.iver.cit.gvsig.fmap.core.ICanReproject;
79
import com.iver.cit.gvsig.fmap.core.IFeature;
80
import com.iver.cit.gvsig.fmap.core.IGeometry;
81
import com.iver.cit.gvsig.fmap.drivers.DBException;
82
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
83
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
84
import com.iver.cit.gvsig.fmap.drivers.FieldDescription;
85
import com.iver.cit.gvsig.fmap.drivers.IConnection;
86
import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator;
87
import com.iver.cit.gvsig.fmap.drivers.db.utils.ConnectionWithParams;
88
import com.iver.cit.gvsig.fmap.drivers.db.utils.SingleVectorialDBConnectionManager;
89
import com.iver.cit.gvsig.fmap.edition.IWriteable;
90
import com.iver.cit.gvsig.fmap.edition.IWriter;
91
import com.iver.cit.gvsig.fmap.layers.XMLException;
92
import com.iver.utiles.XMLEntity;
93
import com.iver.utiles.swing.JPasswordDlg;
94

    
95

    
96
/**
97
 * Driver of ArcSDE.
98
 * @author Vicente Caballero Navarro
99
 */
100
public class ArcSdeDriver implements ICanReproject, IWriteable, IVectorialSDEDriver, ObjectDriver{
101
    protected static Hashtable poolPassw = new Hashtable();
102
    private SeLayer layer;
103
    private SeQuery query=null;
104
    private SeQuery queryAux=null;
105
    private SeSqlConstruct sqlConstruct;
106
    private SeColumnDefinition[] colDefs;
107
    private SeRow row = null;
108
    private int numReg = -1;
109
    private Rectangle2D fullExtent = null;
110
    private Hashtable hashRelate = null;
111
    private int idSpatialColumn = -1;
112
    private String[] fields;
113
    private int[] fieldTypes;
114
    private long lastRowServed = -1;
115
//    private SeConnection alphanumericConnection = null;
116
    private IConnection spatialConnection=null;
117
    private String strEPSG = "-1";
118
    private String originalEPSG = "-1";
119
    private String sqlTotal;
120
    private long posActual = -1;
121
    private SeRow cachedRow = null;
122
    protected DBLayerDefinition lyrDef = null;
123
    protected Rectangle2D workingArea;
124
    protected String driverClass;
125
    protected String className;
126
    protected String catalogName;
127
        private ArcSdeWriter writer;
128
        private String userName;
129
        private String tableName;
130
        private String FIDfield;
131
        private String geometryField;
132
        private String whereClause;
133
        private String strSRID;
134
        private String host;
135
        private String port;
136
        private String dbName;
137
        private String connName;
138
//        private String dbUrl;
139
        private SeConnection alphanumericConnection;
140

    
141
    /**
142
     * Recorre el recordset creando una tabla Hash que usaremos para relacionar
143
     * el n?mero de un registro con su identificador ?nico. Debe ser llamado
144
     * en el setData justo despu?s de crear el recorset principal
145
     */
146
    protected void doRelateID_FID() {
147
        hashRelate = new Hashtable();
148

    
149
                if (row == null) {
150
                System.out.println(" No rows fetched");
151

    
152
                return;
153
            }
154

    
155
            int index = 0;
156
            int fid=getLyrDef().getIdFieldID();
157
            Value value=getFieldValue(index,fid);
158

    
159
            while (value != null) {
160
                //SeShape shpVal = row.getShape(idSpatialColumn);
161
                //SeObjectId objID = shpVal.getFeatureId();
162
                    String theKey = value.toString();
163
                hashRelate.put(theKey, new Integer(index));
164
                index++;
165
                value = getFieldValue(index,fid);
166

    
167

    
168
            }
169

    
170
            numReg = index;
171
    }
172
    /**
173
         * @return
174
         */
175
    public Rectangle2D getFullExtent() {
176
                return fullExtent;
177
        }
178
    public IGeometry getShape(int index) {
179
        SeRow row;
180

    
181
        try {
182
            row = obtainRow(index);
183
            if (row==null)
184
                    return null;
185
            SeShape spVal = row.getShape(idSpatialColumn);
186
            IGeometry geom = ArcSdeFeatureIterator.getGeometry(spVal);
187
            return geom;
188
        } catch (SeException e) {
189
                NotificationManager.addError(e);
190
        }
191
        return null;
192
    }
193

    
194
    public IFeatureIterator getFeatureIterator(String sql){
195
        return null;
196
    }
197

    
198
    public IFeatureIterator getFeatureIterator(Rectangle2D r, String strEPSG) {
199
        /*
200
         *   Generate a rectangular shape that will be used as a filter
201
         */
202
        try {
203
            SeShape shape = new SeShape(layer.getCoordRef());
204
            SeExtent extent=layer.getExtent();
205
            shape.generateRectangle(extent);
206

    
207
            SeShape[] shapes = new SeShape[1];
208
            shapes[0] = shape;
209

    
210
            /*
211
             *   Retrieve all the shapes that are contained within the
212
             *   rectangles envelope.
213
             */
214
            SeShapeFilter[] filters = new SeShapeFilter[1];
215
            SeShapeFilter filter = null;
216

    
217
            filter = new SeShapeFilter(layer.getName(),
218
                    layer.getSpatialColumn(), shape, SeFilter.METHOD_ENVP);
219
            filters[0] = filter;
220

    
221
            SeQuery spatialQuery = null;
222
            SeSqlConstruct sqlCons = new SeSqlConstruct(layer.getName());
223

    
224
            spatialQuery = new SeQuery(alphanumericConnection, fields, sqlCons);
225

    
226
            /*
227
             *   Set spatial constraints
228
             */
229
            spatialQuery.setSpatialConstraints(SeQuery.SE_OPTIMIZE, false,
230
                filters);
231

    
232
            spatialQuery.prepareQuery();
233

    
234
            spatialQuery.execute();
235

    
236
            return new ArcSdeFeatureIterator(spatialQuery);
237
        } catch (SeException e) {
238
                NotificationManager.addError(e);
239
            return null;
240
        }
241
    }
242

    
243
    public void close() {
244
    }
245

    
246
    public void open() {
247
    }
248

    
249
    public int getRowIndexByFID(IFeature FID) {
250
        int resul;
251
        String strID = FID.getID();
252
        Integer rowIndex = (Integer) hashRelate.get(strID);
253

    
254
        if (rowIndex == null) {
255
            System.err.println("Error: No se ha encontrado " + strID +
256
                " dentro del Hash");
257
        }
258
        resul = rowIndex.intValue();
259
        return resul;
260
    }
261

    
262
    public String getGeometryField(String fieldName) {
263
        return layer.getSpatialColumn();
264
    }
265

    
266
    public int getShapeCount() {
267
        return numReg;
268
    }
269

    
270
    public DriverAttributes getDriverAttributes() {
271
        return null;
272
    }
273

    
274
    public String getName() {
275
        return "gvSIG SDE driver";
276
    }
277

    
278
    /**
279
         * @return
280
         * @uml.property  name="fields"
281
         */
282
    public String[] getFields() {
283
                String[] attributes = new String[fields.length - 1];
284
                for (int i = 1; i < fields.length; i++)
285
                        attributes[i - 1] = fields[i];
286
                return attributes;
287
        }
288

    
289
    public String getTableName() {
290
        return layer.getName();
291
    }
292

    
293
    private synchronized SeRow obtainRow(long rowIndex) throws SeException {
294
       if (rowIndex != posActual) {
295
            if (rowIndex == 0) {
296
                if (query != null) {
297
                    if (query.inProgress()) {
298
                        query.close();
299
                    }
300
                    query = new SeQuery(((ConnectionSDE)spatialConnection).getConnection(), fields, sqlConstruct);
301
                    query.prepareQuery();
302
                    query.execute();
303
                }
304
                lastRowServed = -1;
305
            }
306

    
307
            if (lastRowServed == (rowIndex - 1)) {
308
                row = query.fetch();
309
                lastRowServed++;
310
            } else {
311
                if (queryAux != null && queryAux.inProgress()) {
312
                        queryAux.close();
313
                }
314

    
315
                queryAux = new SeQuery(((ConnectionSDE)spatialConnection).getConnection(), fields, sqlConstruct);
316
                SeObjectId rowID = new SeObjectId(rowIndex + 1);
317
                row = queryAux.fetchRow(layer.getName(), rowID, fields);
318
            }
319
            posActual = rowIndex;
320
            cachedRow = row;
321
        }
322

    
323
        return cachedRow;
324
    }
325

    
326
    public Value getFieldValue(long rowIndex, int fieldId) {
327
        SeRow row;
328
        Value val = null;
329

    
330
        try {
331
            int idFieldArcSDE = fieldId+1; // SIEMPRE CONTANDO CON
332
            // QUE NOS HAN PASADO EL PRIMER CAMPO EL DE SHAPE
333
            row = obtainRow(rowIndex);
334
            if (row==null)
335
                    return null;
336
            int dataType = colDefs[idFieldArcSDE].getType();
337

    
338
            switch (dataType) {
339
            case SeColumnDefinition.TYPE_INT16:
340
                val = ValueFactory.createValue(row.getShort(idFieldArcSDE)
341
                                                  .intValue());
342

    
343
                break;
344

    
345
            case SeColumnDefinition.TYPE_INT32:
346
            case SeColumnDefinition.TYPE_INT64:
347
                val = ValueFactory.createValue(row.getInteger(idFieldArcSDE)
348
                                                  .intValue());
349

    
350
                break;
351

    
352
            case SeColumnDefinition.TYPE_FLOAT32:
353
                val = ValueFactory.createValue(row.getFloat(idFieldArcSDE)
354
                                                  .floatValue());
355

    
356
                break;
357

    
358
            case SeColumnDefinition.TYPE_FLOAT64:
359
                val = ValueFactory.createValue(row.getDouble(idFieldArcSDE)
360
                                                  .doubleValue());
361

    
362
                break;
363

    
364
            case SeColumnDefinition.TYPE_DATE:
365
                val = ValueFactory.createValue(row.getTime(idFieldArcSDE)
366
                                                  .getTime());
367

    
368
                break;
369

    
370
            case SeColumnDefinition.TYPE_STRING:
371
            case SeColumnDefinition.TYPE_NSTRING:
372

    
373
                String strAux = row.getString(idFieldArcSDE);
374

    
375
                if (strAux == null) {
376
                    strAux = "";
377
                }
378

    
379
                val = ValueFactory.createValue(strAux);
380

    
381
                break;
382
            }
383

    
384
            return val;
385
        } catch (SeException e) {
386
                NotificationManager.addError(e);
387
        }
388

    
389
        return ValueFactory.createNullValue();
390
    }
391

    
392
    public int getFieldCount(){
393
        return fields.length - 1;
394
    }
395

    
396
    public String getFieldName(int fieldId) {
397
        return fields[fieldId + 1];
398
    }
399

    
400
    public long getRowCount() {
401
        return numReg;
402
    }
403

    
404
    public int getFieldType(int i) {
405
        return fieldTypes[i+1];
406
    }
407

    
408
    /**
409
     * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#getPrimaryKeys()
410
     */
411
    public int[] getPrimaryKeys() {
412
        throw new UnsupportedOperationException();
413
    }
414

    
415
    /**
416
     * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#write(com.hardcode.gdbms.engine.data.edition.DataWare)
417
     */
418
    public void write(DataWare arg0) {
419
    }
420

    
421
    public IFeatureIterator getFeatureIterator(Rectangle2D r, String strEPSG,
422
        String[] alphaNumericFieldsNeeded) {
423
        /*
424
        *   Generate a rectangular shape that will be used as a filter
425
        */
426
        try {
427
            SeShape shape = new SeShape(layer.getCoordRef());
428
            SeExtent extent=layer.getExtent();
429
            shape.generateRectangle(extent);
430

    
431
            SeShape[] shapes = new SeShape[1];
432
            shapes[0] = shape;
433

    
434
            /*
435
             *   Retrieve all the shapes that are contained within the
436
             *   rectangles envelope.
437
             */
438
            SeShapeFilter[] filters = new SeShapeFilter[1];
439
            SeShapeFilter filter = null;
440

    
441
            filter = new SeShapeFilter(layer.getName(),
442
                    layer.getSpatialColumn(), shape, SeFilter.METHOD_ENVP);
443
            filters[0] = filter;
444

    
445
            SeQuery spatialQuery = null;
446
            SeSqlConstruct sqlCons = new SeSqlConstruct(layer.getName());
447

    
448
            spatialQuery = new SeQuery(alphanumericConnection, fields, sqlCons);
449

    
450
            /*
451
             *   Set spatial constraints
452
             */
453
            spatialQuery.setSpatialConstraints(SeQuery.SE_OPTIMIZE, false,
454
                filters);
455

    
456
            spatialQuery.prepareQuery();
457

    
458
            spatialQuery.execute();
459

    
460
            return new ArcSdeFeatureIterator(spatialQuery);
461
        } catch (SeException e) {
462
                NotificationManager.addError(e);
463

    
464
            return null;
465
        }
466
    }
467

    
468
    public boolean isWritable() {
469
        return false;
470
    }
471
    public void setData(IConnection connection, DBLayerDefinition lyrDef) throws DBException {
472
             String[] fieldsAux=null;
473
         FieldDescription[] fds=lyrDef.getFieldsDesc();
474
             if ((fds != null) && (fds.length != 0)) {
475
             if (!fds[0].getFieldName().equals(lyrDef.getFieldGeometry())) {
476
                 fieldsAux = new String[fds.length + 1];
477
                 fieldsAux[0] = lyrDef.getFieldGeometry();
478

    
479
                 for (int k = 1; k < fds.length+1; k++) {
480
                     fieldsAux[k] = fds[k - 1].getFieldName();
481
                 }
482
             }
483
         }
484
        lyrDef.setFieldNames(fieldsAux);
485
        lyrDef.setIdFieldID(lyrDef.getIdField(lyrDef.getFieldID())-1);
486
        setLyrDef(lyrDef);
487
        // Conexi?n:
488
        String server = lyrDef.getHost();
489
        int instance = lyrDef.getPort();
490
        String database = lyrDef.getDataBase();
491
        String user = lyrDef.getUser();
492
        String password = lyrDef.getPassword();
493
        String[] cols = lyrDef.getFieldNames();
494
        String tableName = lyrDef.getComposedTableName();
495

    
496
        try {
497
            alphanumericConnection =new SeConnection(server, instance, database, user, password);
498
//            alphanumericConnection.startTransaction();
499
            spatialConnection = connection;
500
//            ((ConnectionSDE)spatialConnection).getConnection().startTransaction();
501
        } catch (SeException e) {
502
                NotificationManager.addError(e);
503
            return;
504
                }
505
        // Fetching data
506
        String layerName = tableName;
507
        SeObjectId layerID = null;
508
        String strSpatialColumn = "";
509

    
510
        try {
511
            Vector theLayers = ((ConnectionSDE)spatialConnection).getConnection().getLayers();
512

    
513
            for (int i = 0; i < theLayers.size(); i++) {
514
                SeLayer layer = (SeLayer) theLayers.elementAt(i);
515

    
516
                if (layer.getName().compareToIgnoreCase(layerName) == 0) {
517
                        layerID = layer.getID();
518
                    strSpatialColumn = layer.getSpatialColumn();
519
                    break;
520
                }
521

    
522

    
523
            }
524

    
525
            if (layerID == null) {
526
                System.err.println("Capa no encontrada");
527

    
528
                return;
529
            }
530

    
531
            // layerName = layer.getName();
532
            layer = new SeLayer(((ConnectionSDE)spatialConnection).getConnection(), layerName, strSpatialColumn);
533

    
534
            //TODO aqu? se puede saber la proyecci?n
535
            //layer.getCoordRef().getSrid();
536

    
537
//            if ((cols != null) && (cols.length != 0)) {
538
//                if (!cols[0].equals(lyrDef.getFieldGeometry())) {
539
//                    this.fields = new String[cols.length + 1];
540
//                    this.fields[0] = lyrDef.getFieldGeometry();
541
//
542
//                    for (int i = 1; i < fields.length; i++) {
543
//                        fields[i] = cols[i - 1];
544
//                    }
545
//                } else {
546
//                    fields = cols;
547
//                }
548
//            } else {
549
//                SeSqlConstruct sqlConstruct = new SeSqlConstruct(tableName);
550
//                sqlTotal = sqlConstruct.getWhere();
551
//
552
//                SeTable table1 = new SeTable(conn, tableName);
553
//
554
//                /*
555
//                 *   Get the table's column definition.
556
//                 */
557
//                SeColumnDefinition[] tableDef = table1.describe();
558
//                this.fields = new String[tableDef.length];
559
//
560
//                /*
561
//                 *   Store the names of all the table's columns in the
562
//                 *   String array cols. This array specifies the columns
563
//                 *   to be retrieved from the database.
564
//                 */
565
//                int idField = 1;
566
//
567
//                for (int i = 0; i < tableDef.length; i++) {
568
//                    if (tableDef[i].getType() == SeColumnDefinition.TYPE_SHAPE) {
569
//                        this.fields[0] = tableDef[i].getName();
570
//                    } else {
571
//                        this.fields[idField] = tableDef[i].getName();
572
//                        idField++;
573
//                    }
574
//                }
575
//
576
//                lyrDef.setFieldNames(fields);
577
//            }
578
            fields=cols;
579
            sqlConstruct = new SeSqlConstruct(layerName);
580

    
581
            //      Create a query stream between the client and server
582
            query = new SeQuery(alphanumericConnection, fields, sqlConstruct);
583
            query.prepareQuery();
584
            query.execute();
585
            row = query.fetch();
586
            if (row == null) {
587
                System.out.println("La tabla " + getName() +
588
                    " no tiene registros");
589

    
590
                return;
591
            }
592

    
593
            colDefs = row.getColumns();
594
            lyrDef.setShapeType(obtainShapeType(row.getColumnDef(0).getType()));
595
            fieldTypes = new int[colDefs.length];
596

    
597
            for (int colNum = 0; colNum < colDefs.length; colNum++) {
598
                SeColumnDefinition colDef = colDefs[colNum];
599
                int dataType = colDef.getType();
600

    
601
                switch (dataType) {
602
                case SeColumnDefinition.TYPE_SHAPE:
603

    
604
                    if (colNum != 0) {
605
                        System.err.println(
606
                            "Por favor, el campo de shapes deber ser el primero");
607

    
608
                        return;
609
                    }
610

    
611
                    idSpatialColumn = colNum;
612

    
613
                    break;
614

    
615
                case SeColumnDefinition.TYPE_INT16:
616
                case SeColumnDefinition.TYPE_INT32:
617
                case SeColumnDefinition.TYPE_INT64:
618
                    fieldTypes[colNum] = Types.INTEGER;
619

    
620
                    break;
621

    
622
                case SeColumnDefinition.TYPE_FLOAT32:
623
                    fieldTypes[colNum] = Types.FLOAT;
624

    
625
                    break;
626

    
627
                case SeColumnDefinition.TYPE_FLOAT64:
628
                    fieldTypes[colNum] = Types.DOUBLE;
629

    
630
                    break;
631

    
632
                case SeColumnDefinition.TYPE_DATE:
633
                    fieldTypes[colNum] = Types.DATE;
634

    
635
                    break;
636

    
637
                default:
638
                    fieldTypes[colNum] = Types.VARCHAR;
639

    
640
                    break;
641
                }
642
            }
643
            fields=cols;
644
            SeQuery extentQuery = new SeQuery(((ConnectionSDE)spatialConnection).getConnection(), fields, sqlConstruct);
645
            SeQueryInfo queryInfo = new SeQueryInfo();
646
            queryInfo.setConstruct(sqlConstruct);
647

    
648
            SeExtent seExtent = extentQuery.calculateLayerExtent(queryInfo);
649
            fullExtent = new Rectangle2D.Double(seExtent.getMinX(),
650
                    seExtent.getMinY(),
651
                    seExtent.getMaxX() - seExtent.getMinX(),
652
                    seExtent.getMaxY() - seExtent.getMinY());
653
            extentQuery.close();
654

    
655
            doRelateID_FID();
656
        } catch (SeException e) {
657
                throw new DBException(e);
658
        }
659
    }
660

    
661
    private int obtainShapeType(int type) {
662
        int shapeType = -1;
663

    
664
        switch (type) {
665
        case SeLayer.TYPE_POINT:
666
            shapeType = FShape.POINT;
667

    
668
            break;
669

    
670
        case SeLayer.TYPE_LINE:
671
        case SeLayer.TYPE_SIMPLE_LINE:
672
        case SeLayer.TYPE_MULTI_LINE:
673
        case SeLayer.TYPE_MULTI_SIMPLE_LINE:
674
            shapeType = FShape.LINE;
675

    
676
            break;
677

    
678
        case SeLayer.TYPE_POLYGON:
679
        case SeLayer.TYPE_MULTI_POLYGON:
680
            shapeType = FShape.POLYGON;
681

    
682
            break;
683

    
684
        default:
685
            shapeType = FShape.MULTI;
686
        }
687

    
688
        return shapeType;
689
    }
690

    
691
    public String getCompleteWhere() {
692
        return null;
693
    }
694

    
695
    public String getConnectionStringBeginning() {
696
        return "sde";
697
    }
698

    
699
    public int getDefaultPort() {
700
        return 5151;
701
    }
702

    
703
    public String getSourceProjection(IConnection conn,DBLayerDefinition dbld) {
704
        return originalEPSG;
705
    }
706

    
707
    public String getDestProjection() {
708
        return strEPSG;
709
    }
710

    
711
    public void setDestProjection(String toEPSG) {
712
        this.strEPSG = toEPSG;
713
    }
714

    
715
    public boolean canReproject(String toEPSGdestinyProjection) {
716
        //                 TODO POR AHORA, REPROYECTA SIEMPRE gvSIG.
717
        return false;
718
    }
719

    
720
    public IWriter getWriter() {
721
             if (writer == null) {
722
             writer = new ArcSdeWriter();
723
             writer.setDriver(this);
724
             writer.setSeLayer(layer);
725
             try {
726
                                writer.initialize(getLyrDef());
727
                        } catch (InitializeWriterException e) {
728
                                NotificationManager.addError(e);
729
                        }
730
         }
731

    
732
         return writer;
733
    }
734

    
735
    /**
736
         * @return
737
         * @uml.property  name="sqlTotal"
738
         */
739
    public String getSqlTotal() {
740
                return sqlTotal;
741
        }
742

    
743
    public XMLEntity getXMLEntity() {
744
        DBLayerDefinition lyrDef = getLyrDef();
745
        XMLEntity xml = new XMLEntity();
746
        xml.putProperty("className", this.getClass().getName());
747
        xml.putProperty("driverclass", this.getClass().getName());
748
        xml.putProperty("catalog", lyrDef.getCatalogName());
749

    
750
        // TODO: NO DEBEMOS GUARDAR EL NOMBRE DE USUARIO Y CONTRASE?A
751
        // AQUI. Hay que utilizar un pool de conexiones
752
        // y pedir al usuario que conecte a la base de datos
753
        // en la primera capa. En el resto, usar la conexi?n
754
        // creada con anterioridad.
755
        String userName = lyrDef.getUser();
756
        if (userName != null) {
757
            int aux = userName.indexOf("@");
758

    
759
            if (aux != -1) {
760
                userName = userName.substring(0, aux);
761
            }
762
        }
763

    
764
        xml.putProperty("username", userName);
765

    
766
        xml.putProperty("tablename", getTableName());
767
        xml.putProperty("fields", fields);
768
        xml.putProperty("ID", lyrDef.getFieldID());
769
        xml.putProperty("idfield",lyrDef.getIdFieldID());
770
        xml.putProperty("THE_GEOM", lyrDef.getFieldGeometry());
771
        xml.putProperty("whereclause", getWhereClause());
772
        xml.putProperty("SRID", lyrDef.getSRID_EPSG());
773

    
774
        xml.putProperty("host", lyrDef.getHost());
775
        xml.putProperty("port", lyrDef.getPort());
776
        xml.putProperty("dbName", lyrDef.getDataBase());
777
        xml.putProperty("connName", lyrDef.getConnectionName());
778

    
779
        xml.putProperty("typeShape",lyrDef.getShapeType());
780

    
781
        if (getWorkingArea() != null) {
782
            xml.putProperty("minXworkArea", getWorkingArea().getMinX());
783
            xml.putProperty("minYworkArea", getWorkingArea().getMinY());
784
            xml.putProperty("HworkArea", getWorkingArea().getHeight());
785
            xml.putProperty("WworkArea", getWorkingArea().getWidth());
786
        }
787

    
788
        return xml;
789
    }
790

    
791
    public void setXMLEntity(XMLEntity xml) throws XMLException {
792
        className = xml.getStringProperty("className");
793
        catalogName = xml.getStringProperty("catalog");
794
        lyrDef = new DBLayerDefinition();
795

    
796
        if (xml.contains("username")) {
797
            lyrDef.setUser(xml.getStringProperty("username"));
798
        }
799

    
800
        driverClass = xml.getStringProperty("driverclass");
801
        lyrDef.setTableName(xml.getStringProperty("tablename"));
802
        fields = xml.getStringArrayProperty("fields");
803
        lyrDef.setFieldNames(fields);
804
        lyrDef.setFieldID(xml.getStringProperty("ID"));
805
        if (xml.contains("idfield"))
806
                lyrDef.setIdFieldID(xml.getIntProperty("idfield"));
807
        lyrDef.setFieldGeometry(xml.getStringProperty("THE_GEOM"));
808
        lyrDef.setWhereClause(xml.getStringProperty("whereclause"));
809
        lyrDef.setSRID_EPSG(xml.getStringProperty("SRID"));
810

    
811
        if (xml.contains("host")) {
812
            lyrDef.setHost(xml.getStringProperty("host"));
813
            lyrDef.setPort(Integer.parseInt(xml.getStringProperty("port")));
814
            lyrDef.setDataBase(xml.getStringProperty("dbName"));
815
            lyrDef.setConnectionName(xml.getStringProperty("connName"));
816
        }
817
        lyrDef.setShapeType(xml.getIntProperty("typeShape"));
818
        if (xml.contains("minXworkArea")) {
819
            double x = xml.getDoubleProperty("minXworkArea");
820
            double y = xml.getDoubleProperty("minYworkArea");
821
            double H = xml.getDoubleProperty("HworkArea");
822
            double W = xml.getDoubleProperty("WworkArea");
823
            workingArea = new Rectangle2D.Double(x, y, W, H);
824
        }
825

    
826
        lyrDef.setCatalogName(catalogName);
827

    
828
        if (workingArea != null) {
829
            lyrDef.setWorkingArea(workingArea);
830
        }
831

    
832
        setLyrDef(lyrDef);
833
    }
834

    
835
    public int getFieldWidth(int fieldId) {
836
        return colDefs[fieldId+1].getSize();
837
    }
838

    
839
    public void setLyrDef(DBLayerDefinition lyrDef) {
840
        this.lyrDef =lyrDef;
841
    }
842

    
843
    /**
844
         * @see  com.iver.cit.gvsig.fmap.drivers.IVectorialJDBCDriver#setWorkingArea(java.awt.geom.Rectangle2D)
845
         * @uml.property  name="workingArea"
846
         */
847
    public void setWorkingArea(Rectangle2D rect) {
848
                this.workingArea = rect;
849
        }
850

    
851
    /**
852
         * @see  com.iver.cit.gvsig.fmap.drivers.IVectorialJDBCDriver#getWorkingArea()
853
         * @uml.property  name="workingArea"
854
         */
855
    public Rectangle2D getWorkingArea() {
856
                return workingArea;
857
        }
858

    
859
    /**
860
     * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getShapeType()
861
     */
862
    public int getShapeType() {
863
        return lyrDef.getShapeType();
864
    }
865

    
866
    /* (non-Javadoc)
867
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getWhereClause()
868
     */
869
    public String getWhereClause() {
870
        if (lyrDef.getWhereClause() == null) {
871
            return "";
872
        }
873

    
874
        return lyrDef.getWhereClause().toUpperCase();
875
    }
876

    
877
    /**
878
         * @return
879
         */
880
    public DBLayerDefinition getLyrDef() {
881
            // Esto hace saltar un error.
882
//            if (this.spatialConnection != null){
883
//                    lyrDef.setSeConnection();
884
//            }
885
        return lyrDef;
886
    }
887

    
888
    /**
889
     * Empty method called when the layer is going to be removed from the view.
890
     * Subclasses can overwrite it if needed.
891
     */
892
    public void remove() {
893
    }
894

    
895
    /* (non-Javadoc)
896
    * @see com.iver.cit.gvsig.fmap.drivers.VectorialDriver#reLoad()
897
    */
898
    public void reload() throws ReloadDriverException{
899
            try {
900
                        load();
901
                } catch (ReadDriverException e) {
902
                        throw new ReloadDriverException(this.className,e);
903
                }
904
        }
905

    
906
    public void setDataSourceFactory(DataSourceFactory dsf) {
907
        // TODO Auto-generated method stub
908
    }
909

    
910
    public void load() throws ReadDriverException{
911
            try {
912
            if (driverClass != null)
913
                    Class.forName(driverClass);
914

    
915
            String _drvName = getName();
916

    
917
            String keyPool = _drvName.toLowerCase() + "_" + lyrDef.getHost().toLowerCase()
918
            + "_" + lyrDef.getPort() + "_" + lyrDef.getDataBase().toLowerCase()
919
            + "_" + lyrDef.getUser().toLowerCase();
920

    
921
            IConnection newConn = null;
922
            String clave = null;
923
            ConnectionWithParams cwp = null;
924

    
925
            if (poolPassw.containsKey(keyPool)) {
926

    
927
                clave = (String) poolPassw.get(keyPool);
928
                cwp = SingleVectorialDBConnectionManager.instance().getConnection(
929
                                         _drvName, userName, clave, connName,
930
                                         host, port, dbName, true);
931

    
932
            } else {
933

    
934
                cwp = SingleVectorialDBConnectionManager.instance().getConnection(
935
                                             _drvName, userName, null, connName,
936
                                             host, port, dbName, false);
937

    
938
                if (cwp.isConnected()) {
939

    
940
                        poolPassw.put(keyPool, cwp.getPw());
941

    
942
                } else {
943

    
944
                    JPasswordDlg dlg = new JPasswordDlg();
945
                    String strMessage = Messages.getString("conectar_jdbc");
946
                    String strPassword = Messages.getString("password");
947
                    dlg.setMessage(strMessage
948
                                    + " ["
949
                                    + _drvName + ", "
950
                                    + host + ", "
951
                                    + port + ", "
952
                                    + dbName + ", "
953
                                    + userName + "]. "
954
                                    + strPassword
955
                                    + "?");
956
                    dlg.setVisible(true);
957
                    clave = dlg.getPassword();
958
                    if (clave == null)
959
                        return;
960
                    poolPassw.put(keyPool, clave);
961

    
962
                    cwp.connect(clave);
963
                }
964
            }
965

    
966
            newConn = cwp.getConnection();
967
//            newConn.setAutoCommit(false);
968

    
969
            DBLayerDefinition lyrDef = new DBLayerDefinition();
970
            if (getLyrDef() == null) {
971
                    lyrDef.setCatalogName(catalogName);
972
                    lyrDef.setTableName(tableName);
973
                    lyrDef.setFieldNames(fields);
974
                    lyrDef.setFieldID(FIDfield);
975
                    lyrDef.setFieldGeometry(geometryField);
976
                    lyrDef.setWhereClause(whereClause);
977
                    // lyrDef.setClassToInstantiate(driverClass);
978
                    if (workingArea != null)
979
                        lyrDef.setWorkingArea(workingArea);
980

    
981
                    lyrDef.setSRID_EPSG(strSRID);
982
            } else {
983
                    lyrDef = getLyrDef();
984
            }
985

    
986
            setData(newConn, lyrDef);
987
        } catch (ClassNotFoundException e) {
988
                throw new ReadDriverException(this.className,e);
989
        } catch (DBException e) {
990
                throw new ReadDriverException(this.className,e);
991

    
992
                }
993
    }
994

    
995
    public IConnection getConnection() {
996
        return spatialConnection;
997
    }
998
        public String getConnectionString(
999
                    String host,
1000
                    String port,
1001
                    String dbname,
1002
                    String user,
1003
                    String pw) {
1004

    
1005
                String resp = getConnectionStringBeginning()+ ":" + host.toLowerCase();
1006

    
1007
                if (dbname.trim().length() > 0) {
1008
                        resp += ":" + port;
1009
                } else {
1010
                        resp += ":" + getDefaultPort();
1011
                }
1012

    
1013
                resp += ":" + dbname.toLowerCase();
1014
                return resp;
1015
    }
1016
        public String[] getAllFields(IConnection conex, String tableName) throws DBException {
1017
                try {
1018
                        SeTable table = new SeTable(((ConnectionSDE)conex).getConnection(),tableName);
1019
                        SeRegisteredColumn[] columns=table.getColumnList();
1020
                        String[] fieldNames=new String[columns.length];
1021
                        for (int i=0; i < columns.length; i++){
1022
                                fieldNames[i]=columns[i].getName();
1023
                        }
1024
                        return fieldNames;
1025
                } catch (SeException e) {
1026
                        throw new DBException(e);
1027
                }
1028
        }
1029
        public String[] getAllFieldTypeNames(IConnection conex, String tableName) throws DBException {
1030
                try {
1031
                        SeTable table = new SeTable(((ConnectionSDE)conex).getConnection(),tableName);
1032
                        SeRegisteredColumn[] columns=table.getColumnList();
1033
                        String[] fieldNames=new String[columns.length];
1034
                        for (int i=0; i < columns.length; i++){
1035
                                fieldNames[i]=String.valueOf(columns[i].getType());
1036
                        }
1037
                        return fieldNames;
1038
                } catch (SeException e) {
1039
                        throw new DBException(e);
1040
                }
1041
        }
1042
        public String[] getIdFieldsCandidates(IConnection conn2, String tableName) throws DBException {
1043
                return getAllFields(conn2,tableName);
1044
        }
1045
        public String[] getGeometryFieldsCandidates(IConnection conn2, String tableName) {
1046
                return new String[]{"SHAPE"};//getAllFields(conn2,tableName);
1047
        }
1048
        public String[] getTableNames(IConnection conex, String dbName) throws DBException {
1049
                 try {
1050
                        Vector theLayers = ((ConnectionSDE)conex).getConnection().getLayers();
1051
                        TreeMap ret = new TreeMap();
1052
                        for (int i = 0; i < theLayers.size(); i++) {
1053
                                SeLayer layer = (SeLayer) theLayers.elementAt(i);
1054
                                ret.put(layer.getTableName(), layer.getTableName());
1055
                        }
1056
                        return (String[]) ret.keySet().toArray(new String[0]);
1057
                        } catch (SeException e) {
1058
                                throw new DBException(e);
1059
                        }
1060
                }
1061
         public String[] getTableFields(IConnection conex,String tableName) throws DBException{
1062
                        try {
1063
                                SeTable table = new SeTable(((ConnectionSDE)conex).getConnection(),tableName);
1064
                                SeRegisteredColumn[] columns=table.getColumnList();
1065
                                String[] fieldNames=new String[columns.length];
1066
                                for (int i=0; i < columns.length; i++){
1067
                                        fieldNames[i]=columns[i].getName();
1068
                                }
1069
                                return fieldNames;
1070
                        } catch (SeException e) {
1071
                                throw new DBException(e);
1072
                        }
1073
                }
1074

    
1075
}