Statistics
| Revision:

svn-gvsig-desktop / branches / v10 / extensions / extSDE / src / com / iver / cit / gvsig / fmap / drivers / sde / ArcSdeDriver.java @ 14244

History | View | Annotate | Download (36.6 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.Component;
47
import java.awt.geom.Rectangle2D;
48
import java.io.IOException;
49
import java.sql.Types;
50
import java.util.Hashtable;
51
import java.util.TreeMap;
52
import java.util.Vector;
53

    
54
import com.esri.sde.sdk.client.SeColumnDefinition;
55
import com.esri.sde.sdk.client.SeConnection;
56
import com.esri.sde.sdk.client.SeDefs;
57
import com.esri.sde.sdk.client.SeException;
58
import com.esri.sde.sdk.client.SeExtent;
59
import com.esri.sde.sdk.client.SeFilter;
60
import com.esri.sde.sdk.client.SeLayer;
61
import com.esri.sde.sdk.client.SeObjectId;
62
import com.esri.sde.sdk.client.SeQuery;
63
import com.esri.sde.sdk.client.SeQueryInfo;
64
import com.esri.sde.sdk.client.SeRegisteredColumn;
65
import com.esri.sde.sdk.client.SeRow;
66
import com.esri.sde.sdk.client.SeShape;
67
import com.esri.sde.sdk.client.SeShapeFilter;
68
import com.esri.sde.sdk.client.SeSqlConstruct;
69
import com.esri.sde.sdk.client.SeTable;
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.PluginServices;
76
import com.iver.andami.messages.Messages;
77
import com.iver.andami.messages.NotificationManager;
78
import com.iver.cit.gvsig.fmap.DriverException;
79
import com.iver.cit.gvsig.fmap.DriverJdbcNotFoundExceptionType;
80
import com.iver.cit.gvsig.fmap.core.FShape;
81
import com.iver.cit.gvsig.fmap.core.ICanReproject;
82
import com.iver.cit.gvsig.fmap.core.IFeature;
83
import com.iver.cit.gvsig.fmap.core.IGeometry;
84
import com.iver.cit.gvsig.fmap.drivers.DBException;
85
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
86
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
87
import com.iver.cit.gvsig.fmap.drivers.FieldDescription;
88
import com.iver.cit.gvsig.fmap.drivers.IConnection;
89
import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator;
90
import com.iver.cit.gvsig.fmap.drivers.db.utils.ConnectionWithParams;
91
import com.iver.cit.gvsig.fmap.drivers.db.utils.SingleVectorialDBConnectionManager;
92
import com.iver.cit.gvsig.fmap.edition.EditionException;
93
import com.iver.cit.gvsig.fmap.edition.IWriteable;
94
import com.iver.cit.gvsig.fmap.edition.IWriter;
95
import com.iver.cit.gvsig.fmap.layers.XMLException;
96
import com.iver.utiles.XMLEntity;
97
import com.iver.utiles.swing.JPasswordDlg;
98

    
99

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

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

    
153
        try {
154
            if (row == null) {
155
                System.out.println(" No rows fetched");
156

    
157
                return;
158
            }
159

    
160
            int index = 0;
161
            int fid=getLyrDef().getIdFieldID();
162
            Value value=getFieldValue(index,fid);
163

    
164
            while (value != null) {
165
                //SeShape shpVal = row.getShape(idSpatialColumn);
166
                //SeObjectId objID = shpVal.getFeatureId();
167
                    String theKey = value.toString();
168
                hashRelate.put(theKey, new Integer(index));
169
                index++;
170
                value = getFieldValue(index,fid);
171

    
172

    
173
            }
174

    
175
            numReg = index;
176
        } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
177
                NotificationManager.addError(e);
178
                }
179
    }
180
    /**
181
         * @return
182
         */
183
    public Rectangle2D getFullExtent() {
184
                return fullExtent;
185
        }
186
    public IGeometry getShape(int index) {
187
        SeRow row;
188

    
189
        try {
190
            row = obtainRow(index);
191
            if (row==null)
192
                    return null;
193
            SeShape spVal = row.getShape(idSpatialColumn);
194
            IGeometry geom = ArcSdeFeatureIterator.getGeometry(spVal);
195
            return geom;
196
        } catch (SeException e) {
197
                NotificationManager.addError(e);
198
        }
199
        return null;
200
    }
201

    
202
    public IFeatureIterator getFeatureIterator(String sql)
203
        throws DriverException {
204
        return null;
205
    }
206

    
207
    public IFeatureIterator getFeatureIterator(Rectangle2D r, String strEPSG)
208
        throws DriverException {
209
        /*
210
         *   Generate a rectangular shape that will be used as a filter
211
         */
212
        try {
213
            SeShape shape = new SeShape(layer.getCoordRef());
214
            SeExtent extent=layer.getExtent();
215
            shape.generateRectangle(extent);
216

    
217
            SeShape[] shapes = new SeShape[1];
218
            shapes[0] = shape;
219

    
220
            /*
221
             *   Retrieve all the shapes that are contained within the
222
             *   rectangles envelope.
223
             */
224
            SeShapeFilter[] filters = new SeShapeFilter[1];
225
            SeShapeFilter filter = null;
226

    
227
            filter = new SeShapeFilter(layer.getQualifiedName(),
228
                    layer.getSpatialColumn(), shape, SeFilter.METHOD_ENVP);
229
            filters[0] = filter;
230

    
231
            SeQuery spatialQuery = null;
232
            SeSqlConstruct sqlCons = new SeSqlConstruct(layer.getQualifiedName());
233

    
234
            spatialQuery = new SeQuery(alphanumericConnection, fields, sqlCons);
235

    
236
            /*
237
             *   Set spatial constraints
238
             */
239
            spatialQuery.setSpatialConstraints(SeQuery.SE_OPTIMIZE, false,
240
                filters);
241

    
242
            spatialQuery.prepareQuery();
243

    
244
            spatialQuery.execute();
245

    
246
            return new ArcSdeFeatureIterator(spatialQuery,getLyrDef().getFieldID());
247
        } catch (SeException e) {
248
                NotificationManager.addError(e);
249
            return null;
250
        }
251
    }
252

    
253
    public void close() {
254
    }
255

    
256
    public void open() throws DriverException {
257
    }
258

    
259
    public int getRowIndexByFID(IFeature FID) {
260
        int resul;
261
        String strID = FID.getID();
262
        Integer rowIndex = (Integer) hashRelate.get(strID);
263

    
264
        if (rowIndex == null) {
265
            System.err.println("Error: No se ha encontrado " + strID +
266
                " dentro del Hash");
267
        }
268
        resul = rowIndex.intValue();
269
        return resul;
270
    }
271

    
272
    public String getGeometryField(String fieldName) {
273
        return layer.getSpatialColumn();
274
    }
275

    
276
    public int getShapeCount() throws IOException {
277
        return numReg;
278
    }
279

    
280
    public DriverAttributes getDriverAttributes() {
281
        return null;
282
    }
283

    
284
    public String getName() {
285
        return "gvSIG SDE driver";
286
    }
287

    
288
    /**
289
         * @return
290
         * @uml.property  name="fields"
291
         */
292
    public String[] getFields() {
293
                String[] attributes = new String[fields.length - 1];
294
                for (int i = 1; i < fields.length; i++)
295
                        attributes[i - 1] = fields[i];
296
                return attributes;
297
        }
298

    
299
    public String getTableName() {
300
        try {
301
                        return layer.getQualifiedName();
302
                } catch (SeException e) {
303
                        e.printStackTrace();
304
                }
305
                return layer.getName();
306
    }
307

    
308
    private synchronized SeRow obtainRow(long rowIndex) throws SeException {
309
       if (rowIndex != posActual) {
310
            if (rowIndex == 0) {
311
                if (query != null) {
312
                    if (query.inProgress()) {
313
                        query.close();
314
                    }
315
                    query = new SeQuery(((ConnectionSDE)spatialConnection).getConnection(), fields, sqlConstruct);
316
                    query.prepareQuery();
317
                    query.execute();
318
                }
319
                lastRowServed = -1;
320
            }
321

    
322
            if (lastRowServed == (rowIndex - 1)) {
323
                row = query.fetch();
324
                lastRowServed++;
325
            } else {
326
                if (queryAux != null && queryAux.inProgress()) {
327
                        queryAux.close();
328
                }
329

    
330
                queryAux = new SeQuery(((ConnectionSDE)spatialConnection).getConnection(), fields, sqlConstruct);
331
                SeObjectId rowID = new SeObjectId(rowIndex + 1);
332
                row = queryAux.fetchRow(layer.getQualifiedName(), rowID, fields);
333
            }
334
            posActual = rowIndex;
335
            cachedRow = row;
336
        }
337

    
338
        return cachedRow;
339
    }
340

    
341
    public Value getFieldValue(long rowIndex, int fieldId)
342
        throws com.hardcode.gdbms.engine.data.driver.DriverException {
343
        SeRow row;
344
        Value val = null;
345

    
346
        try {
347
            int idFieldArcSDE = fieldId+1; // SIEMPRE CONTANDO CON
348
            // QUE NOS HAN PASADO EL PRIMER CAMPO EL DE SHAPE
349
            row = obtainRow(rowIndex);
350
            if (row==null)
351
                    return null;
352
            int dataType = colDefs[idFieldArcSDE].getType();
353

    
354
            switch (dataType) {
355
            case SeColumnDefinition.TYPE_INT16:
356
                val = ValueFactory.createValue(row.getShort(idFieldArcSDE)
357
                                                  .intValue());
358

    
359
                break;
360

    
361
            case SeColumnDefinition.TYPE_INT32:
362
            case SeColumnDefinition.TYPE_INT64:
363
                val = ValueFactory.createValue(row.getInteger(idFieldArcSDE)
364
                                                  .intValue());
365

    
366
                break;
367

    
368
            case SeColumnDefinition.TYPE_FLOAT32:
369
                val = ValueFactory.createValue(row.getFloat(idFieldArcSDE)
370
                                                  .floatValue());
371

    
372
                break;
373

    
374
            case SeColumnDefinition.TYPE_FLOAT64:
375
                val = ValueFactory.createValue(row.getDouble(idFieldArcSDE)
376
                                                  .doubleValue());
377

    
378
                break;
379

    
380
            case SeColumnDefinition.TYPE_DATE:
381
                val = ValueFactory.createValue(row.getTime(idFieldArcSDE)
382
                                                  .getTime());
383

    
384
                break;
385

    
386
            case SeColumnDefinition.TYPE_STRING:
387
                String strAux = row.getString(idFieldArcSDE);
388

    
389
                if (strAux == null) {
390
                    strAux = "";
391
                }
392

    
393
                val = ValueFactory.createValue(strAux);
394

    
395
                break;
396
            case SeColumnDefinition.TYPE_NSTRING:
397
                String nstrAux = row.getNString(idFieldArcSDE);
398
                if (nstrAux == null) {
399
                    nstrAux = "";
400
                }
401

    
402
                val = ValueFactory.createValue(nstrAux);
403

    
404
                break;
405
            }
406

    
407
            return val;
408
        } catch (SeException e) {
409
                NotificationManager.addError(e);
410
        }
411

    
412
        return ValueFactory.createNullValue();
413
    }
414

    
415
    public int getFieldCount()
416
        throws com.hardcode.gdbms.engine.data.driver.DriverException {
417
        return fields.length - 1;
418
    }
419

    
420
    public String getFieldName(int fieldId)
421
        throws com.hardcode.gdbms.engine.data.driver.DriverException {
422
        return fields[fieldId + 1];
423
    }
424

    
425
    public long getRowCount() {
426
        return numReg;
427
    }
428

    
429
    public int getFieldType(int i)
430
        throws com.hardcode.gdbms.engine.data.driver.DriverException {
431
        return fieldTypes[i+1];
432
    }
433

    
434
    /**
435
     * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#getPrimaryKeys()
436
     */
437
    public int[] getPrimaryKeys()
438
        throws com.hardcode.gdbms.engine.data.driver.DriverException {
439
        throw new UnsupportedOperationException();
440
    }
441

    
442
    /**
443
     * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#write(com.hardcode.gdbms.engine.data.edition.DataWare)
444
     */
445
    public void write(DataWare arg0)
446
        throws com.hardcode.gdbms.engine.data.driver.DriverException {
447
    }
448

    
449
    public IFeatureIterator getFeatureIterator(Rectangle2D r, String strEPSG,
450
        String[] alphaNumericFieldsNeeded) throws DriverException {
451
        /*
452
        *   Generate a rectangular shape that will be used as a filter
453
        */
454
        try {
455
            SeShape shape = new SeShape(layer.getCoordRef());
456
            SeExtent extent=layer.getExtent();
457
            shape.generateRectangle(extent);
458

    
459
            SeShape[] shapes = new SeShape[1];
460
            shapes[0] = shape;
461

    
462
            /*
463
             *   Retrieve all the shapes that are contained within the
464
             *   rectangles envelope.
465
             */
466
            SeShapeFilter[] filters = new SeShapeFilter[1];
467
            SeShapeFilter filter = null;
468

    
469
            filter = new SeShapeFilter(layer.getQualifiedName(),
470
                    layer.getSpatialColumn(), shape, SeFilter.METHOD_ENVP);
471
            filters[0] = filter;
472

    
473
            SeQuery spatialQuery = null;
474
            SeSqlConstruct sqlCons = new SeSqlConstruct(layer.getQualifiedName());
475

    
476
            spatialQuery = new SeQuery(alphanumericConnection, fields, sqlCons);
477

    
478
            /*
479
             *   Set spatial constraints
480
             */
481
            spatialQuery.setSpatialConstraints(SeQuery.SE_OPTIMIZE, false,
482
                filters);
483

    
484
            spatialQuery.prepareQuery();
485

    
486
            spatialQuery.execute();
487

    
488
            return new ArcSdeFeatureIterator(spatialQuery,getLyrDef().getFieldID());
489
        } catch (SeException e) {
490
                NotificationManager.addError(e);
491

    
492
            return null;
493
        }
494
    }
495

    
496
    public boolean isWritable() {
497
        return false;
498
    }
499
    public void setData(IConnection connection, DBLayerDefinition lyrDef) throws DBException {
500
             String[] fieldsAux=null;
501
         FieldDescription[] fds=lyrDef.getFieldsDesc();
502
             if ((fds != null) && (fds.length != 0)) {
503
             if (!fds[0].getFieldName().equals(lyrDef.getFieldGeometry())) {
504
                 fieldsAux = new String[fds.length + 1];
505
                 fieldsAux[0] = lyrDef.getFieldGeometry();
506

    
507
                 for (int k = 1; k < fds.length+1; k++) {
508
                     fieldsAux[k] = fds[k - 1].getFieldName();
509
                 }
510
             }else{
511
                     fieldsAux = new String[fds.length];
512
                     for (int k = 0; k < fds.length; k++) {
513
                     fieldsAux[k] = fds[k].getFieldName();
514
                 }
515
             }
516
         }
517
        lyrDef.setFieldNames(fieldsAux);
518
        lyrDef.setIdFieldID(lyrDef.getIdField(lyrDef.getFieldID())-1);
519
        setLyrDef(lyrDef);
520
        // Conexi?n:
521
        String server = lyrDef.getHost();
522
        int instance = lyrDef.getPort();
523
        String database = lyrDef.getDataBase();
524
        String user = lyrDef.getUser();
525
//        String password = lyrDef.getPassword();
526
        String[] cols = lyrDef.getFieldNames();
527
        String tableName = lyrDef.getComposedTableName();
528
        String password;
529
        if (lyrDef.getPassword()!=null){
530
                password=lyrDef.getPassword();
531
        }else{
532
                String keyPool = getName().toLowerCase() + "_" + lyrDef.getHost().toLowerCase()
533
                        + "_" + lyrDef.getPort() + "_" + lyrDef.getDataBase().toLowerCase()
534
                        + "_" + lyrDef.getUser().toLowerCase();
535
                password=(String)poolPassw.get(keyPool);
536
        }
537
        try {
538
            alphanumericConnection =new SeConnection(server, instance, database, user, password);
539
//            alphanumericConnection.startTransaction();
540
            spatialConnection = connection;
541
//            ((ConnectionSDE)spatialConnection).getConnection().startTransaction();
542
        } catch (SeException e) {
543
                NotificationManager.addError(e);
544
            return;
545
                }
546
        // Fetching data
547
        String layerName = tableName;
548
        SeObjectId layerID = null;
549
        String strSpatialColumn = "";
550

    
551
        try {
552
            Vector theLayers = ((ConnectionSDE)spatialConnection).getConnection().getLayers();
553

    
554
            for (int i = 0; i < theLayers.size(); i++) {
555
                SeLayer layer = (SeLayer) theLayers.elementAt(i);
556

    
557
                if (layer.getQualifiedName().compareToIgnoreCase(layerName) == 0) {
558
                        layerID = layer.getID();
559
                    strSpatialColumn = layer.getSpatialColumn();
560
                    this.layer=layer;
561
                    break;
562
                }
563

    
564

    
565
            }
566

    
567
            if (layerID == null) {
568
                System.err.println("Capa no encontrada");
569

    
570
                return;
571
            }
572

    
573
            // layerName = layer.getName();
574
//            layer = new SeLayer(((ConnectionSDE)spatialConnection).getConnection(), layerName, strSpatialColumn);
575

    
576
            //TODO aqu? se puede saber la proyecci?n
577
            //layer.getCoordRef().getSrid();
578

    
579
//            if ((cols != null) && (cols.length != 0)) {
580
//                if (!cols[0].equals(lyrDef.getFieldGeometry())) {
581
//                    this.fields = new String[cols.length + 1];
582
//                    this.fields[0] = lyrDef.getFieldGeometry();
583
//
584
//                    for (int i = 1; i < fields.length; i++) {
585
//                        fields[i] = cols[i - 1];
586
//                    }
587
//                } else {
588
//                    fields = cols;
589
//                }
590
//            } else {
591
//                SeSqlConstruct sqlConstruct = new SeSqlConstruct(tableName);
592
//                sqlTotal = sqlConstruct.getWhere();
593
//
594
//                SeTable table1 = new SeTable(conn, tableName);
595
//
596
//                /*
597
//                 *   Get the table's column definition.
598
//                 */
599
//                SeColumnDefinition[] tableDef = table1.describe();
600
//                this.fields = new String[tableDef.length];
601
//
602
//                /*
603
//                 *   Store the names of all the table's columns in the
604
//                 *   String array cols. This array specifies the columns
605
//                 *   to be retrieved from the database.
606
//                 */
607
//                int idField = 1;
608
//
609
//                for (int i = 0; i < tableDef.length; i++) {
610
//                    if (tableDef[i].getType() == SeColumnDefinition.TYPE_SHAPE) {
611
//                        this.fields[0] = tableDef[i].getName();
612
//                    } else {
613
//                        this.fields[idField] = tableDef[i].getName();
614
//                        idField++;
615
//                    }
616
//                }
617
//
618
//                lyrDef.setFieldNames(fields);
619
//            }
620
            fields=cols;
621
            sqlConstruct = new SeSqlConstruct(layerName);
622

    
623
            //      Create a query stream between the client and server
624
            query = new SeQuery(alphanumericConnection, fields, sqlConstruct);
625
            query.prepareQuery();
626
            query.execute();
627
            row = query.fetch();
628
            if (row == null) {
629
                System.out.println("La tabla " + getName() +
630
                    " no tiene registros");
631

    
632
                return;
633
            }
634

    
635
            colDefs = row.getColumns();
636
            lyrDef.setShapeType(obtainShapeType(row.getColumnDef(0).getType()));
637
            fieldTypes = new int[colDefs.length];
638

    
639
            for (int colNum = 0; colNum < colDefs.length; colNum++) {
640
                SeColumnDefinition colDef = colDefs[colNum];
641
                int dataType = colDef.getType();
642

    
643
                switch (dataType) {
644
                case SeColumnDefinition.TYPE_SHAPE:
645

    
646
                    if (colNum != 0) {
647
                        System.err.println(
648
                            "Por favor, el campo de shapes deber ser el primero");
649

    
650
                        return;
651
                    }
652

    
653
                    idSpatialColumn = colNum;
654

    
655
                    break;
656

    
657
                case SeColumnDefinition.TYPE_INT16:
658
                case SeColumnDefinition.TYPE_INT32:
659
                case SeColumnDefinition.TYPE_INT64:
660
                    fieldTypes[colNum] = Types.INTEGER;
661

    
662
                    break;
663

    
664
                case SeColumnDefinition.TYPE_FLOAT32:
665
                    fieldTypes[colNum] = Types.FLOAT;
666

    
667
                    break;
668

    
669
                case SeColumnDefinition.TYPE_FLOAT64:
670
                    fieldTypes[colNum] = Types.DOUBLE;
671

    
672
                    break;
673

    
674
                case SeColumnDefinition.TYPE_DATE:
675
                    fieldTypes[colNum] = Types.DATE;
676

    
677
                    break;
678

    
679
                default:
680
                    fieldTypes[colNum] = Types.VARCHAR;
681

    
682
                    break;
683
                }
684
            }
685
            fields=cols;
686
            SeQuery extentQuery = new SeQuery(((ConnectionSDE)spatialConnection).getConnection(), fields, sqlConstruct);
687
            SeQueryInfo queryInfo = new SeQueryInfo();
688
            queryInfo.setConstruct(sqlConstruct);
689

    
690
            SeExtent seExtent = extentQuery.calculateLayerExtent(queryInfo);
691
            fullExtent = new Rectangle2D.Double(seExtent.getMinX(),
692
                    seExtent.getMinY(),
693
                    seExtent.getMaxX() - seExtent.getMinX(),
694
                    seExtent.getMaxY() - seExtent.getMinY());
695
            extentQuery.close();
696

    
697
            doRelateID_FID();
698
        } catch (SeException e) {
699
                throw new DBException(e);
700
        }
701
    }
702

    
703
    private int obtainShapeType(int type) {
704
        int shapeType = -1;
705

    
706
        switch (type) {
707
        case SeLayer.TYPE_POINT:
708
            shapeType = FShape.POINT;
709

    
710
            break;
711

    
712
        case SeLayer.TYPE_LINE:
713
        case SeLayer.TYPE_SIMPLE_LINE:
714
        case SeLayer.TYPE_MULTI_LINE:
715
        case SeLayer.TYPE_MULTI_SIMPLE_LINE:
716
            shapeType = FShape.LINE;
717

    
718
            break;
719

    
720
        case SeLayer.TYPE_POLYGON:
721
        case SeLayer.TYPE_MULTI_POLYGON:
722
            shapeType = FShape.POLYGON;
723

    
724
            break;
725

    
726
        default:
727
            shapeType = FShape.MULTI;
728
        }
729

    
730
        return shapeType;
731
    }
732

    
733
    public String getCompleteWhere() {
734
        return null;
735
    }
736

    
737
    public String getConnectionStringBeginning() {
738
        return "sde";
739
    }
740

    
741
    public int getDefaultPort() {
742
        return 5151;
743
    }
744

    
745
    public String getSourceProjection(IConnection conn,DBLayerDefinition dbld) {
746
        return originalEPSG;
747
    }
748

    
749
    public String getDestProjection() {
750
        return strEPSG;
751
    }
752

    
753
    public void setDestProjection(String toEPSG) {
754
        this.strEPSG = toEPSG;
755
    }
756

    
757
    public boolean canReproject(String toEPSGdestinyProjection) {
758
        //                 TODO POR AHORA, REPROYECTA SIEMPRE gvSIG.
759
        return false;
760
    }
761

    
762
    public IWriter getWriter() {
763
             if (writer == null) {
764
             writer = new ArcSdeWriter();
765
             writer.setDriver(this);
766
             writer.setSeLayer(layer);
767
             try {
768
                 writer.initialize(getLyrDef());
769
             }
770
             catch (EditionException e) {
771

    
772
             }
773
         }
774

    
775
         return writer;
776
    }
777

    
778
    /**
779
         * @return
780
         * @uml.property  name="sqlTotal"
781
         */
782
    public String getSqlTotal() {
783
                return sqlTotal;
784
        }
785

    
786
    public XMLEntity getXMLEntity() {
787
        DBLayerDefinition lyrDef = getLyrDef();
788
        XMLEntity xml = new XMLEntity();
789
        xml.putProperty("className", this.getClass().getName());
790
        xml.putProperty("driverclass", this.getClass().getName());
791
        xml.putProperty("catalog", lyrDef.getCatalogName());
792

    
793
        ConnectionWithParams cwp =
794
                SingleVectorialDBConnectionManager.instance().findConnection(getConnection());
795

    
796

    
797
        // TODO: NO DEBEMOS GUARDAR EL NOMBRE DE USUARIO Y CONTRASE?A
798
        // AQUI. Hay que utilizar un pool de conexiones
799
        // y pedir al usuario que conecte a la base de datos
800
        // en la primera capa. En el resto, usar la conexi?n
801
        // creada con anterioridad.
802
        String userName = lyrDef.getUser();
803
        if (userName != null) {
804
            int aux = userName.indexOf("@");
805

    
806
            if (aux != -1) {
807
                userName = userName.substring(0, aux);
808
            }
809
        }
810

    
811
        xml.putProperty("username", userName);
812

    
813
        xml.putProperty("tablename", getTableName());
814
        xml.putProperty("fields", fields);
815
        xml.putProperty("ID", lyrDef.getFieldID());
816
        xml.putProperty("idfield",lyrDef.getIdFieldID());
817
        xml.putProperty("THE_GEOM", lyrDef.getFieldGeometry());
818
        xml.putProperty("whereclause", getWhereClause());
819
        xml.putProperty("SRID", lyrDef.getSRID_EPSG());
820

    
821
        xml.putProperty("host", lyrDef.getHost());
822
        xml.putProperty("port", lyrDef.getPort());
823
        xml.putProperty("dbName", lyrDef.getDataBase());
824
        xml.putProperty("connName", cwp.getName());
825

    
826
        xml.putProperty("typeShape",lyrDef.getShapeType());
827

    
828
        if (getWorkingArea() != null) {
829
            xml.putProperty("minXworkArea", getWorkingArea().getMinX());
830
            xml.putProperty("minYworkArea", getWorkingArea().getMinY());
831
            xml.putProperty("HworkArea", getWorkingArea().getHeight());
832
            xml.putProperty("WworkArea", getWorkingArea().getWidth());
833
        }
834

    
835
        return xml;
836
    }
837

    
838
    public void setXMLEntity(XMLEntity xml) throws XMLException {
839
        className = xml.getStringProperty("className");
840
        catalogName = xml.getStringProperty("catalog");
841
        lyrDef = new DBLayerDefinition();
842

    
843
        if (xml.contains("username")) {
844
            lyrDef.setUser(xml.getStringProperty("username"));
845
        }
846

    
847
        driverClass = xml.getStringProperty("driverclass");
848
        lyrDef.setTableName(xml.getStringProperty("tablename"));
849
        fields = xml.getStringArrayProperty("fields");
850
        lyrDef.setFieldNames(fields);
851
        lyrDef.setFieldID(xml.getStringProperty("ID"));
852
        if (xml.contains("idfield"))
853
                lyrDef.setIdFieldID(xml.getIntProperty("idfield"));
854
        lyrDef.setFieldGeometry(xml.getStringProperty("THE_GEOM"));
855
        lyrDef.setWhereClause(xml.getStringProperty("whereclause"));
856
        lyrDef.setSRID_EPSG(xml.getStringProperty("SRID"));
857

    
858
        if (xml.contains("host")) {
859
            lyrDef.setHost(xml.getStringProperty("host"));
860
            lyrDef.setPort(Integer.parseInt(xml.getStringProperty("port")));
861
            lyrDef.setDataBase(xml.getStringProperty("dbName"));
862
            lyrDef.setConnectionName(xml.getStringProperty("connName"));
863
        }
864
        lyrDef.setShapeType(xml.getIntProperty("typeShape"));
865
        if (xml.contains("minXworkArea")) {
866
            double x = xml.getDoubleProperty("minXworkArea");
867
            double y = xml.getDoubleProperty("minYworkArea");
868
            double H = xml.getDoubleProperty("HworkArea");
869
            double W = xml.getDoubleProperty("WworkArea");
870
            workingArea = new Rectangle2D.Double(x, y, W, H);
871
        }
872

    
873
        lyrDef.setCatalogName(catalogName);
874

    
875
        if (workingArea != null) {
876
            lyrDef.setWorkingArea(workingArea);
877
        }
878

    
879
        setLyrDef(lyrDef);
880
    }
881

    
882
    public int getFieldWidth(int fieldId) {
883
        return colDefs[fieldId+1].getSize();
884
    }
885

    
886
    public void setLyrDef(DBLayerDefinition lyrDef) {
887
        this.lyrDef =lyrDef;
888
    }
889

    
890
    /**
891
         * @see  com.iver.cit.gvsig.fmap.drivers.IVectorialJDBCDriver#setWorkingArea(java.awt.geom.Rectangle2D)
892
         * @uml.property  name="workingArea"
893
         */
894
    public void setWorkingArea(Rectangle2D rect) {
895
                this.workingArea = rect;
896
        }
897

    
898
    /**
899
         * @see  com.iver.cit.gvsig.fmap.drivers.IVectorialJDBCDriver#getWorkingArea()
900
         * @uml.property  name="workingArea"
901
         */
902
    public Rectangle2D getWorkingArea() {
903
                return workingArea;
904
        }
905

    
906
    /**
907
     * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getShapeType()
908
     */
909
    public int getShapeType() {
910
        return lyrDef.getShapeType();
911
    }
912

    
913
    /* (non-Javadoc)
914
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getWhereClause()
915
     */
916
    public String getWhereClause() {
917
        if (lyrDef.getWhereClause() == null) {
918
            return "";
919
        }
920

    
921
        return lyrDef.getWhereClause().toUpperCase();
922
    }
923

    
924
    /**
925
         * @return
926
         */
927
    public DBLayerDefinition getLyrDef() {
928
            // Esto hace saltar un error.
929
//            if (this.spatialConnection != null){
930
//                    lyrDef.setSeConnection();
931
//            }
932
        return lyrDef;
933
    }
934

    
935
    /**
936
     * Empty method called when the layer is going to be removed from the view.
937
     * Subclasses can overwrite it if needed.
938
     */
939
    public void remove() {
940
    }
941

    
942
    /* (non-Javadoc)
943
    * @see com.iver.cit.gvsig.fmap.drivers.VectorialDriver#reLoad()
944
    */
945
    public void reload() throws IOException {
946
            try {
947
                        load();
948
                } catch (DriverException e) {
949
                        NotificationManager.addError(e);
950
                }
951
               //setData(null, lyrDef);
952
    }
953

    
954
    public void setDataSourceFactory(DataSourceFactory dsf) {
955
        // TODO Auto-generated method stub
956
    }
957

    
958
    public void load() throws DriverException {
959
            try {
960
            if (driverClass != null)
961
                    Class.forName(driverClass);
962

    
963
            String _drvName = getName();
964

    
965
            String keyPool = _drvName.toLowerCase() + "_" + lyrDef.getHost().toLowerCase()
966
            + "_" + lyrDef.getPort() + "_" + lyrDef.getDataBase().toLowerCase()
967
            + "_" + lyrDef.getUser().toLowerCase();
968

    
969
            IConnection newConn = null;
970
            String clave = null;
971
            ConnectionWithParams cwp = null;
972

    
973
            if (poolPassw.containsKey(keyPool)) {
974

    
975
                clave = (String) poolPassw.get(keyPool);
976
                cwp = SingleVectorialDBConnectionManager.instance().getConnection(
977
                                         _drvName, lyrDef.getUser(), clave, lyrDef.getConnectionName(),
978
                                         lyrDef.getHost(), String.valueOf(lyrDef.getPort()), lyrDef.getDataBase(), true);
979

    
980
            } else {
981

    
982
                cwp = SingleVectorialDBConnectionManager.instance().getConnection(
983
                                             _drvName, lyrDef.getUser(), null, lyrDef.getConnectionName(),
984
                                             lyrDef.getHost(), String.valueOf(lyrDef.getPort()), lyrDef.getDataBase(), false);
985

    
986
                if (cwp.isConnected()) {
987

    
988
                        poolPassw.put(keyPool, cwp.getPw());
989

    
990
                } else {
991

    
992
                    JPasswordDlg dlg = new JPasswordDlg();
993
                    dlg.setLocationRelativeTo((Component)PluginServices.getMainFrame());
994
                    String strMessage = Messages.getString("conectar_jdbc");
995
                    String strPassword = Messages.getString("password");
996
                    dlg.setMessage(strMessage
997
                                    + " ["
998
                                    + _drvName + ", "
999
                                    + lyrDef.getHost() + ", "
1000
                                    + String.valueOf(lyrDef.getPort()) + ", "
1001
                                    + lyrDef.getDataBase() + ", "
1002
                                    + lyrDef.getUser() + "]. "
1003
                                    + strPassword
1004
                                    + "?");
1005
                    dlg.setVisible(true);
1006
                    clave = dlg.getPassword();
1007
                    if (clave == null)
1008
                        return;
1009
                    poolPassw.put(keyPool, clave);
1010

    
1011
                    cwp.connect(clave);
1012
                }
1013
            }
1014

    
1015
            newConn = cwp.getConnection();
1016
//            newConn.setAutoCommit(false);
1017

    
1018
            DBLayerDefinition lyrDef = new DBLayerDefinition();
1019
            if (getLyrDef() == null) {
1020
                    lyrDef.setCatalogName(catalogName);
1021
                    lyrDef.setTableName(getTableName());
1022
                    lyrDef.setFieldNames(fields);
1023
                    lyrDef.setFieldID(FIDfield);
1024
                    lyrDef.setFieldGeometry(geometryField);
1025
                    lyrDef.setWhereClause(whereClause);
1026
                    // lyrDef.setClassToInstantiate(driverClass);
1027
                    if (workingArea != null)
1028
                        lyrDef.setWorkingArea(workingArea);
1029

    
1030
                    lyrDef.setSRID_EPSG(strSRID);
1031
            } else {
1032
                    lyrDef = getLyrDef();
1033
            }
1034

    
1035
            setData(newConn, lyrDef);
1036
        } catch (ClassNotFoundException e) {
1037
            DriverJdbcNotFoundExceptionType type =
1038
                    new DriverJdbcNotFoundExceptionType();
1039
            type.setDriverJdbcClassName(driverClass);
1040
            type.setLayerName(this.getTableName());
1041
            throw new DriverException("Driver JDBC no encontrado", e,  type);
1042
        } catch (DBException e) {
1043

    
1044
                throw new DriverException(e.getMessage());
1045

    
1046
                }
1047
    }
1048

    
1049
    public IConnection getConnection() {
1050
        return spatialConnection;
1051
    }
1052
        public String getConnectionString(
1053
                    String host,
1054
                    String port,
1055
                    String dbname,
1056
                    String user,
1057
                    String pw) {
1058

    
1059
                String resp = getConnectionStringBeginning()+ ":" + host.toLowerCase();
1060

    
1061
                if (dbname.trim().length() > 0) {
1062
                        resp += ":" + port;
1063
                } else {
1064
                        resp += ":" + getDefaultPort();
1065
                }
1066

    
1067
                resp += ":" + dbname.toLowerCase();
1068
                return resp;
1069
    }
1070
        public String[] getAllFields(IConnection conex, String tableName) throws DBException {
1071
                try {
1072
                        SeTable table = null;
1073
                        Vector tables=((ConnectionSDE)conex).getConnection().getTables(SeDefs.SE_SELECT_PRIVILEGE);
1074
                        for (int i=0;i<tables.size();i++) {
1075
                                if (tableName.equals(((SeTable)tables.get(i)).getQualifiedName())) {
1076
                                        table=(SeTable)tables.get(i);
1077
                                        break;
1078
                                }
1079
                        }
1080
                        SeRegisteredColumn[] columns=table.getColumnList();
1081
                        String[] fieldNames=new String[columns.length];
1082
                        for (int i=0; i < columns.length; i++){
1083
                                fieldNames[i]=columns[i].getName();
1084
                        }
1085
                        return fieldNames;
1086
                } catch (SeException e) {
1087
                        throw new DBException(e);
1088
                }
1089
        }
1090
        public String[] getAllFieldTypeNames(IConnection conex, String tableName) throws DBException {
1091
                try {
1092
                        SeTable table = null;
1093
                        Vector tables=((ConnectionSDE)conex).getConnection().getTables(SeDefs.SE_SELECT_PRIVILEGE);
1094
                        for (int i=0;i<tables.size();i++) {
1095
                                if (tableName.equals(((SeTable)tables.get(i)).getQualifiedName())) {
1096
                                        table=(SeTable)tables.get(i);
1097
                                        break;
1098
                                }
1099
                        }
1100
                        SeRegisteredColumn[] columns=table.getColumnList();
1101
                        String[] fieldNames=new String[columns.length];
1102
                        for (int i=0; i < columns.length; i++){
1103
                                fieldNames[i]=String.valueOf(columns[i].getType());
1104
                        }
1105
                        return fieldNames;
1106
                } catch (SeException e) {
1107
                        throw new DBException(e);
1108
                }
1109
        }
1110
        public String[] getIdFieldsCandidates(IConnection conn2, String tableName) throws DBException {
1111
                return getAllFields(conn2,tableName);
1112
        }
1113
        public String[] getGeometryFieldsCandidates(IConnection conn2, String tableName) {
1114
                return new String[]{"SHAPE"};//getAllFields(conn2,tableName);
1115
        }
1116
        public String[] getTableNames(IConnection conex, String dbName) throws DBException {
1117
                 try {
1118
                        Vector theLayers = ((ConnectionSDE)conex).getConnection().getLayers();
1119
                        TreeMap ret = new TreeMap();
1120
                        for (int i = 0; i < theLayers.size(); i++) {
1121
                                SeLayer layer = (SeLayer) theLayers.elementAt(i);
1122
                                ret.put(layer.getQualifiedName(), layer.getQualifiedName());
1123
                        }
1124
                        return (String[]) ret.keySet().toArray(new String[0]);
1125
                        } catch (SeException e) {
1126
                                throw new DBException(e);
1127
                        }
1128
                }
1129
         public String[] getTableFields(IConnection conex,String tableName) throws DBException{
1130
                        try {
1131
                                SeTable table = new SeTable(((ConnectionSDE)conex).getConnection(),tableName);
1132
                                SeRegisteredColumn[] columns=table.getColumnList();
1133
                                String[] fieldNames=new String[columns.length];
1134
                                for (int i=0; i < columns.length; i++){
1135
                                        fieldNames[i]=columns[i].getName();
1136
                                }
1137
                                return fieldNames;
1138
                        } catch (SeException e) {
1139
                                throw new DBException(e);
1140
                        }
1141
                }
1142

    
1143
}