Statistics
| Revision:

root / branches / v10 / extensions / extSDE / src / com / iver / cit / gvsig / fmap / drivers / sde / ArcSdeDriver.java @ 11254

History | View | Annotate | Download (29.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.geom.Rectangle2D;
47
import java.io.IOException;
48
import java.sql.Connection;
49
import java.sql.Types;
50
import java.util.Hashtable;
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.SeException;
56
import com.esri.sde.sdk.client.SeExtent;
57
import com.esri.sde.sdk.client.SeFilter;
58
import com.esri.sde.sdk.client.SeLayer;
59
import com.esri.sde.sdk.client.SeObjectId;
60
import com.esri.sde.sdk.client.SeQuery;
61
import com.esri.sde.sdk.client.SeQueryInfo;
62
import com.esri.sde.sdk.client.SeRow;
63
import com.esri.sde.sdk.client.SeShape;
64
import com.esri.sde.sdk.client.SeShapeFilter;
65
import com.esri.sde.sdk.client.SeSqlConstruct;
66
import com.hardcode.gdbms.engine.data.DataSourceFactory;
67
import com.hardcode.gdbms.engine.data.driver.ObjectDriver;
68
import com.hardcode.gdbms.engine.data.edition.DataWare;
69
import com.hardcode.gdbms.engine.values.Value;
70
import com.hardcode.gdbms.engine.values.ValueFactory;
71
import com.iver.cit.gvsig.fmap.DriverException;
72
import com.iver.cit.gvsig.fmap.DriverJdbcNotFoundExceptionType;
73
import com.iver.cit.gvsig.fmap.Messages;
74
import com.iver.cit.gvsig.fmap.core.FShape;
75
import com.iver.cit.gvsig.fmap.core.ICanReproject;
76
import com.iver.cit.gvsig.fmap.core.IFeature;
77
import com.iver.cit.gvsig.fmap.core.IGeometry;
78
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
79
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
80
import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator;
81
import com.iver.cit.gvsig.fmap.edition.EditionException;
82
import com.iver.cit.gvsig.fmap.edition.IWriteable;
83
import com.iver.cit.gvsig.fmap.edition.IWriter;
84
import com.iver.cit.gvsig.fmap.layers.XMLException;
85
import com.iver.utiles.XMLEntity;
86
import com.iver.utiles.swing.JPasswordDlg;
87

    
88

    
89
/**
90
 * Driver of ArcSDE.
91
 * @author Vicente Caballero Navarro
92
 */
93
public class ArcSdeDriver implements ICanReproject, IWriteable, VectorialSDEDriver, ObjectDriver{
94
    protected static Hashtable poolPassw = new Hashtable();
95
    private SeLayer layer;
96
    private SeQuery query=null;
97
    private SeQuery queryAux=null;
98
    private SeSqlConstruct sqlConstruct;
99
    private SeColumnDefinition[] colDefs;
100
    private SeRow row = null;
101
    private int numReg = -1;
102
    private Rectangle2D fullExtent = null;
103
    private Hashtable hashRelate = null;
104
    private int idSpatialColumn = -1;
105
    private String[] fields;
106
    private int[] fieldTypes;
107
    private long lastRowServed = -1;
108
    private SeConnection alphanumericConnection = null;
109
    private SeConnection spatialConnection=null;
110
    private String strEPSG;
111
    private String originalEPSG = null;
112
    private String sqlTotal;
113
    private long posActual = -1;
114
    private SeRow cachedRow = null;
115
    protected VectorialSDELayerDefinition lyrDef = null;
116
    protected Rectangle2D workingArea;
117
    protected String driverClass;
118
    protected String className;
119
    protected String catalogName;
120
        private ArcSdeWriter writer;
121

    
122
    /**
123
     * Recorre el recordset creando una tabla Hash que usaremos para relacionar
124
     * el n?mero de un registro con su identificador ?nico. Debe ser llamado
125
     * en el setData justo despu?s de crear el recorset principal
126
     */
127
    protected void doRelateID_FID() {
128
        hashRelate = new Hashtable();
129

    
130
        try {
131
            if (row == null) {
132
                System.out.println(" No rows fetched");
133

    
134
                return;
135
            }
136

    
137
            int index = 0;
138
            int fid=getLyrDef().getIdFieldID();
139
            Value value=getFieldValue(index,fid);
140

    
141
            while (value != null) {
142
                //SeShape shpVal = row.getShape(idSpatialColumn);
143
                //SeObjectId objID = shpVal.getFeatureId();
144
                    String theKey = value.toString();
145
                hashRelate.put(theKey, new Integer(index));
146
                index++;
147
                value = getFieldValue(index,fid);
148

    
149

    
150
            }
151

    
152
            numReg = index;
153
        } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
154
                        e.printStackTrace();
155
                }
156
    }
157
    /**
158
         * @return
159
         */
160
    public Rectangle2D getFullExtent() {
161
                return fullExtent;
162
        }
163
    public IGeometry getShape(int index) {
164
        SeRow row;
165

    
166
        try {
167
            row = obtainRow(index);
168
            if (row==null)
169
                    return null;
170
            SeShape spVal = row.getShape(idSpatialColumn);
171
            IGeometry geom = ArcSdeFeatureIterator.getGeometry(spVal);
172
            return geom;
173
        } catch (SeException e) {
174
            e.printStackTrace();
175
        }
176
        return null;
177
    }
178

    
179
    public IFeatureIterator getFeatureIterator(String sql)
180
        throws DriverException {
181
        return null;
182
    }
183

    
184
    public IFeatureIterator getFeatureIterator(Rectangle2D r, String strEPSG)
185
        throws DriverException {
186
        /*
187
         *   Generate a rectangular shape that will be used as a filter
188
         */
189
        try {
190
            SeShape shape = new SeShape(layer.getCoordRef());
191
            SeExtent extent=layer.getExtent();
192
            shape.generateRectangle(extent);
193

    
194
            SeShape[] shapes = new SeShape[1];
195
            shapes[0] = shape;
196

    
197
            /*
198
             *   Retrieve all the shapes that are contained within the
199
             *   rectangles envelope.
200
             */
201
            SeShapeFilter[] filters = new SeShapeFilter[1];
202
            SeShapeFilter filter = null;
203

    
204
            filter = new SeShapeFilter(layer.getName(),
205
                    layer.getSpatialColumn(), shape, SeFilter.METHOD_ENVP);
206
            filters[0] = filter;
207

    
208
            SeQuery spatialQuery = null;
209
            SeSqlConstruct sqlCons = new SeSqlConstruct(layer.getName());
210

    
211
            spatialQuery = new SeQuery(spatialConnection, fields, sqlCons);
212

    
213
            /*
214
             *   Set spatial constraints
215
             */
216
            spatialQuery.setSpatialConstraints(SeQuery.SE_OPTIMIZE, false,
217
                filters);
218

    
219
            spatialQuery.prepareQuery();
220

    
221
            spatialQuery.execute();
222

    
223
            return new ArcSdeFeatureIterator(spatialQuery);
224
        } catch (SeException e) {
225
            e.printStackTrace();
226
            return null;
227
        }
228
    }
229

    
230
    public void close() {
231
    }
232

    
233
    public void open() throws DriverException {
234
    }
235

    
236
    public int getRowIndexByFID(IFeature FID) {
237
        int resul;
238
        String strID = FID.getID();
239
        Integer rowIndex = (Integer) hashRelate.get(strID);
240

    
241
        if (rowIndex == null) {
242
            System.err.println("Error: No se ha encontrado " + strID +
243
                " dentro del Hash");
244
        }
245
        resul = rowIndex.intValue();
246
        return resul;
247
    }
248

    
249
    public String getGeometryField(String fieldName) {
250
        return layer.getSpatialColumn();
251
    }
252

    
253
    public int getShapeCount() throws IOException {
254
        return numReg;
255
    }
256

    
257
    public DriverAttributes getDriverAttributes() {
258
        return null;
259
    }
260

    
261
    public String getName() {
262
        return "gvSIG SDE driver";
263
    }
264

    
265
    /**
266
         * @return
267
         */
268
    public String[] getFields() {
269
                String[] attributes = new String[fields.length - 1];
270
                for (int i = 1; i < fields.length; i++)
271
                        attributes[i - 1] = fields[i];
272
                return attributes;
273
        }
274

    
275
    public String getTableName() {
276
        return layer.getName();
277
    }
278

    
279
    private synchronized SeRow obtainRow(long rowIndex) throws SeException {
280
       if (rowIndex != posActual) {
281
            if (rowIndex == 0) {
282
                if (query != null) {
283
                    if (query.inProgress()) {
284
                        query.close();
285
                    }
286
                    query = new SeQuery(spatialConnection, fields, sqlConstruct);
287
                    query.prepareQuery();
288
                    query.execute();
289
                }
290
                lastRowServed = -1;
291
            }
292

    
293
            if (lastRowServed == (rowIndex - 1)) {
294
                row = query.fetch();
295
                lastRowServed++;
296
            } else {
297
                if (queryAux != null && queryAux.inProgress()) {
298
                        queryAux.close();
299
                }
300

    
301
                queryAux = new SeQuery(spatialConnection, fields, sqlConstruct);
302
                SeObjectId rowID = new SeObjectId(rowIndex + 1);
303
                row = queryAux.fetchRow(layer.getName(), rowID, fields);
304
            }
305
            posActual = rowIndex;
306
            cachedRow = row;
307
        }
308

    
309
        return cachedRow;
310
    }
311

    
312
    public Value getFieldValue(long rowIndex, int fieldId)
313
        throws com.hardcode.gdbms.engine.data.driver.DriverException {
314
        SeRow row;
315
        Value val = null;
316

    
317
        try {
318
            int idFieldArcSDE = fieldId+1; // SIEMPRE CONTANDO CON
319
            // QUE NOS HAN PASADO EL PRIMER CAMPO EL DE SHAPE
320
            row = obtainRow(rowIndex);
321
            if (row==null)
322
                    return null;
323
            int dataType = colDefs[idFieldArcSDE].getType();
324

    
325
            switch (dataType) {
326
            case SeColumnDefinition.TYPE_INT16:
327
                val = ValueFactory.createValue(row.getShort(idFieldArcSDE)
328
                                                  .intValue());
329

    
330
                break;
331

    
332
            case SeColumnDefinition.TYPE_INT32:
333
            case SeColumnDefinition.TYPE_INT64:
334
                val = ValueFactory.createValue(row.getInteger(idFieldArcSDE)
335
                                                  .intValue());
336

    
337
                break;
338

    
339
            case SeColumnDefinition.TYPE_FLOAT32:
340
                val = ValueFactory.createValue(row.getFloat(idFieldArcSDE)
341
                                                  .floatValue());
342

    
343
                break;
344

    
345
            case SeColumnDefinition.TYPE_FLOAT64:
346
                val = ValueFactory.createValue(row.getDouble(idFieldArcSDE)
347
                                                  .doubleValue());
348

    
349
                break;
350

    
351
            case SeColumnDefinition.TYPE_DATE:
352
                val = ValueFactory.createValue(row.getTime(idFieldArcSDE)
353
                                                  .getTime());
354

    
355
                break;
356

    
357
            case SeColumnDefinition.TYPE_STRING:
358

    
359
                String strAux = row.getString(idFieldArcSDE);
360

    
361
                if (strAux == null) {
362
                    strAux = "";
363
                }
364

    
365
                val = ValueFactory.createValue(strAux);
366

    
367
                break;
368
            }
369

    
370
            return val;
371
        } catch (SeException e) {
372
            e.printStackTrace();
373
        }
374

    
375
        return ValueFactory.createNullValue();
376
    }
377

    
378
    public int getFieldCount()
379
        throws com.hardcode.gdbms.engine.data.driver.DriverException {
380
        return fields.length - 1;
381
    }
382

    
383
    public String getFieldName(int fieldId)
384
        throws com.hardcode.gdbms.engine.data.driver.DriverException {
385
        return fields[fieldId + 1];
386
    }
387

    
388
    public long getRowCount() {
389
        return numReg;
390
    }
391

    
392
    public int getFieldType(int i)
393
        throws com.hardcode.gdbms.engine.data.driver.DriverException {
394
        return fieldTypes[i];
395
    }
396

    
397
    /**
398
     * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#getPrimaryKeys()
399
     */
400
    public int[] getPrimaryKeys()
401
        throws com.hardcode.gdbms.engine.data.driver.DriverException {
402
        throw new UnsupportedOperationException();
403
    }
404

    
405
    /**
406
     * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#write(com.hardcode.gdbms.engine.data.edition.DataWare)
407
     */
408
    public void write(DataWare arg0)
409
        throws com.hardcode.gdbms.engine.data.driver.DriverException {
410
    }
411

    
412
    public IFeatureIterator getFeatureIterator(Rectangle2D r, String strEPSG,
413
        String[] alphaNumericFieldsNeeded) throws DriverException {
414
        /*
415
        *   Generate a rectangular shape that will be used as a filter
416
        */
417
        try {
418
            SeShape shape = new SeShape(layer.getCoordRef());
419
            SeExtent extent=layer.getExtent();
420
            shape.generateRectangle(extent);
421

    
422
            SeShape[] shapes = new SeShape[1];
423
            shapes[0] = shape;
424

    
425
            /*
426
             *   Retrieve all the shapes that are contained within the
427
             *   rectangles envelope.
428
             */
429
            SeShapeFilter[] filters = new SeShapeFilter[1];
430
            SeShapeFilter filter = null;
431

    
432
            filter = new SeShapeFilter(layer.getName(),
433
                    layer.getSpatialColumn(), shape, SeFilter.METHOD_ENVP);
434
            filters[0] = filter;
435

    
436
            SeQuery spatialQuery = null;
437
            SeSqlConstruct sqlCons = new SeSqlConstruct(layer.getName());
438

    
439
            spatialQuery = new SeQuery(alphanumericConnection, fields, sqlCons);
440

    
441
            /*
442
             *   Set spatial constraints
443
             */
444
            spatialQuery.setSpatialConstraints(SeQuery.SE_OPTIMIZE, false,
445
                filters);
446

    
447
            spatialQuery.prepareQuery();
448

    
449
            spatialQuery.execute();
450

    
451
            return new ArcSdeFeatureIterator(spatialQuery);
452
        } catch (SeException e) {
453
            e.printStackTrace();
454

    
455
            return null;
456
        }
457
    }
458

    
459
    public boolean isWritable() {
460
        return false;
461
    }
462
    public void setData(Connection connection, DBLayerDefinition lyrDef) {
463
        setLyrDef(lyrDef);
464
        // Conexi?n:
465
        VectorialSDELayerDefinition sdeDef = (VectorialSDELayerDefinition) lyrDef;
466
        String server = sdeDef.getHost();
467
        int instance = Integer.parseInt(sdeDef.getPort());
468
        String database = sdeDef.getSchema();
469
        String user = sdeDef.getUser();
470
        String password = sdeDef.getPassword();
471
        String[] cols = sdeDef.getFieldNames();
472
        String tableName = sdeDef.getTableName();
473
        try {
474
            alphanumericConnection = new SeConnection(server, instance, database, user, password);
475
            spatialConnection = new SeConnection(server, instance, database, user, password);
476
        } catch (SeException e) {
477
            e.printStackTrace();
478

    
479
            return;
480
        }
481
        // Fetching data
482
        String layerName = tableName;
483
        SeObjectId layerID = null;
484
        String strSpatialColumn = "";
485

    
486
        try {
487
            Vector theLayers = spatialConnection.getLayers();
488

    
489
            for (int i = 0; i < theLayers.size(); i++) {
490
                SeLayer layer = (SeLayer) theLayers.elementAt(i);
491

    
492
                if (layer.getName().compareToIgnoreCase(layerName) == 0) {
493
                    ;
494
                }
495

    
496
                layerID = layer.getID();
497
                strSpatialColumn = layer.getSpatialColumn();
498
            }
499

    
500
            if (layerID == null) {
501
                System.err.println("Capa no encontrada");
502

    
503
                return;
504
            }
505

    
506
            // layerName = layer.getName();
507
            layer = new SeLayer(spatialConnection, layerName, strSpatialColumn);
508

    
509
            //TODO aqu? se puede saber la proyecci?n
510
            //layer.getCoordRef().getSrid();
511

    
512
//            if ((cols != null) && (cols.length != 0)) {
513
//                if (!cols[0].equals(lyrDef.getFieldGeometry())) {
514
//                    this.fields = new String[cols.length + 1];
515
//                    this.fields[0] = lyrDef.getFieldGeometry();
516
//
517
//                    for (int i = 1; i < fields.length; i++) {
518
//                        fields[i] = cols[i - 1];
519
//                    }
520
//                } else {
521
//                    fields = cols;
522
//                }
523
//            } else {
524
//                SeSqlConstruct sqlConstruct = new SeSqlConstruct(tableName);
525
//                sqlTotal = sqlConstruct.getWhere();
526
//
527
//                SeTable table1 = new SeTable(conn, tableName);
528
//
529
//                /*
530
//                 *   Get the table's column definition.
531
//                 */
532
//                SeColumnDefinition[] tableDef = table1.describe();
533
//                this.fields = new String[tableDef.length];
534
//
535
//                /*
536
//                 *   Store the names of all the table's columns in the
537
//                 *   String array cols. This array specifies the columns
538
//                 *   to be retrieved from the database.
539
//                 */
540
//                int idField = 1;
541
//
542
//                for (int i = 0; i < tableDef.length; i++) {
543
//                    if (tableDef[i].getType() == SeColumnDefinition.TYPE_SHAPE) {
544
//                        this.fields[0] = tableDef[i].getName();
545
//                    } else {
546
//                        this.fields[idField] = tableDef[i].getName();
547
//                        idField++;
548
//                    }
549
//                }
550
//
551
//                lyrDef.setFieldNames(fields);
552
//            }
553
            fields=cols;
554
            sqlConstruct = new SeSqlConstruct(layerName);
555

    
556
            //      Create a query stream between the client and server
557
            query = new SeQuery(spatialConnection, fields, sqlConstruct);
558
            query.prepareQuery();
559
            query.execute();
560
            row = query.fetch();
561

    
562
            if (row == null) {
563
                System.out.println("La tabla " + getName() +
564
                    " no tiene registros");
565

    
566
                return;
567
            }
568

    
569
            colDefs = row.getColumns();
570
            lyrDef.setShapeType(obtainShapeType(row.getShape(0).getType()));
571
            fieldTypes = new int[colDefs.length - 1];
572

    
573
            for (int colNum = 0; colNum < colDefs.length; colNum++) {
574
                SeColumnDefinition colDef = colDefs[colNum];
575
                int dataType = colDef.getType();
576

    
577
                switch (dataType) {
578
                case SeColumnDefinition.TYPE_SHAPE:
579

    
580
                    if (colNum != 0) {
581
                        System.err.println(
582
                            "Por favor, el campo de shapes deber ser el primero");
583

    
584
                        return;
585
                    }
586

    
587
                    idSpatialColumn = colNum;
588

    
589
                    break;
590

    
591
                case SeColumnDefinition.TYPE_INT16:
592
                case SeColumnDefinition.TYPE_INT32:
593
                case SeColumnDefinition.TYPE_INT64:
594
                    fieldTypes[colNum - 1] = Types.INTEGER;
595

    
596
                    break;
597

    
598
                case SeColumnDefinition.TYPE_FLOAT32:
599
                    fieldTypes[colNum - 1] = Types.FLOAT;
600

    
601
                    break;
602

    
603
                case SeColumnDefinition.TYPE_FLOAT64:
604
                    fieldTypes[colNum - 1] = Types.DOUBLE;
605

    
606
                    break;
607

    
608
                case SeColumnDefinition.TYPE_DATE:
609
                    fieldTypes[colNum - 1] = Types.DATE;
610

    
611
                    break;
612

    
613
                default:
614
                    fieldTypes[colNum - 1] = Types.VARCHAR;
615

    
616
                    break;
617
                }
618
            }
619
            fields=cols;
620
            SeQuery extentQuery = new SeQuery(spatialConnection, fields, sqlConstruct);
621
            SeQueryInfo queryInfo = new SeQueryInfo();
622
            queryInfo.setConstruct(sqlConstruct);
623

    
624
            SeExtent seExtent = extentQuery.calculateLayerExtent(queryInfo);
625
            fullExtent = new Rectangle2D.Double(seExtent.getMinX(),
626
                    seExtent.getMinY(),
627
                    seExtent.getMaxX() - seExtent.getMinX(),
628
                    seExtent.getMaxY() - seExtent.getMinY());
629
            extentQuery.close();
630

    
631
            doRelateID_FID();
632
        } catch (SeException e) {
633
            e.printStackTrace();
634
        }
635
    }
636

    
637
    private int obtainShapeType(int type) {
638
        int shapeType = -1;
639

    
640
        switch (type) {
641
        case SeLayer.TYPE_POINT:
642
            shapeType = FShape.POINT;
643

    
644
            break;
645

    
646
        case SeLayer.TYPE_LINE:
647
        case SeLayer.TYPE_SIMPLE_LINE:
648
        case SeLayer.TYPE_MULTI_LINE:
649
        case SeLayer.TYPE_MULTI_SIMPLE_LINE:
650
            shapeType = FShape.LINE;
651

    
652
            break;
653

    
654
        case SeLayer.TYPE_POLYGON:
655
        case SeLayer.TYPE_MULTI_POLYGON:
656
            shapeType = FShape.POLYGON;
657

    
658
            break;
659

    
660
        default:
661
            shapeType = FShape.MULTI;
662
        }
663

    
664
        return shapeType;
665
    }
666

    
667
    public String getCompleteWhere() {
668
        return null;
669
    }
670

    
671
    public String getConnectionStringBeginning() {
672
        return "";
673
    }
674

    
675
    public int getDefaultPort() {
676
        return 5151;
677
    }
678

    
679
    public String getSourceProjection() {
680
        return originalEPSG;
681
    }
682

    
683
    public String getDestProjection() {
684
        return strEPSG;
685
    }
686

    
687
    public void setDestProjection(String toEPSG) {
688
        this.strEPSG = toEPSG;
689
    }
690

    
691
    public boolean canReproject(String toEPSGdestinyProjection) {
692
        //                 TODO POR AHORA, REPROYECTA SIEMPRE gvSIG.
693
        return false;
694
    }
695

    
696
    public IWriter getWriter() {
697
             if (writer == null) {
698
             writer = new ArcSdeWriter();
699
             writer.setDriver(this);
700
             writer.setSeLayer(layer);
701
             try {
702
                 writer.initialize(getLyrDef());
703
             }
704
             catch (EditionException e) {
705

    
706
             }
707
         }
708

    
709
         return writer;
710
    }
711

    
712
    /**
713
         * @return
714
         */
715
    public String getSqlTotal() {
716
                return sqlTotal;
717
        }
718

    
719
    public XMLEntity getXMLEntity() {
720
        VectorialSDELayerDefinition sdeDef = (VectorialSDELayerDefinition) getLyrDef();
721
        XMLEntity xml = new XMLEntity();
722
        xml.putProperty("className", this.getClass().getName());
723
        xml.putProperty("driverclass", this.getClass().getName());
724
        xml.putProperty("catalog", sdeDef.getCatalogName());
725

    
726
        // TODO: NO DEBEMOS GUARDAR EL NOMBRE DE USUARIO Y CONTRASE?A
727
        // AQUI. Hay que utilizar un pool de conexiones
728
        // y pedir al usuario que conecte a la base de datos
729
        // en la primera capa. En el resto, usar la conexi?n
730
        // creada con anterioridad.
731
        String userName = sdeDef.getUser();
732
        if (userName != null) {
733
            int aux = userName.indexOf("@");
734

    
735
            if (aux != -1) {
736
                userName = userName.substring(0, aux);
737
            }
738
        }
739

    
740
        xml.putProperty("username", userName);
741

    
742
        xml.putProperty("tablename", getTableName());
743
        xml.putProperty("fields", fields);
744
        xml.putProperty("ID", sdeDef.getFieldID());
745
        xml.putProperty("THE_GEOM", sdeDef.getFieldGeometry());
746
        xml.putProperty("whereclause", getWhereClause());
747
        xml.putProperty("SRID", sdeDef.getSRID_EPSG());
748

    
749
        xml.putProperty("host", sdeDef.getHost());
750
        xml.putProperty("port", sdeDef.getPort());
751
        xml.putProperty("dbName", sdeDef.getSchema());
752
        xml.putProperty("connName", sdeDef.getConnectionName());
753

    
754
        xml.putProperty("typeShape",sdeDef.getShapeType());
755

    
756
        if (getWorkingArea() != null) {
757
            xml.putProperty("minXworkArea", getWorkingArea().getMinX());
758
            xml.putProperty("minYworkArea", getWorkingArea().getMinY());
759
            xml.putProperty("HworkArea", getWorkingArea().getHeight());
760
            xml.putProperty("WworkArea", getWorkingArea().getWidth());
761
        }
762

    
763
        return xml;
764
    }
765

    
766
    public void setXMLEntity(XMLEntity xml) throws XMLException {
767
        className = xml.getStringProperty("className");
768
        catalogName = xml.getStringProperty("catalog");
769
        lyrDef = new ArcSdeLayerDefinition();
770

    
771
        if (xml.contains("username")) {
772
            lyrDef.setUser(xml.getStringProperty("username"));
773
        }
774

    
775
        driverClass = xml.getStringProperty("driverclass");
776
        lyrDef.setTableName(xml.getStringProperty("tablename"));
777
        fields = xml.getStringArrayProperty("fields");
778
        lyrDef.setFieldNames(fields);
779
        lyrDef.setFieldID(xml.getStringProperty("ID"));
780
        lyrDef.setFieldGeometry(xml.getStringProperty("THE_GEOM"));
781
        lyrDef.setWhereClause(xml.getStringProperty("whereclause"));
782
        lyrDef.setSRID_EPSG(xml.getStringProperty("SRID"));
783

    
784
        if (xml.contains("host")) {
785
            lyrDef.setHost(xml.getStringProperty("host"));
786
            lyrDef.setPort(xml.getStringProperty("port"));
787
            lyrDef.setSchema(xml.getStringProperty("dbName"));
788
            lyrDef.setConnectionName(xml.getStringProperty("connName"));
789
        }
790
        lyrDef.setShapeType(xml.getIntProperty("typeShape"));
791
        if (xml.contains("minXworkArea")) {
792
            double x = xml.getDoubleProperty("minXworkArea");
793
            double y = xml.getDoubleProperty("minYworkArea");
794
            double H = xml.getDoubleProperty("HworkArea");
795
            double W = xml.getDoubleProperty("WworkArea");
796
            workingArea = new Rectangle2D.Double(x, y, W, H);
797
        }
798

    
799
        lyrDef.setCatalogName(catalogName);
800
        lyrDef.setFieldNames(fields);
801

    
802
        if (workingArea != null) {
803
            lyrDef.setWorkingArea(workingArea);
804
        }
805

    
806
        setLyrDef(lyrDef);
807
    }
808

    
809
    public int getFieldWidth(int fieldId) {
810
        return colDefs[fieldId].getSize();
811
    }
812

    
813
    public void setLyrDef(DBLayerDefinition lyrDef) {
814
        this.lyrDef = (VectorialSDELayerDefinition) lyrDef;
815
    }
816

    
817
    /**
818
         * @see  com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver#setWorkingArea(java.awt.geom.Rectangle2D)
819
         */
820
    public void setWorkingArea(Rectangle2D rect) {
821
                this.workingArea = rect;
822
        }
823

    
824
    /**
825
         * @see  com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver#getWorkingArea()
826
         */
827
    public Rectangle2D getWorkingArea() {
828
                return workingArea;
829
        }
830

    
831
    /**
832
     * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getShapeType()
833
     */
834
    public int getShapeType() {
835
        return lyrDef.getShapeType();
836
    }
837

    
838
    /* (non-Javadoc)
839
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getWhereClause()
840
     */
841
    public String getWhereClause() {
842
        if (lyrDef.getWhereClause() == null) {
843
            return "";
844
        }
845

    
846
        return lyrDef.getWhereClause().toUpperCase();
847
    }
848

    
849
    /**
850
         * @return
851
         */
852
    public DBLayerDefinition getLyrDef() {
853
            // Esto hace saltar un error.
854
//            if (this.spatialConnection != null){
855
//                    lyrDef.setSeConnection();
856
//            }
857
        return lyrDef;
858
    }
859

    
860
    /**
861
     * Empty method called when the layer is going to be removed from the view.
862
     * Subclasses can overwrite it if needed.
863
     */
864
    public void remove() {
865
    }
866

    
867
    /* (non-Javadoc)
868
    * @see com.iver.cit.gvsig.fmap.drivers.VectorialDriver#reLoad()
869
    */
870
    public void reload() throws IOException {
871
            try {
872
                        load();
873
                } catch (DriverException e) {
874
                        e.printStackTrace();
875
                }
876
               //setData(null, lyrDef);
877
    }
878

    
879
    public void setDataSourceFactory(DataSourceFactory dsf) {
880
        // TODO Auto-generated method stub
881
    }
882

    
883
    public void load() throws DriverException {
884
        try {
885
            if (driverClass != null) {
886
                Class.forName(driverClass);
887
            }
888

    
889
            String _drvName = getName();
890

    
891
            String keyPool = _drvName.toLowerCase() + "_" +
892
                lyrDef.getHost().toLowerCase() + "_" + lyrDef.getPort() + "_" +
893
                lyrDef.getSchema().toLowerCase() + "_" +
894
                lyrDef.getUser().toLowerCase();
895

    
896
            String clave = null;
897

    
898
            if (poolPassw.containsKey(keyPool)) {
899
                clave = (String) poolPassw.get(keyPool);
900

    
901
                lyrDef.setPassword(clave);
902
            } else {
903
                JPasswordDlg dlg = new JPasswordDlg();
904
                String strMessage = Messages.getString("conectar_sde");
905
                String strPassword = Messages.getString("password");
906
                dlg.setMessage(strMessage + " [" + _drvName + ", " +
907
                    lyrDef.getHost() + ", " + lyrDef.getPort() + ", " +
908
                    lyrDef.getSchema() + ", " + lyrDef.getUser() + "]. " +
909
                    strPassword + "?");
910
                dlg.show();
911
                clave = dlg.getPassword();
912

    
913
                if (clave == null) {
914
                    return;
915
                }
916

    
917
                poolPassw.put(keyPool, clave);
918
                lyrDef.setPassword(clave);
919

    
920
            }
921

    
922
            DBLayerDefinition lyrDef = new DBLayerDefinition();
923

    
924
            if (getLyrDef() == null) {
925
                lyrDef.setCatalogName(catalogName);
926
                lyrDef.setFieldNames(fields);
927
                if (workingArea != null) {
928
                    lyrDef.setWorkingArea(workingArea);
929
                }
930
            } else {
931
                lyrDef = getLyrDef();
932
            }
933

    
934
            setData(null, lyrDef);
935
        } catch (ClassNotFoundException e) {
936
            DriverJdbcNotFoundExceptionType type = new DriverJdbcNotFoundExceptionType();
937
            type.setDriverJdbcClassName(driverClass);
938
            type.setLayerName(this.getLyrDef().getTableName());
939
            throw new DriverException("Driver SDE no encontrado", e, type);
940
        }
941
    }
942

    
943
    public Object getConnection() {
944
        return spatialConnection;
945
    }
946
        public String getConnectionString(
947
                    String host,
948
                    String port,
949
                    String dbname,
950
                    String user,
951
                    String pw) {
952

    
953
                String resp = getConnectionStringBeginning() + "//" + host.toLowerCase();
954

    
955
                if (dbname.trim().length() > 0) {
956
                        resp += ":" + port;
957
                } else {
958
                        resp += ":" + getDefaultPort();
959
                }
960

    
961
                resp += "/" + dbname.toLowerCase();
962
                return resp;
963
    }
964

    
965
}