Statistics
| Revision:

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

History | View | Annotate | Download (40.4 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.sql.Types;
49
import java.util.Hashtable;
50
import java.util.TreeMap;
51
import java.util.Vector;
52

    
53
import com.esri.sde.sdk.client.SeColumnDefinition;
54
import com.esri.sde.sdk.client.SeConnection;
55
import com.esri.sde.sdk.client.SeDefs;
56
import com.esri.sde.sdk.client.SeException;
57
import com.esri.sde.sdk.client.SeExtent;
58
import com.esri.sde.sdk.client.SeFilter;
59
import com.esri.sde.sdk.client.SeLayer;
60
import com.esri.sde.sdk.client.SeObjectId;
61
import com.esri.sde.sdk.client.SeQuery;
62
import com.esri.sde.sdk.client.SeQueryInfo;
63
import com.esri.sde.sdk.client.SeRegisteredColumn;
64
import com.esri.sde.sdk.client.SeRow;
65
import com.esri.sde.sdk.client.SeShape;
66
import com.esri.sde.sdk.client.SeShapeFilter;
67
import com.esri.sde.sdk.client.SeSqlConstruct;
68
import com.esri.sde.sdk.client.SeTable;
69
import com.hardcode.gdbms.driver.exceptions.InitializeWriterException;
70
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
71
import com.hardcode.gdbms.driver.exceptions.ReloadDriverException;
72
import com.hardcode.gdbms.engine.data.DataSourceFactory;
73
import com.hardcode.gdbms.engine.data.driver.ObjectDriver;
74
import com.hardcode.gdbms.engine.data.edition.DataWare;
75
import com.hardcode.gdbms.engine.values.Value;
76
import com.hardcode.gdbms.engine.values.ValueFactory;
77
import com.iver.andami.PluginServices;
78
import com.iver.andami.messages.Messages;
79
import com.iver.andami.messages.NotificationManager;
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.IWriteable;
93
import com.iver.cit.gvsig.fmap.edition.IWriter;
94
import com.iver.cit.gvsig.fmap.layers.XMLException;
95
import com.iver.utiles.XMLEntity;
96
import com.iver.utiles.swing.JPasswordDlg;
97

    
98

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

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

    
145
                if (row == null) {
146
                System.out.println(" No rows fetched");
147

    
148
                return;
149
            }
150

    
151
            int index = 0;
152
            int fid=getLyrDef().getIdFieldID();
153
            Value value=getFieldValue(index,fid);
154

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

    
163

    
164
            }
165

    
166
            numReg = index;
167
    }
168
    /* (non-Javadoc)
169
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDriver#getFullExtent()
170
     */
171
    public Rectangle2D getFullExtent() {
172
                return fullExtent;
173
        }
174
    /* (non-Javadoc)
175
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDriver#getShape(int)
176
     */
177
    public IGeometry getShape(int index) {
178
        SeRow row;
179

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

    
193
    /* (non-Javadoc)
194
     * @see com.iver.cit.gvsig.fmap.drivers.sde.IVectorialSDEDriver#getFeatureIterator(java.lang.String)
195
     */
196
    public IFeatureIterator getFeatureIterator(String sql){
197
        return null;
198
    }
199

    
200
    /* (non-Javadoc)
201
     * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#getFeatureIterator(java.awt.geom.Rectangle2D, java.lang.String)
202
     */
203
    public IFeatureIterator getFeatureIterator(Rectangle2D r, String strEPSG) {
204
        /*
205
         *   Generate a rectangular shape that will be used as a filter
206
         */
207
        try {
208
            SeShape shape = new SeShape(layer.getCoordRef());
209
            SeExtent extent=layer.getExtent();
210
            shape.generateRectangle(extent);
211

    
212
            SeShape[] shapes = new SeShape[1];
213
            shapes[0] = shape;
214

    
215
            /*
216
             *   Retrieve all the shapes that are contained within the
217
             *   rectangles envelope.
218
             */
219
//            SeShapeFilter[] filters = new SeShapeFilter[1];
220
//            SeShapeFilter filter = null;
221
//
222
//            filter = new SeShapeFilter(layer.getQualifiedName(),
223
//                    layer.getSpatialColumn(), shape, SeFilter.METHOD_ENVP);
224
//            filters[0] = filter;
225

    
226
            SeQuery spatialQuery = null;
227
            SeSqlConstruct sqlCons = new SeSqlConstruct(layer.getQualifiedName());
228

    
229
            spatialQuery = new SeQuery(alphanumericConnection, fields, sqlCons);
230

    
231
            /*
232
             *   Set spatial constraints
233
             */
234
//            spatialQuery.setSpatialConstraints(SeQuery.SE_OPTIMIZE, false,
235
//                filters);
236

    
237
            spatialQuery.prepareQuery();
238

    
239
            spatialQuery.execute();
240

    
241
            return new ArcSdeFeatureIterator(spatialQuery,getLyrDef().getFieldID());
242
        } catch (SeException e) {
243
                NotificationManager.addError(e);
244
            return null;
245
        }
246
    }
247

    
248
    /* (non-Javadoc)
249
     * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#close()
250
     */
251
    public void close() {
252
    }
253

    
254
    /* (non-Javadoc)
255
     * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#open()
256
     */
257
    public void open() {
258
    }
259

    
260
    /* (non-Javadoc)
261
     * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#getRowIndexByFID(com.iver.cit.gvsig.fmap.core.IFeature)
262
     */
263
    public int getRowIndexByFID(IFeature FID) {
264
        int resul;
265
        String strID = FID.getID();
266
        Integer rowIndex = (Integer) hashRelate.get(strID);
267

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

    
276
    /* (non-Javadoc)
277
     * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#getGeometryField(java.lang.String)
278
     */
279
    public String getGeometryField(String fieldName) {
280
        return layer.getSpatialColumn();
281
    }
282

    
283
    /* (non-Javadoc)
284
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDriver#getShapeCount()
285
     */
286
    public int getShapeCount() {
287
        return numReg;
288
    }
289

    
290
    /* (non-Javadoc)
291
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDriver#getDriverAttributes()
292
     */
293
    public DriverAttributes getDriverAttributes() {
294
        return null;
295
    }
296

    
297
    /* (non-Javadoc)
298
     * @see com.hardcode.driverManager.Driver#getName()
299
     */
300
    public String getName() {
301
        return "gvSIG SDE driver";
302
    }
303

    
304
    /* (non-Javadoc)
305
     * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#getFields()
306
     */
307
    public String[] getFields() {
308
                String[] attributes = new String[fields.length - 1];
309
                for (int i = 1; i < fields.length; i++)
310
                        attributes[i - 1] = fields[i];
311
                return attributes;
312
        }
313

    
314
    /* (non-Javadoc)
315
     * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#getTableName()
316
     */
317
    public String getTableName() {
318
        try {
319
                        return layer.getQualifiedName();
320
                } catch (SeException e) {
321
                        e.printStackTrace();
322
                }
323
                return layer.getName();
324
    }
325

    
326
    private synchronized SeRow obtainRow(long rowIndex) throws SeException {
327
       if (rowIndex != posActual) {
328
            if (rowIndex == 0) {
329
                if (query != null) {
330
                    if (query.inProgress()) {
331
                        query.close();
332
                    }
333
                    query = new SeQuery(((ConnectionSDE)spatialConnection).getConnection(), fields, sqlConstruct);
334
                    query.prepareQuery();
335
                    query.execute();
336
                }
337
                lastRowServed = -1;
338
            }
339

    
340
            if (lastRowServed == (rowIndex - 1)) {
341
                row = query.fetch();
342
                lastRowServed++;
343
            } else {
344
                if (queryAux != null && queryAux.inProgress()) {
345
                        queryAux.close();
346
                }
347

    
348
                queryAux = new SeQuery(((ConnectionSDE)spatialConnection).getConnection(), fields, sqlConstruct);
349
                SeObjectId rowID = new SeObjectId(rowIndex + 1);
350
                row = queryAux.fetchRow(layer.getQualifiedName(), rowID, fields);
351
            }
352
            posActual = rowIndex;
353
            cachedRow = row;
354
        }
355

    
356
        return cachedRow;
357
    }
358

    
359
    /* (non-Javadoc)
360
     * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldValue(long, int)
361
     */
362
    public Value getFieldValue(long rowIndex, int fieldId) {
363
        SeRow row;
364
        Value val = null;
365

    
366
        try {
367
            int idFieldArcSDE = fieldId+1; // SIEMPRE CONTANDO CON
368
            // QUE NOS HAN PASADO EL PRIMER CAMPO EL DE SHAPE
369
            row = obtainRow(rowIndex);
370
            if (row==null)
371
                    return null;
372
            int dataType = colDefs[idFieldArcSDE].getType();
373

    
374
            switch (dataType) {
375
            case SeColumnDefinition.TYPE_INT16:
376
                val = ValueFactory.createValue(row.getShort(idFieldArcSDE)
377
                                                  .intValue());
378

    
379
                break;
380

    
381
            case SeColumnDefinition.TYPE_INT32:
382
            case SeColumnDefinition.TYPE_INT64:
383
                val = ValueFactory.createValue(row.getInteger(idFieldArcSDE)
384
                                                  .intValue());
385

    
386
                break;
387

    
388
            case SeColumnDefinition.TYPE_FLOAT32:
389
                val = ValueFactory.createValue(row.getFloat(idFieldArcSDE)
390
                                                  .floatValue());
391

    
392
                break;
393

    
394
            case SeColumnDefinition.TYPE_FLOAT64:
395
                val = ValueFactory.createValue(row.getDouble(idFieldArcSDE)
396
                                                  .doubleValue());
397

    
398
                break;
399

    
400
            case SeColumnDefinition.TYPE_DATE:
401
                val = ValueFactory.createValue(row.getTime(idFieldArcSDE)
402
                                                  .getTime());
403

    
404
                break;
405

    
406
            case SeColumnDefinition.TYPE_STRING:
407
                String strAux = row.getString(idFieldArcSDE);
408

    
409
                if (strAux == null) {
410
                    strAux = "";
411
                }
412

    
413
                val = ValueFactory.createValue(strAux);
414

    
415
                break;
416
            case SeColumnDefinition.TYPE_NSTRING:
417
                String nstrAux = row.getNString(idFieldArcSDE);
418
                if (nstrAux == null) {
419
                    nstrAux = "";
420
                }
421

    
422
                val = ValueFactory.createValue(nstrAux);
423

    
424
                break;
425
            }
426

    
427
            return val;
428

    
429
        } catch (SeException e) {
430
                NotificationManager.addError(e);
431
        }
432

    
433
        return ValueFactory.createNullValue();
434
    }
435

    
436
    /* (non-Javadoc)
437
     * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldCount()
438
     */
439
    public int getFieldCount(){
440
        return fields.length - 1;
441
    }
442

    
443
    /* (non-Javadoc)
444
     * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldName(int)
445
     */
446
    public String getFieldName(int fieldId) {
447
        return fields[fieldId + 1];
448
    }
449

    
450
    /* (non-Javadoc)
451
     * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getRowCount()
452
     */
453
    public long getRowCount() {
454
        return numReg;
455
    }
456

    
457
    /* (non-Javadoc)
458
     * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldType(int)
459
     */
460
    public int getFieldType(int i) {
461
        return fieldTypes[i+1];
462
    }
463

    
464
    /**
465
     * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#getPrimaryKeys()
466
     */
467
    public int[] getPrimaryKeys() {
468
        throw new UnsupportedOperationException();
469
    }
470

    
471
    /* (non-Javadoc)
472
     * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#write(com.hardcode.gdbms.engine.data.edition.DataWare)
473
     */
474
    public void write(DataWare arg0) {
475
    }
476

    
477
    /* (non-Javadoc)
478
     * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#getFeatureIterator(java.awt.geom.Rectangle2D, java.lang.String, java.lang.String[])
479
     */
480
    public IFeatureIterator getFeatureIterator(Rectangle2D r, String strEPSG,
481
        String[] alphaNumericFieldsNeeded) {
482
        /*
483
        *   Generate a rectangular shape that will be used as a filter
484
        */
485
        try {
486
            SeShape shape = new SeShape(layer.getCoordRef());
487
            SeExtent extent=layer.getExtent();
488
            shape.generateRectangle(extent);
489

    
490
            SeShape[] shapes = new SeShape[1];
491
            shapes[0] = shape;
492

    
493
            /*
494
             *   Retrieve all the shapes that are contained within the
495
             *   rectangles envelope.
496
             */
497
//            SeShapeFilter[] filters = new SeShapeFilter[1];
498
//            SeShapeFilter filter = null;
499
//
500
//            filter = new SeShapeFilter(layer.getQualifiedName(),
501
//                    layer.getSpatialColumn(), shape, SeFilter.METHOD_ENVP);
502
//            filters[0] = filter;
503

    
504
            SeQuery spatialQuery = null;
505
            SeSqlConstruct sqlCons = new SeSqlConstruct(layer.getQualifiedName());
506

    
507
            spatialQuery = new SeQuery(alphanumericConnection, fields, sqlCons);
508

    
509
            /*
510
             *   Set spatial constraints
511
             */
512
//            spatialQuery.setSpatialConstraints(SeQuery.SE_OPTIMIZE, false,
513
//                filters);
514

    
515
            spatialQuery.prepareQuery();
516

    
517
            spatialQuery.execute();
518

    
519
            return new ArcSdeFeatureIterator(spatialQuery,getLyrDef().getFieldID());
520
        } catch (SeException e) {
521
                NotificationManager.addError(e);
522

    
523
            return null;
524
        }
525
    }
526

    
527
    /* (non-Javadoc)
528
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDriver#isWritable()
529
     */
530
    public boolean isWritable() {
531
        return false;
532
    }
533
    /* (non-Javadoc)
534
     * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#setData(com.iver.cit.gvsig.fmap.drivers.IConnection, com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition)
535
     */
536
    public void setData(IConnection connection, DBLayerDefinition lyrDef) throws DBException {
537
             String[] fieldsAux=null;
538
         FieldDescription[] fds=lyrDef.getFieldsDesc();
539
             if ((fds != null) && (fds.length != 0)) {
540
             if (!fds[0].getFieldName().equals(lyrDef.getFieldGeometry())) {
541
                 fieldsAux = new String[fds.length + 1];
542
                 fieldsAux[0] = lyrDef.getFieldGeometry();
543

    
544
                 for (int k = 1; k < fds.length+1; k++) {
545
                     fieldsAux[k] = fds[k - 1].getFieldName();
546
                 }
547
             }else{
548
                     fieldsAux = new String[fds.length];
549
                     for (int k = 0; k < fds.length; k++) {
550
                     fieldsAux[k] = fds[k].getFieldName();
551
                 }
552
             }
553
         }
554
        lyrDef.setFieldNames(fieldsAux);
555
        lyrDef.setIdFieldID(lyrDef.getIdField(lyrDef.getFieldID())-1);
556
        setLyrDef(lyrDef);
557
        // Conexi?n:
558
        String server = lyrDef.getHost();
559
        int instance = lyrDef.getPort();
560
        String database = lyrDef.getDataBase();
561
        String user = lyrDef.getUser();
562
        String[] cols = lyrDef.getFieldNames();
563
        String tableName = lyrDef.getComposedTableName();
564
        String password;
565
        if (lyrDef.getPassword()!=null){
566
                password=lyrDef.getPassword();
567
        }else{
568
                String keyPool = getName().toLowerCase() + "_" + lyrDef.getHost().toLowerCase()
569
                        + "_" + lyrDef.getPort() + "_" + lyrDef.getDataBase().toLowerCase()
570
                        + "_" + lyrDef.getUser().toLowerCase();
571
                password=(String)poolPassw.get(keyPool);
572
        }
573
        try {
574
            alphanumericConnection =new SeConnection(server, instance, database, user, password);
575
//            alphanumericConnection.startTransaction();
576
            spatialConnection = connection;
577
//            ((ConnectionSDE)spatialConnection).getConnection().startTransaction();
578
        } catch (SeException e) {
579
                NotificationManager.addError(e);
580
            return;
581
                }
582
        // Fetching data
583
        String layerName = tableName;
584
        SeObjectId layerID = null;
585
        String strSpatialColumn = "";
586

    
587
        try {
588
            Vector theLayers = ((ConnectionSDE)spatialConnection).getConnection().getLayers();
589

    
590
            for (int i = 0; i < theLayers.size(); i++) {
591
                SeLayer layer = (SeLayer) theLayers.elementAt(i);
592

    
593
                if (layer.getQualifiedName().compareToIgnoreCase(layerName) == 0) {
594
                        layerID = layer.getID();
595
                    strSpatialColumn = layer.getSpatialColumn();
596
                    this.layer=layer;
597
                    break;
598
                }
599

    
600

    
601
            }
602

    
603
            if (layerID == null) {
604
                System.err.println("Capa no encontrada");
605

    
606
                return;
607
            }
608

    
609
            // layerName = layer.getName();
610
//            layer = new SeLayer(((ConnectionSDE)spatialConnection).getConnection(), layerName, strSpatialColumn);
611

    
612
            //TODO aqu? se puede saber la proyecci?n
613
            //layer.getCoordRef().getSrid();
614

    
615
//            if ((cols != null) && (cols.length != 0)) {
616
//                if (!cols[0].equals(lyrDef.getFieldGeometry())) {
617
//                    this.fields = new String[cols.length + 1];
618
//                    this.fields[0] = lyrDef.getFieldGeometry();
619
//
620
//                    for (int i = 1; i < fields.length; i++) {
621
//                        fields[i] = cols[i - 1];
622
//                    }
623
//                } else {
624
//                    fields = cols;
625
//                }
626
//            } else {
627
//                SeSqlConstruct sqlConstruct = new SeSqlConstruct(tableName);
628
//                sqlTotal = sqlConstruct.getWhere();
629
//
630
//                SeTable table1 = new SeTable(conn, tableName);
631
//
632
//                /*
633
//                 *   Get the table's column definition.
634
//                 */
635
//                SeColumnDefinition[] tableDef = table1.describe();
636
//                this.fields = new String[tableDef.length];
637
//
638
//                /*
639
//                 *   Store the names of all the table's columns in the
640
//                 *   String array cols. This array specifies the columns
641
//                 *   to be retrieved from the database.
642
//                 */
643
//                int idField = 1;
644
//
645
//                for (int i = 0; i < tableDef.length; i++) {
646
//                    if (tableDef[i].getType() == SeColumnDefinition.TYPE_SHAPE) {
647
//                        this.fields[0] = tableDef[i].getName();
648
//                    } else {
649
//                        this.fields[idField] = tableDef[i].getName();
650
//                        idField++;
651
//                    }
652
//                }
653
//
654
//                lyrDef.setFieldNames(fields);
655
//            }
656
            fields=cols;
657
            sqlConstruct = new SeSqlConstruct(layerName);
658

    
659
            //      Create a query stream between the client and server
660
            query = new SeQuery(alphanumericConnection, fields, sqlConstruct);
661
            query.prepareQuery();
662
            query.execute();
663
            row = query.fetch();
664
            if (row == null) {
665
                System.out.println("La tabla " + getName() +
666
                    " no tiene registros");
667

    
668
                return;
669
            }
670

    
671
            colDefs = row.getColumns();
672
            lyrDef.setShapeType(obtainShapeType(row.getColumnDef(0).getType()));
673
            fieldTypes = new int[colDefs.length];
674

    
675
            for (int colNum = 0; colNum < colDefs.length; colNum++) {
676
                SeColumnDefinition colDef = colDefs[colNum];
677
                int dataType = colDef.getType();
678

    
679
                switch (dataType) {
680
                case SeColumnDefinition.TYPE_SHAPE:
681

    
682
                    if (colNum != 0) {
683
                        System.err.println(
684
                            "Por favor, el campo de shapes deber ser el primero");
685

    
686
                        return;
687
                    }
688

    
689
                    idSpatialColumn = colNum;
690

    
691
                    break;
692

    
693
                case SeColumnDefinition.TYPE_INT16:
694
                case SeColumnDefinition.TYPE_INT32:
695
                case SeColumnDefinition.TYPE_INT64:
696
                    fieldTypes[colNum] = Types.INTEGER;
697

    
698
                    break;
699

    
700
                case SeColumnDefinition.TYPE_FLOAT32:
701
                    fieldTypes[colNum] = Types.FLOAT;
702

    
703
                    break;
704

    
705
                case SeColumnDefinition.TYPE_FLOAT64:
706
                    fieldTypes[colNum] = Types.DOUBLE;
707

    
708
                    break;
709

    
710
                case SeColumnDefinition.TYPE_DATE:
711
                    fieldTypes[colNum] = Types.DATE;
712

    
713
                    break;
714

    
715
                default:
716
                    fieldTypes[colNum] = Types.VARCHAR;
717

    
718
                    break;
719
                }
720
            }
721
            fields=cols;
722
            SeQuery extentQuery = new SeQuery(((ConnectionSDE)spatialConnection).getConnection(), fields, sqlConstruct);
723
            SeQueryInfo queryInfo = new SeQueryInfo();
724
            queryInfo.setConstruct(sqlConstruct);
725

    
726
            SeExtent seExtent = extentQuery.calculateLayerExtent(queryInfo);
727
            fullExtent = new Rectangle2D.Double(seExtent.getMinX(),
728
                    seExtent.getMinY(),
729
                    seExtent.getMaxX() - seExtent.getMinX(),
730
                    seExtent.getMaxY() - seExtent.getMinY());
731
            extentQuery.close();
732

    
733
            doRelateID_FID();
734
        } catch (SeException e) {
735
                throw new DBException(e);
736
        }
737
    }
738

    
739
    private int obtainShapeType(int type) {
740
        int shapeType = -1;
741

    
742
        switch (type) {
743
        case SeLayer.TYPE_POINT:
744
            shapeType = FShape.POINT;
745

    
746
            break;
747

    
748
        case SeLayer.TYPE_LINE:
749
        case SeLayer.TYPE_SIMPLE_LINE:
750
        case SeLayer.TYPE_MULTI_LINE:
751
        case SeLayer.TYPE_MULTI_SIMPLE_LINE:
752
            shapeType = FShape.LINE;
753

    
754
            break;
755

    
756
        case SeLayer.TYPE_POLYGON:
757
        case SeLayer.TYPE_MULTI_POLYGON:
758
            shapeType = FShape.POLYGON;
759

    
760
            break;
761

    
762
        default:
763
            shapeType = FShape.MULTI;
764
        }
765

    
766
        return shapeType;
767
    }
768

    
769
    public String getCompleteWhere() {
770
        return null;
771
    }
772

    
773
    /* (non-Javadoc)
774
     * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#getConnectionStringBeginning()
775
     */
776
    public String getConnectionStringBeginning() {
777
        return "sde";
778
    }
779

    
780
    /* (non-Javadoc)
781
     * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#getDefaultPort()
782
     */
783
    public int getDefaultPort() {
784
        return 5151;
785
    }
786

    
787
    public String getSourceProjection(IConnection conn,DBLayerDefinition dbld) {
788
        return originalEPSG;
789
    }
790

    
791
    /* (non-Javadoc)
792
     * @see com.iver.cit.gvsig.fmap.core.ICanReproject#getDestProjection()
793
     */
794
    public String getDestProjection() {
795
        return strEPSG;
796
    }
797

    
798
    /* (non-Javadoc)
799
     * @see com.iver.cit.gvsig.fmap.core.ICanReproject#setDestProjection(java.lang.String)
800
     */
801
    public void setDestProjection(String toEPSG) {
802
        this.strEPSG = toEPSG;
803
    }
804

    
805
    /* (non-Javadoc)
806
     * @see com.iver.cit.gvsig.fmap.core.ICanReproject#canReproject(java.lang.String)
807
     */
808
    public boolean canReproject(String toEPSGdestinyProjection) {
809
        //                 TODO POR AHORA, REPROYECTA SIEMPRE gvSIG.
810
        return false;
811
    }
812

    
813
    /* (non-Javadoc)
814
     * @see com.iver.cit.gvsig.fmap.edition.IWriteable#getWriter()
815
     */
816
    public IWriter getWriter() {
817
             if (writer == null) {
818
             writer = new ArcSdeWriter();
819
             writer.setDriver(this);
820
             writer.setSeLayer(layer);
821
             try {
822
                                writer.initialize(getLyrDef());
823
                        } catch (InitializeWriterException e) {
824
                                NotificationManager.addError(e);
825
                        }
826
         }
827

    
828
         return writer;
829
    }
830

    
831
    public String getSqlTotal() {
832
                return sqlTotal;
833
        }
834

    
835
    /* (non-Javadoc)
836
     * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#getXMLEntity()
837
     */
838
    public XMLEntity getXMLEntity() {
839
        DBLayerDefinition lyrDef = getLyrDef();
840
        XMLEntity xml = new XMLEntity();
841
        xml.putProperty("className", this.getClass().getName());
842
        xml.putProperty("driverclass", this.getClass().getName());
843
        xml.putProperty("catalog", lyrDef.getCatalogName());
844
        ConnectionWithParams cwp =
845
                SingleVectorialDBConnectionManager.instance().findConnection(getConnection());
846

    
847
        // TODO: NO DEBEMOS GUARDAR EL NOMBRE DE USUARIO Y CONTRASE?A
848
        // AQUI. Hay que utilizar un pool de conexiones
849
        // y pedir al usuario que conecte a la base de datos
850
        // en la primera capa. En el resto, usar la conexi?n
851
        // creada con anterioridad.
852
        String userName = lyrDef.getUser();
853
        if (userName != null) {
854
            int aux = userName.indexOf("@");
855

    
856
            if (aux != -1) {
857
                userName = userName.substring(0, aux);
858
            }
859
        }
860

    
861
        xml.putProperty("username", userName);
862

    
863
        xml.putProperty("tablename", getTableName());
864
        xml.putProperty("fields", fields);
865
        xml.putProperty("ID", lyrDef.getFieldID());
866
        xml.putProperty("idfield",lyrDef.getIdFieldID());
867
        xml.putProperty("THE_GEOM", lyrDef.getFieldGeometry());
868
        xml.putProperty("whereclause", getWhereClause());
869
        xml.putProperty("SRID", lyrDef.getSRID_EPSG());
870

    
871
        xml.putProperty("host", lyrDef.getHost());
872
        xml.putProperty("port", lyrDef.getPort());
873
        xml.putProperty("dbName", lyrDef.getDataBase());
874
        xml.putProperty("connName", cwp.getName());
875

    
876
        xml.putProperty("typeShape",lyrDef.getShapeType());
877

    
878
        if (getWorkingArea() != null) {
879
            xml.putProperty("minXworkArea", getWorkingArea().getMinX());
880
            xml.putProperty("minYworkArea", getWorkingArea().getMinY());
881
            xml.putProperty("HworkArea", getWorkingArea().getHeight());
882
            xml.putProperty("WworkArea", getWorkingArea().getWidth());
883
        }
884

    
885
        return xml;
886
    }
887

    
888
    /* (non-Javadoc)
889
     * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#setXMLEntity(com.iver.utiles.XMLEntity)
890
     */
891
    public void setXMLEntity(XMLEntity xml) throws XMLException {
892
        className = xml.getStringProperty("className");
893
        catalogName = xml.getStringProperty("catalog");
894
        lyrDef = new DBLayerDefinition();
895

    
896
        if (xml.contains("username")) {
897
            lyrDef.setUser(xml.getStringProperty("username"));
898
        }
899

    
900
        driverClass = xml.getStringProperty("driverclass");
901
        lyrDef.setTableName(xml.getStringProperty("tablename"));
902
        fields = xml.getStringArrayProperty("fields");
903
        lyrDef.setFieldNames(fields);
904
        lyrDef.setFieldID(xml.getStringProperty("ID"));
905
        if (xml.contains("idfield"))
906
                lyrDef.setIdFieldID(xml.getIntProperty("idfield"));
907
        lyrDef.setFieldGeometry(xml.getStringProperty("THE_GEOM"));
908
        lyrDef.setWhereClause(xml.getStringProperty("whereclause"));
909
        lyrDef.setSRID_EPSG(xml.getStringProperty("SRID"));
910

    
911
        if (xml.contains("host")) {
912
            lyrDef.setHost(xml.getStringProperty("host"));
913
            lyrDef.setPort(Integer.parseInt(xml.getStringProperty("port")));
914
            lyrDef.setDataBase(xml.getStringProperty("dbName"));
915
            lyrDef.setConnectionName(xml.getStringProperty("connName"));
916
        }
917
        lyrDef.setShapeType(xml.getIntProperty("typeShape"));
918
        if (xml.contains("minXworkArea")) {
919
            double x = xml.getDoubleProperty("minXworkArea");
920
            double y = xml.getDoubleProperty("minYworkArea");
921
            double H = xml.getDoubleProperty("HworkArea");
922
            double W = xml.getDoubleProperty("WworkArea");
923
            workingArea = new Rectangle2D.Double(x, y, W, H);
924
        }
925

    
926
        lyrDef.setCatalogName(catalogName);
927

    
928
        if (workingArea != null) {
929
            lyrDef.setWorkingArea(workingArea);
930
        }
931

    
932
        setLyrDef(lyrDef);
933
    }
934

    
935
    /* (non-Javadoc)
936
     * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldWidth(int)
937
     */
938
    public int getFieldWidth(int fieldId) {
939
        return colDefs[fieldId+1].getSize();
940
    }
941

    
942
    public void setLyrDef(DBLayerDefinition lyrDef) {
943
        this.lyrDef =lyrDef;
944
    }
945

    
946
    /* (non-Javadoc)
947
     * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#setWorkingArea(java.awt.geom.Rectangle2D)
948
     */
949
    public void setWorkingArea(Rectangle2D rect) {
950
                this.workingArea = rect;
951
        }
952

    
953
    /* (non-Javadoc)
954
     * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#getWorkingArea()
955
     */
956
    public Rectangle2D getWorkingArea() {
957
                return workingArea;
958
        }
959

    
960
    /* (non-Javadoc)
961
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDriver#getShapeType()
962
     */
963
    public int getShapeType() {
964
        return lyrDef.getShapeType();
965
    }
966

    
967
    /* (non-Javadoc)
968
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getWhereClause()
969
     */
970
    public String getWhereClause() {
971
        if (lyrDef.getWhereClause() == null) {
972
            return "";
973
        }
974

    
975
        return lyrDef.getWhereClause().toUpperCase();
976
    }
977

    
978
    /* (non-Javadoc)
979
     * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#getLyrDef()
980
     */
981
    public DBLayerDefinition getLyrDef() {
982
            // Esto hace saltar un error.
983
            //            if (this.spatialConnection != null){
984
            //                    lyrDef.setSeConnection();
985
            //            }
986
        return lyrDef;
987
    }
988

    
989
    /**
990
     * Empty method called when the layer is going to be removed from the view.
991
     * Subclasses can overwrite it if needed.
992
     */
993
    public void remove() {
994
    }
995

    
996
    /* (non-Javadoc)
997
    * @see com.iver.cit.gvsig.fmap.drivers.VectorialDriver#reLoad()
998
    */
999
    public void reload() throws ReloadDriverException{
1000
            try {
1001
                        load();
1002
                } catch (ReadDriverException e) {
1003
                        throw new ReloadDriverException(this.className,e);
1004
                }
1005
        }
1006

    
1007
    /* (non-Javadoc)
1008
     * @see com.hardcode.gdbms.engine.data.driver.GDBMSDriver#setDataSourceFactory(com.hardcode.gdbms.engine.data.DataSourceFactory)
1009
     */
1010
    public void setDataSourceFactory(DataSourceFactory dsf) {
1011
        // TODO Auto-generated method stub
1012
    }
1013

    
1014
    /* (non-Javadoc)
1015
     * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#load()
1016
     */
1017
    public void load() throws ReadDriverException{
1018
            try {
1019
            if (driverClass != null)
1020
                    Class.forName(driverClass);
1021

    
1022
            String _drvName = getName();
1023

    
1024
            String keyPool = _drvName.toLowerCase() + "_" + lyrDef.getHost().toLowerCase()
1025
            + "_" + lyrDef.getPort() + "_" + lyrDef.getDataBase().toLowerCase()
1026
            + "_" + lyrDef.getUser().toLowerCase();
1027

    
1028
            IConnection newConn = null;
1029
            String clave = null;
1030
            ConnectionWithParams cwp = null;
1031

    
1032
            if (poolPassw.containsKey(keyPool)) {
1033

    
1034
                clave = (String) poolPassw.get(keyPool);
1035
                cwp = SingleVectorialDBConnectionManager.instance().getConnection(
1036
                                             _drvName, lyrDef.getUser(), clave, lyrDef.getConnectionName(),
1037
                                             lyrDef.getHost(), String.valueOf(lyrDef.getPort()), lyrDef.getDataBase(), true);
1038

    
1039
            } else {
1040

    
1041
                     cwp = SingleVectorialDBConnectionManager.instance().getConnection(
1042
                                              _drvName, lyrDef.getUser(), null, lyrDef.getConnectionName(),
1043
                                              lyrDef.getHost(), String.valueOf(lyrDef.getPort()), lyrDef.getDataBase(), false);
1044

    
1045
                if (cwp.isConnected()) {
1046

    
1047
                        poolPassw.put(keyPool, cwp.getPw());
1048

    
1049
                } else {
1050

    
1051
                    JPasswordDlg dlg = new JPasswordDlg();
1052
                    dlg.setLocationRelativeTo((Component)PluginServices.getMainFrame());
1053
                    String strMessage = Messages.getString("conectar_jdbc");
1054
                    String strPassword = Messages.getString("password");
1055
                    dlg.setMessage(strMessage
1056
                                    + " ["
1057
                                    + _drvName + ", "
1058
                                    + lyrDef.getHost() + ", "
1059
                                    + String.valueOf(lyrDef.getPort()) + ", "
1060
                                    + lyrDef.getDataBase() + ", "
1061
                                    + lyrDef.getUser() + "]. "
1062
                                    + strPassword
1063
                                    + "?");
1064
                    dlg.setVisible(true);
1065
                    clave = dlg.getPassword();
1066
                    if (clave == null)
1067
                        return;
1068
                    poolPassw.put(keyPool, clave);
1069

    
1070
                    cwp.connect(clave);
1071
                }
1072
            }
1073

    
1074
            newConn = cwp.getConnection();
1075
//            newConn.setAutoCommit(false);
1076

    
1077
            DBLayerDefinition lyrDef = new DBLayerDefinition();
1078
            if (getLyrDef() == null) {
1079
                    lyrDef.setCatalogName(catalogName);
1080
                    lyrDef.setTableName(getTableName());
1081
                    lyrDef.setFieldNames(fields);
1082
                    lyrDef.setFieldID(FIDfield);
1083
                    lyrDef.setFieldGeometry(geometryField);
1084
                    lyrDef.setWhereClause(whereClause);
1085
                    // lyrDef.setClassToInstantiate(driverClass);
1086
                    if (workingArea != null)
1087
                        lyrDef.setWorkingArea(workingArea);
1088

    
1089
                    lyrDef.setSRID_EPSG(strSRID);
1090
            } else {
1091
                    lyrDef = getLyrDef();
1092
            }
1093

    
1094
            setData(newConn, lyrDef);
1095
        } catch (ClassNotFoundException e) {
1096
                throw new ReadDriverException(this.className,e);
1097
        } catch (DBException e) {
1098
                throw new ReadDriverException(this.className,e);
1099

    
1100
                }
1101
    }
1102

    
1103
    /* (non-Javadoc)
1104
     * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#getConnection()
1105
     */
1106
    public IConnection getConnection() {
1107
        return spatialConnection;
1108
    }
1109
        /* (non-Javadoc)
1110
         * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#getConnectionString(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
1111
         */
1112
        public String getConnectionString(
1113
                    String host,
1114
                    String port,
1115
                    String dbname,
1116
                    String user,
1117
                    String pw) {
1118

    
1119
                String resp = getConnectionStringBeginning()+ ":" + host.toLowerCase();
1120

    
1121
                if (dbname.trim().length() > 0) {
1122
                        resp += ":" + port;
1123
                } else {
1124
                        resp += ":" + getDefaultPort();
1125
                }
1126

    
1127
                resp += ":" + dbname.toLowerCase();
1128
                return resp;
1129
    }
1130
        /* (non-Javadoc)
1131
         * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#getAllFields(com.iver.cit.gvsig.fmap.drivers.IConnection, java.lang.String)
1132
         */
1133
        public String[] getAllFields(IConnection conex, String tableName) throws DBException {
1134
                try {
1135
                        SeTable table = null;
1136
                        Vector tables=((ConnectionSDE)conex).getConnection().getTables(SeDefs.SE_SELECT_PRIVILEGE);
1137
                        for (int i=0;i<tables.size();i++) {
1138
                                if (tableName.equals(((SeTable)tables.get(i)).getQualifiedName())) {
1139
                                        table=(SeTable)tables.get(i);
1140
                                        break;
1141
                                }
1142
                        }
1143
                        SeRegisteredColumn[] columns=table.getColumnList();
1144
                        String[] fieldNames=new String[columns.length];
1145
                        for (int i=0; i < columns.length; i++){
1146
                                fieldNames[i]=columns[i].getName();
1147
                        }
1148
                        return fieldNames;
1149
                } catch (SeException e) {
1150
                        throw new DBException(e);
1151
                }
1152
        }
1153
        /* (non-Javadoc)
1154
         * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#getAllFieldTypeNames(com.iver.cit.gvsig.fmap.drivers.IConnection, java.lang.String)
1155
         */
1156
        public String[] getAllFieldTypeNames(IConnection conex, String tableName) throws DBException {
1157
                try {
1158
                        SeTable table = null;
1159
                        Vector tables=((ConnectionSDE)conex).getConnection().getTables(SeDefs.SE_SELECT_PRIVILEGE);
1160
                        for (int i=0;i<tables.size();i++) {
1161
                                if (tableName.equals(((SeTable)tables.get(i)).getQualifiedName())) {
1162
                                        table=(SeTable)tables.get(i);
1163
                                        break;
1164
                                }
1165
                        }
1166
                        SeRegisteredColumn[] columns=table.getColumnList();
1167
                        String[] fieldNames=new String[columns.length];
1168
                        for (int i=0; i < columns.length; i++){
1169
                                fieldNames[i]=String.valueOf(columns[i].getType());
1170
                        }
1171
                        return fieldNames;
1172
                } catch (SeException e) {
1173
                        throw new DBException(e);
1174
                }
1175
        }
1176
        /* (non-Javadoc)
1177
         * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#getIdFieldsCandidates(com.iver.cit.gvsig.fmap.drivers.IConnection, java.lang.String)
1178
         */
1179
        public String[] getIdFieldsCandidates(IConnection conn2, String tableName) throws DBException {
1180
                return getAllFields(conn2,tableName);
1181
        }
1182
        /* (non-Javadoc)
1183
         * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#getGeometryFieldsCandidates(com.iver.cit.gvsig.fmap.drivers.IConnection, java.lang.String)
1184
         */
1185
        public String[] getGeometryFieldsCandidates(IConnection conn2, String tableName) {
1186
                return new String[]{"SHAPE"};//getAllFields(conn2,tableName);
1187
        }
1188
        /* (non-Javadoc)
1189
         * @see com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver#getTableNames(com.iver.cit.gvsig.fmap.drivers.IConnection, java.lang.String)
1190
         */
1191
        public String[] getTableNames(IConnection conex, String dbName) throws DBException {
1192
                 try {
1193
                        Vector theLayers = ((ConnectionSDE)conex).getConnection().getLayers();
1194
                        TreeMap ret = new TreeMap();
1195
                        for (int i = 0; i < theLayers.size(); i++) {
1196
                                SeLayer layer = (SeLayer) theLayers.elementAt(i);
1197
                                ret.put(layer.getQualifiedName(), layer.getQualifiedName());
1198
                        }
1199
                        return (String[]) ret.keySet().toArray(new String[0]);
1200
                        } catch (SeException e) {
1201
                                throw new DBException(e);
1202
                        }
1203
                }
1204
         public String[] getTableFields(IConnection conex,String tableName) throws DBException{
1205
                        try {
1206
                                SeTable table = new SeTable(((ConnectionSDE)conex).getConnection(),tableName);
1207
                                SeRegisteredColumn[] columns=table.getColumnList();
1208
                                String[] fieldNames=new String[columns.length];
1209
                                for (int i=0; i < columns.length; i++){
1210
                                        fieldNames[i]=columns[i].getName();
1211
                                }
1212
                                return fieldNames;
1213
                        } catch (SeException e) {
1214
                                throw new DBException(e);
1215
                        }
1216
                }
1217

    
1218
}