Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / layers / FLyrVect.java @ 5057

History | View | Annotate | Download (30.9 KB)

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

    
43
import java.awt.Graphics2D;
44
import java.awt.Point;
45
import java.awt.geom.Point2D;
46
import java.awt.geom.Rectangle2D;
47
import java.awt.image.BufferedImage;
48
import java.io.File;
49
import java.io.IOException;
50

    
51
import org.apache.log4j.Logger;
52
import org.cresques.cts.ICoordTrans;
53

    
54
import com.hardcode.driverManager.DriverLoadException;
55
import com.hardcode.gdbms.engine.data.DataSourceFactory;
56
import com.hardcode.gdbms.engine.data.NoSuchTableException;
57
import com.hardcode.gdbms.engine.instruction.FieldNotFoundException;
58
import com.iver.cit.gvsig.fmap.DriverException;
59
import com.iver.cit.gvsig.fmap.ViewPort;
60
import com.iver.cit.gvsig.fmap.core.IGeometry;
61
import com.iver.cit.gvsig.fmap.drivers.BoundedShapes;
62
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
63
import com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver;
64
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
65
import com.iver.cit.gvsig.fmap.edition.AnnotationEditableAdapter;
66
import com.iver.cit.gvsig.fmap.edition.EditionException;
67
import com.iver.cit.gvsig.fmap.edition.VectorialEditableAdapter;
68
import com.iver.cit.gvsig.fmap.edition.VectorialEditableDBAdapter;
69
import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData;
70
import com.iver.cit.gvsig.fmap.layers.layerOperations.ClassifiableVectorial;
71
import com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint;
72
import com.iver.cit.gvsig.fmap.layers.layerOperations.Labelable;
73
import com.iver.cit.gvsig.fmap.layers.layerOperations.RandomVectorialData;
74
import com.iver.cit.gvsig.fmap.layers.layerOperations.SingleLayer;
75
import com.iver.cit.gvsig.fmap.layers.layerOperations.VectorialData;
76
import com.iver.cit.gvsig.fmap.layers.layerOperations.VectorialXMLItem;
77
import com.iver.cit.gvsig.fmap.operations.Cancellable;
78
import com.iver.cit.gvsig.fmap.operations.CancellableMonitorable;
79
import com.iver.cit.gvsig.fmap.operations.strategies.FeatureVisitor;
80
import com.iver.cit.gvsig.fmap.operations.strategies.Strategy;
81
import com.iver.cit.gvsig.fmap.operations.strategies.StrategyManager;
82
import com.iver.cit.gvsig.fmap.operations.strategies.VisitException;
83
import com.iver.cit.gvsig.fmap.rendering.Legend;
84
import com.iver.cit.gvsig.fmap.rendering.LegendChangedEvent;
85
import com.iver.cit.gvsig.fmap.rendering.LegendFactory;
86
import com.iver.cit.gvsig.fmap.rendering.SingleSymbolLegend;
87
import com.iver.cit.gvsig.fmap.rendering.VectorialLegend;
88
import com.iver.cit.gvsig.fmap.spatialindex.IPersistentSpatialIndex;
89
import com.iver.cit.gvsig.fmap.spatialindex.ISpatialIndex;
90
import com.iver.cit.gvsig.fmap.spatialindex.QuadtreeJts;
91
import com.iver.cit.gvsig.fmap.spatialindex.RTreeSptLib;
92
import com.iver.cit.gvsig.fmap.spatialindex.SpatialIndexException;
93
import com.iver.utiles.FileUtils;
94
import com.iver.utiles.IPersistance;
95
import com.iver.utiles.PostProcessSupport;
96
import com.iver.utiles.XMLEntity;
97
import com.iver.utiles.xmlViewer.XMLItem;
98
import com.vividsolutions.jts.index.SpatialIndex;
99

    
100
/**
101
 * Capa b?sica Vectorial.
102
 *
103
 * @author Fernando Gonz?lez Cort?s
104
 */
105

    
106
//TODO Cuando no sea para pruebas debe no ser public
107
public class FLyrVect extends FLyrDefault implements Labelable, ClassifiableVectorial, SingleLayer, VectorialData,
108
        RandomVectorialData,AlphanumericData, InfoByPoint {
109
        private static Logger logger = Logger.getLogger(FLyrVect.class.getName());
110

    
111
        /** Leyenda de la capa vectorial */
112
        private VectorialLegend legend;
113
        private int typeShape = -1;
114

    
115
        private LayerChangeSupport layerChangeSupport = new LayerChangeSupport();
116
        private ReadableVectorial source;
117
        private SelectableDataSource sds;
118
        private SelectionSupport selectionSupport = new SelectionSupport();
119

    
120
    
121
        //protected SpatialIndex spatialIndex = null;
122
        /**
123
         * An implementation of gvSIG spatial index
124
         */
125
    protected ISpatialIndex spatialIndex = null;
126
        
127
    private boolean bHasJoin = false;
128

    
129
        /**
130
         * A?ade un SelectionListener a la lista de listeners.
131
         *
132
         * @param listener SelectionListener.
133
         */
134
        /*public void addSelectionListener(SelectionListener listener) {
135
                try {
136
                        getRecordset().addSelectionListener(listener);
137
                } catch (DriverException e) {
138
                        // TODO Auto-generated catch block
139
                        e.printStackTrace();
140
                }
141
        }
142
*/
143
        /**
144
         * Borra un selectionListener de la lista de listeners.
145
         *
146
         * @param listener SelectionListener
147
         */
148
        /*public void removeSelectionListener(SelectionListener listener) {
149
                try {
150
                        getRecordset().removeSelectionListener(listener);
151
                } catch (DriverException e) {
152
                        // TODO Auto-generated catch block
153
                        e.printStackTrace();
154
                }
155
        }
156
*/
157
        /**
158
         * Cuando ocurre un evento de cambio en la selecci?n, ?ste puede ser uno de
159
         * una gran cantidad de eventos. Con el fin de no propagar todos estos
160
         * eventos, se realiza la propagaci?n de manera manual al final de la
161
         * "r?faga" de eventos
162
         */
163
        /*public void fireSelectionEvents() {
164
                try {
165
                        getRecordset().fireSelectionEvents();
166
                } catch (DriverException e) {
167
                        // TODO Auto-generated catch block
168
                        e.printStackTrace();
169
                }
170
        }
171
*/
172
        /**
173
         * Devuelve el VectorialAdapater de la capa.
174
         *
175
         * @return VectorialAdapter.
176
         */
177
        public ReadableVectorial getSource() {
178
                return source;
179
        }
180
        
181
        /**
182
         * If we use a persistent spatial index associated with this layer,
183
         * and the index is not intrisic to the layer (for example spatial databases)
184
         * this method looks for existent spatial index, and loads it.
185
         *
186
         */
187
        private void loadSpatialIndex(){
188
                ReadableVectorial source = getSource();
189
                if(! (source instanceof VectorialFileAdapter)){
190
                        //we are not interested in db adapters
191
                        return;
192
                }
193
                VectorialDriver driver = source.getDriver();
194
                if(!(driver instanceof BoundedShapes)){
195
                        //we dont spatially index layers that are not bounded
196
                        return;
197
                }
198
                File file = ((VectorialFileAdapter)source).getFile();
199
                String  fileName = FileUtils.getFileWithoutExtension(file);
200
                File sptFile = new File(fileName+".dat");
201
                if(! sptFile.exists() || (! (sptFile.length() > 0))){
202
                        //before to exit, look for it in temp path
203
                        
204
                        String tempPath = System.getProperty("java.io.tmpdir");
205
                        fileName = tempPath + File.separator + sptFile.getName();
206
                        sptFile = new File(fileName);
207
//                        it doesnt exists, must to create
208
                        if(! sptFile.exists() || (! (sptFile.length() > 0))){
209
                                return;
210
                        }//if
211
                }//if
212
                try {
213
                        spatialIndex = new RTreeSptLib(false, FileUtils.getFileWithoutExtension(sptFile));
214
                } catch (SpatialIndexException e) {
215
                        spatialIndex = null;
216
                        e.printStackTrace();
217
                        return;
218
                }
219
        }
220
        
221
        /**
222
         * Checks if it has associated an external spatial index
223
         * @return
224
         */
225
        public boolean isExternallySpatiallyIndexed(){
226
                ReadableVectorial source = getSource();
227
                if(! (source instanceof VectorialFileAdapter)){
228
                        //we are not interested in db adapters
229
                        return false;
230
                }
231
                File file = ((VectorialFileAdapter)source).getFile();
232
                String  fileName = FileUtils.getFileWithoutExtension(file);
233
                File sptFile = new File(fileName+".dat");
234
                if(! sptFile.exists() || (! (sptFile.length() > 0))){
235
                        //before to exit, look for it in temp path
236
                        //it doesnt exists, must to create
237
                        String tempPath = System.getProperty("java.io.tmpdir");
238
                        fileName = tempPath + File.separator + sptFile.getName();
239
                        sptFile = new File(fileName);
240
                        if(! sptFile.exists() || (! (sptFile.length() > 0))){
241
                                return false;
242
                        }//if
243
                }//if
244
                return true;
245
        }
246

    
247
        /**
248
         * Inserta el VectorialAdapter a la capa.
249
         *
250
         * @param va VectorialAdapter.
251
         */
252
        public void setSource(ReadableVectorial rv) {
253
                source = rv;
254
                //azabala: we check if this layer could have a file spatial index
255
                //, if it has, and load it if it exists
256
                loadSpatialIndex();
257
        }
258

    
259
        /**
260
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#getFullExtent()
261
         */
262
        public Rectangle2D getFullExtent() throws DriverException {
263
                try {
264
                        Rectangle2D rAux;
265
                        logger.debug("source.start()");
266
                        source.start();
267
                        rAux = source.getFullExtent();
268
                        logger.debug("source.stop()");
269
                        source.stop();
270

    
271
                        // Si existe reproyecci?n, reproyectar el extent
272
                        ICoordTrans ct = getCoordTrans();
273

    
274
                        if (ct != null) {
275
                                Point2D pt1 = new Point2D.Double(rAux.getMinX(), rAux.getMinY());
276
                                Point2D pt2 = new Point2D.Double(rAux.getMaxX(), rAux.getMaxY());
277
                                pt1 = ct.convert(pt1, null);
278
                                pt2 = ct.convert(pt2, null);
279
                                rAux = new Rectangle2D.Double();
280
                                rAux.setFrameFromDiagonal(pt1, pt2);
281
                        }
282

    
283
                        return rAux;
284
                } catch (DriverIOException e) {
285
                        throw new DriverException(e);
286
                }
287
        }
288

    
289
        /**
290
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#draw(java.awt.image.BufferedImage,
291
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort)
292
         */
293
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
294
                Cancellable cancel,double scale) throws DriverException {
295

    
296
                if (isWithinScale(scale)){
297
            // Las que solo tienen etiquetado sin pintar el shape,
298
            // no pasamos por ellas
299
            boolean bDrawShapes = true;
300
            if (legend instanceof SingleSymbolLegend)
301
            {
302
                if (legend.getDefaultSymbol().isShapeVisible() == false)
303
                    bDrawShapes = false;
304
            }
305
            if (bDrawShapes)
306
            {
307
                Strategy strategy = StrategyManager.getStrategy(this);
308
                try{
309
                strategy.draw(image, g, viewPort, cancel);
310
                }catch (DriverException e) {
311
                                        this.setVisible(false);
312
                                        this.setActive(false);
313
                                        throw e;
314
                                }
315
            }
316
                    if (getVirtualLayers() != null) {
317
                            getVirtualLayers().draw(image, g, viewPort, cancel,scale);
318
                    }
319

    
320
                    if (getLayerText() != null) {
321
                            getLayerText().draw(image, g, viewPort, cancel,scale);
322
                    }
323
                }
324
        }
325

    
326
        /**
327
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D,
328
         *                 com.iver.cit.gvsig.fmap.ViewPort,
329
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
330
         */
331
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale)
332
                throws DriverException {
333
                if (isVisible() && isWithinScale(scale)){
334
                Strategy strategy = StrategyManager.getStrategy(this);
335

    
336
                strategy.print(g, viewPort, cancel);
337

    
338
                if (getLayerText() != null) {
339
                        getLayerText().draw(null, g, viewPort, cancel,scale);
340
                }
341
                }
342
        }
343

    
344
        /**
345
         * @see com.iver.cit.gvsig.fmap.layers.VectorialOperations#createLabelLayer(int)
346
         */
347
        // public FLayer createLabelLayer(int fieldId) {
348
    public FLayer createLabelLayer(SelectableDataSource ds) {
349
                FLyrText layerText = null;
350
        try {
351
            layerText = new FLyrText();
352
                        layerText.setLegend((VectorialLegend) getLegend());
353
            layerText.createLabels(this);
354
                } catch (FieldNotFoundException e1) {
355
                        // TODO Auto-generated catch block
356
                        e1.printStackTrace();
357
                } catch (DriverException e1) {
358
                        // TODO Auto-generated catch block
359
                        e1.printStackTrace();
360
        }
361

    
362

    
363
                setLayerText(layerText);
364
                layerText.setCoordTrans(getCoordTrans());
365
                return layerText;
366
        }
367

    
368
        /**
369
         * @see com.iver.cit.gvsig.fmap.layers.VectorialOperations#removeLabels()
370
         */
371
        public void removeLabels() {
372
                setLayerText(null);
373
        }
374

    
375
    /* (non-Javadoc)
376
     * @see com.iver.cit.gvsig.fmap.layers.layerOperations.RandomVectorialData#deleteSpatialIndex()
377
     */
378
    public void deleteSpatialIndex()
379
    {
380
        spatialIndex = null;
381
    }
382
    
383
   /**
384
    * Creates an spatial index associated to this layers.
385
    * 
386
    * @param cancelMonitor instance of CancellableMonitorable that allows
387
    * to monitor progress of spatial index creation, and cancel the process
388
    */ 
389
    public void createSpatialIndex(CancellableMonitorable cancelMonitor){
390
             // FJP: ESTO HABR? QUE CAMBIARLO. PARA LAS CAPAS SECUENCIALES, TENDREMOS
391
        // QUE ACCEDER CON UN WHILE NEXT. (O mejorar lo de los FeatureVisitor
392
        // para que acepten recorrer sin geometria, solo con rectangulos.
393
            
394
//            //If this vectorial layer is based in a spatial database, the spatial
395
                //index is already implicit. We only will index file drivers
396
            ReadableVectorial va = getSource();
397
                if(!(va instanceof VectorialFileAdapter)){
398
                        return;
399
                }
400
                if(!(va.getDriver() instanceof BoundedShapes)){
401
                        return;
402
                }
403
                File file = ((VectorialFileAdapter)va).getFile();
404
                String  fileName = FileUtils.getFileWithoutExtension(file);
405
        try {
406
                        spatialIndex = new RTreeSptLib(true, fileName);
407
                } catch (SpatialIndexException e1) {
408
                        //Probably we dont have writing permissions
409
                        String directoryName = System.getProperty("java.io.tmpdir");
410
                        File newFile = new File(file.getName());
411
                        String newFileName = newFile.getName();
412
                        try {
413
                                spatialIndex = new RTreeSptLib(true, directoryName + 
414
                                                                File.pathSeparator + 
415
                                                                                newFileName);
416
                        } catch (SpatialIndexException e) {
417
                                //si no lo podemos crear en fichero, lo creamos en memoria
418
                                spatialIndex = new QuadtreeJts();
419
                        }
420
                }//try
421
                
422
        ICoordTrans ct = getCoordTrans();
423
        BoundedShapes shapeBounds = (BoundedShapes) va.getDriver();
424
        try {
425
            va.start();
426

    
427
            for (int i=0; i < va.getShapeCount(); i++)
428
            {
429
                    if(cancelMonitor != null){
430
                            if(cancelMonitor.isCanceled())
431
                                    return;
432
                            cancelMonitor.reportStep();
433
                    }
434
                Rectangle2D r = shapeBounds.getShapeBounds(i);
435
                if (ct != null) {
436
                    r = ct.convert(r);
437
                }
438
                spatialIndex.insert(r, i);
439
                if(spatialIndex instanceof IPersistentSpatialIndex){
440
                        if((i % 50) == 0){//flush spatial index in buckets of 50
441
                                ((IPersistentSpatialIndex)spatialIndex).flush();
442
                        }
443
                }
444
            } // for
445
            va.stop();
446
            if(spatialIndex instanceof IPersistentSpatialIndex)
447
                    ((IPersistentSpatialIndex) spatialIndex).flush();
448
        } catch (DriverIOException e) {
449
            // TODO Auto-generated catch block
450
            e.printStackTrace();
451
        } catch (IOException e) {
452
            // TODO Auto-generated catch block
453
            e.printStackTrace();
454
        }
455
    }
456
    
457
        /* (non-Javadoc)
458
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.RandomVectorialData#createIndex()
459
         */
460
        public void createSpatialIndex() {
461
                createSpatialIndex(null);
462
        }
463

    
464
        /**
465
         * @see com.iver.cit.gvsig.fmap.layers.VectorialOperations#process(com.iver.cit.gvsig.fmap.operations.strategies.FeatureVisitor,
466
         *                 FBitSet)
467
         */
468
        public void process(FeatureVisitor visitor, FBitSet subset)
469
                throws DriverException, VisitException {
470
                Strategy s = StrategyManager.getStrategy(this);
471
                s.process(visitor, subset);
472
        }
473

    
474
        /**
475
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.VectorialData#process(com.iver.cit.gvsig.fmap.operations.strategies.FeatureVisitor)
476
         */
477
        public void process(FeatureVisitor visitor)
478
                throws DriverException, VisitException {
479
                Strategy s = StrategyManager.getStrategy(this);
480
                s.process(visitor);
481
        }
482

    
483
        /**
484
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.VectorialData#process(com.iver.cit.gvsig.fmap.operations.strategies.FeatureVisitor, Rectangle2D)
485
         */
486
        public void process(FeatureVisitor visitor, Rectangle2D rect)
487
                throws DriverException, VisitException {
488
                Strategy s = StrategyManager.getStrategy(this);
489
                s.process(visitor, rect);
490
        }
491

    
492

    
493

    
494
        /**
495
         * @see com.iver.cit.gvsig.fmap.layers.CommonOperations#setSelection(com.iver.cit.gvsig.fmap.operations.selection.VectorialSubSet)
496
         */
497
        /*public void setSelection(FBitSet selection) {
498
                try {
499
                        getRecordset().setSelection(selection);
500
                } catch (DriverException e) {
501
                        // TODO Auto-generated catch block
502
                        e.printStackTrace();
503
                }
504
                fireSelectionEvents();
505
        }
506
*/
507
        /**
508
         * @see com.iver.cit.gvsig.fmap.layers.CommonOperations#isSelected(int)
509
         */
510
        /*public boolean isSelected(int index) {
511
                try {
512
                        return getRecordset().isSelected(index);
513
                } catch (DriverException e) {
514
                        // TODO Auto-generated catch block
515
                        e.printStackTrace();
516
                }
517
                return false;
518
        }
519
*/
520
        /**
521
         * @see com.iver.cit.gvsig.fmap.layers.CommonOperations#getSelection()
522
         */
523
        /*public FBitSet getSelection() {
524
                try {
525
                        return getRecordset().getSelection();
526
                } catch (DriverException e) {
527
                        // TODO Auto-generated catch block
528
                        e.printStackTrace();
529
                }
530
                return new FBitSet();
531
        }
532
*/
533
        /**
534
         * @see com.iver.cit.gvsig.fmap.layers.CommonOperations#clearSelection()
535
         */
536
        /*public void clearSelection() {
537
                try {
538
                        getRecordset().clearSelection();
539
                } catch (DriverException e) {
540
                        // TODO Auto-generated catch block
541
                        e.printStackTrace();
542
                }
543
        }*/
544

    
545
        /* (non-Javadoc)
546
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.RandomVectorialData#queryByRect(java.awt.geom.Rectangle2D)
547
         */
548
        public FBitSet queryByRect(Rectangle2D rect) throws DriverException {
549
                Strategy s = StrategyManager.getStrategy(this);
550

    
551
                return s.queryByRect(rect);
552
        }
553

    
554
    public FBitSet queryByPoint(Point2D p, double tolerance) throws DriverException
555
    {
556
        Strategy s = StrategyManager.getStrategy(this);
557
        return s.queryByPoint(p, tolerance);
558
    }
559

    
560
    public FBitSet queryByShape(IGeometry g, int relationship) throws DriverException, VisitException
561
    {
562
        Strategy s = StrategyManager.getStrategy(this);
563
        return s.queryByShape(g, relationship);
564
    }
565

    
566
    public XMLItem[] getInfo(Point p, double tolerance) throws DriverException
567
    {        
568
                Point2D pReal = this.getFMap().getViewPort().toMapPoint(p);
569
        FBitSet bs = queryByPoint(pReal, tolerance);
570
        VectorialXMLItem[] item = new VectorialXMLItem[1]; 
571
        item[0] = new VectorialXMLItem(bs, this);
572
        
573
        return item;
574
    }
575
        /**
576
         * @throws DriverException
577
         * @see com.iver.cit.gvsig.fmap.layers.CommonOperations#getRecordset()
578
         */
579
        /*public SelectableDataSource getRecordset() throws DriverException {
580
                if (sds == null){
581
                        try {
582
                                DataSource ds = getSource().getRecordset();
583

584
                                if (ds == null) {
585
                                        return null;
586
                                }
587

588
                                sds = new SelectableDataSource(ds);
589
                                //sds.setSelectionSupport(selectionSupport);
590

591
                                return sds;
592
                        } catch (DriverLoadException e) {
593
                                throw new DriverException(e);
594
                        } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
595
                                throw new DriverException(e);
596
            }
597
                }
598
                return sds;
599
        }
600
*/
601
    /**
602
     * Para cuando haces una uni?n, sustituyes el recorset por el nuevo.
603
     * De esta forma, podr?s poner leyendas basadas en el nuevo
604
     * recordset
605
     * @param newSds
606
     * @throws DriverException
607
     * @throws FieldNotFoundException
608
     * @throws FieldNotFoundException
609
     */
610
 /*   public void setRecordset(SelectableDataSource newSds) throws DriverException, FieldNotFoundException
611
    {
612
        sds = newSds;
613
        //sds.setSelectionSupport(selectionSupport);
614
        legend.setDataSource(sds);
615
        logger.debug("Recordset cambiado a " + sds.getName());
616
    }
617
*/
618
        /**
619
         * @see com.iver.cit.gvsig.fmap.layers.CommonOperations#setLegend(int,
620
         *                 com.iver.cit.gvsig.fmap.rendering.Legend)
621
         */
622
        public void setLegend(VectorialLegend r)
623
                throws DriverException, FieldNotFoundException {
624
                VectorialLegend oldLegend = legend;
625
                legend = r;
626

    
627
                try {
628
                        legend.setDataSource(getRecordset());
629

    
630
                        if (legend.getLabelField() != null) {
631
                            // sds.start();
632
                                // int idLabelField = getRecordset().getFieldIndexByName(legend.getLabelField());
633
                                createLabelLayer(getSource().getRecordset());
634
                                // sds.stop();
635
                        }
636
                        else
637
                            removeLabels();
638
                } catch (DriverException e) {
639
                        throw new DriverException(e);
640
                } catch (FieldNotFoundException e) {
641
                        // TODO Auto-generated catch block
642
                        e.printStackTrace();
643
        } catch (DriverLoadException e) {
644
                        // TODO Auto-generated catch block
645
                        e.printStackTrace();
646
                }
647

    
648
                LegendChangedEvent e = LegendChangedEvent.createLegendChangedEvent(oldLegend, legend);
649
                callLegendChanged(e);
650
        }
651

    
652
        /**
653
         * Devuelve la Leyenda de la capa.
654
         *
655
         * @return Leyenda.
656
         */
657
        public Legend getLegend() {
658
                return legend;
659
        }
660

    
661
        /**
662
         * Devuelve el tipo de shape que contiene la capa.
663
         *
664
         * @return tipo de shape.
665
         *
666
         * @throws DriverException
667
         */
668
        public int getShapeType() throws DriverException {
669
                if (typeShape == -1) {
670
                        try {
671
                                logger.debug("source.start()");
672
                                getSource().start();
673
                                typeShape = getSource().getShapeType();
674
                                logger.debug("source.stop()");
675
                                getSource().stop();
676
                        } catch (DriverIOException e) {
677
                                throw new DriverException(e);
678
                        }
679
                }
680

    
681
                return typeShape;
682
        }
683

    
684
        /**
685
         * @throws XMLException
686
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getProperties()
687
         */
688
        public XMLEntity getXMLEntity() throws XMLException {
689
                XMLEntity xml = super.getXMLEntity();
690
       xml.addChild(getLegend().getXMLEntity());
691
       try {
692
                        xml.addChild(getRecordset().getSelectionSupport().getXMLEntity());
693

    
694
                } catch (DriverException e1) {
695
                        e1.printStackTrace();
696
                        throw new XMLException(e1);
697
                }
698
                if (getSource() instanceof VectorialEditableAdapter){
699
                        setSource(((VectorialEditableAdapter)source).getOriginalAdapter());
700
                }
701
                if (getSource() instanceof VectorialFileAdapter) {
702
                        xml.putProperty("type", "vectorial");
703
                        xml.putProperty("file", ((VectorialFileAdapter) getSource()).getFile());
704
                        //try {
705
                                try {
706
                                        xml.putProperty("recordset-name", getSource().getRecordset().getName());
707
                                } catch (DriverLoadException e) {
708
                                        // TODO Auto-generated catch block
709
                                        e.printStackTrace();
710
                                }
711
                        //} catch (DriverException e) {
712
                        //        throw new XMLException(e);
713
                        //}
714
                } else if (source instanceof VectorialDBAdapter) {
715
            xml.putProperty("type", "vectorial");
716

    
717
            VectorialDatabaseDriver dbDriver = (VectorialDatabaseDriver) getSource().getDriver();
718

    
719
            // Guardamos el nombre del driver para poder recuperarlo
720
            // con el DriverManager de Fernando.
721
            xml.putProperty("db", dbDriver.getName());
722
            //try {
723
                try {
724
                                        xml.putProperty("recordset-name", getSource().getRecordset().getName());
725
                                } catch (DriverLoadException e) {
726
                                        // TODO Auto-generated catch block
727
                                        e.printStackTrace();
728
                                }
729
            //} catch (DriverException e) {
730
            //    throw new XMLException(e);
731
            //}
732
            xml.addChild(dbDriver.getXMLEntity()); // Tercer child. Antes hemos metido la leyenda y el selection support
733
        } else if (source instanceof VectorialAdapter) {
734
            // Se supone que hemos hecho algo gen?rico.
735
            xml.putProperty("type", "vectorial");
736

    
737
            VectorialDriver driver = (VectorialDriver) getSource().getDriver();
738

    
739
            // Guardamos el nombre del driver para poder recuperarlo
740
            // con el DriverManager de Fernando.
741
            xml.putProperty("other", driver.getName());
742
            //try {
743
                try {
744
                                        xml.putProperty("recordset-name", getSource().getRecordset().getName());
745
                                } catch (DriverLoadException e) {
746
                                        // TODO Auto-generated catch block
747
                                        e.printStackTrace();
748
                                }
749
            //} catch (DriverException e) {
750
            //    throw new XMLException(e);
751
            //}
752
            if (driver instanceof IPersistance)
753
            {
754
                // xml.putProperty("className", driver.getClass().getName());
755
                IPersistance persist = (IPersistance) driver;
756
                xml.addChild(persist.getXMLEntity()); // Tercer child. Antes hemos metido la leyenda y el selection support
757
            }
758
                }
759
                xml.putProperty("driverName", getSource().getDriver().getName());
760
        if (bHasJoin)
761
            xml.putProperty("hasJoin", "true");
762

    
763

    
764
                return xml;
765
        }
766

    
767
        /**
768
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setXMLEntity(com.iver.utiles.XMLEntity)
769
         */
770
        public void setXMLEntity03(XMLEntity xml)
771
                throws XMLException {
772

    
773
                super.setXMLEntity(xml);
774
                legend = LegendFactory.createFromXML03(xml.getChild(0));
775

    
776
                try {
777
                        // legend.setDataSource(getRecordset());
778
                        setLegend(legend);
779
                } catch (FieldNotFoundException e) {
780
                        throw new XMLException(e);
781
                } catch (DriverException e) {
782
                        throw new XMLException(e);
783
                }
784

    
785
                try {
786
                                getRecordset().getSelectionSupport().setXMLEntity03(xml.getChild(1));
787
                } catch (DriverException e) {
788
                        e.printStackTrace();
789
                }
790
        }
791

    
792
        /**
793
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setXMLEntity(com.iver.utiles.XMLEntity)
794
         */
795
        public void setXMLEntity(XMLEntity xml)
796
                throws XMLException {
797
        super.setXMLEntity(xml);
798

    
799
                VectorialLegend leg = LegendFactory.createFromXML(xml.getChild(0));
800
                try {
801
                        getRecordset().getSelectionSupport().setXMLEntity(xml.getChild(1));
802
                        String recordsetName = xml.getStringProperty("recordset-name");
803

    
804
                        LayerFactory.getDataSourceFactory().changeDataSourceName(
805
                   getSource().getRecordset().getName(), recordsetName
806
                                        );
807
            // Hacemos que el recordset que hemos creado antes (los
808
            // recordset se crean antes que todo) sea el recordset
809
            // de esta capa. Y del que se crea automaticamente
810
            // en el setLegend del createLayer, nos olvidamos
811
                        SelectableDataSource sds=new SelectableDataSource(LayerFactory.getDataSourceFactory()
812
                    .createRandomDataSource(recordsetName, DataSourceFactory.AUTOMATIC_OPENING));
813
                        //sds.setSelectionSupport(selectionSupport);
814
            //((EditableAdapter)getSource()).setRecordSet(sds);
815
                } catch (NoSuchTableException e1) {
816
                        throw new XMLException(e1);
817
                }  catch (com.hardcode.gdbms.engine.data.driver.DriverException e1) {
818
            throw new XMLException(e1);
819
        } catch (DriverLoadException e1) {
820
            throw new XMLException(e1);
821
        } catch (DriverException e1) {
822
            throw new XMLException(e1);
823
                }
824
        // Si tiene una uni?n, lo marcamos para que no se cree la leyenda hasta el final
825
        // de la lectura del proyecto
826
        if (xml.contains("hasJoin"))
827
        {
828
            setIsJoined(true);
829
            PostProcessSupport.addToPostProcess(this,"setLegend", leg, 1);
830
        }
831
        else
832
        {
833
            try {
834
                // legend.setDataSource(getRecordset());
835
                setLegend(leg);
836
            } catch (FieldNotFoundException e) {
837
                throw new XMLException(e);
838
            } catch (DriverException e) {
839
                throw new XMLException(e);
840
            }
841
        }
842

    
843
        }
844

    
845
        /**
846
         * A?ade un LegendListener a la lista de Listeners.
847
         *
848
         * @param listener LegendListener.
849
         */
850
        public void addLegendListener(LegendListener listener) {
851
                layerChangeSupport.addLayerListener(listener);
852
        }
853

    
854
        /**
855
         * Llamada al m?todo callLegendChanged de los listener.
856
         *
857
         * @param e Evento.
858
         */
859
        private void callLegendChanged(LegendChangedEvent e) {
860
                layerChangeSupport.callLegendChanged(e);
861
        }
862

    
863
        /**
864
         * Borra un LegendListener de la lista de Listeners
865
         *
866
         * @param listener LegendListener.
867
         */
868
        public void removeLegendListener(LegendListener listener) {
869
                layerChangeSupport.removeLayerListener(listener);
870
        }
871

    
872
        /**
873
         * Sobreimplementaci?n del m?todo toString para que las bases de datos
874
         * identifiquen la capa.
875
         *
876
         * @return DOCUMENT ME!
877
         */
878
        public String toString() {
879
                /*
880
                 * Se usa internamente para que la parte de datos
881
                 * identifique de forma un?voca las tablas
882
                 */
883
                String ret = super.toString();
884

    
885
                return "layer" + ret.substring(ret.indexOf('@') + 1);
886
        }
887

    
888
    public boolean isJoined() {
889
        return bHasJoin;
890
    }
891
    
892
    /**
893
         * Returns if a layer is spatially indexed
894
         * @return if this layer has the ability to proces
895
         * spatial queries without secuential scans.
896
         */
897
        public boolean isSpatiallyIndexed(){
898
                ReadableVectorial source = getSource();
899
                if(source instanceof ISpatialDB)
900
                        return true;
901
                if(getISpatialIndex() != null)
902
                        return true;
903
                return false;
904
        }
905

    
906
    public void setIsJoined(boolean hasJoin) {
907
        bHasJoin = hasJoin;
908
    }
909

    
910
    /**
911
     * @return Returns the spatialIndex.
912
     */
913

    
914
    public SpatialIndex getSpatialIndex() {
915
        return null;
916
            //return spatialIndex;
917
    }
918
    
919
    public ISpatialIndex getISpatialIndex(){
920
            return spatialIndex;
921
    }
922

    
923

    
924
        /* public SelectableDataSource getRecordset() {
925
                try {
926
                        return getSource().getRecordset();
927
                } catch (DriverLoadException e) {
928
                        // TODO Auto-generated catch block
929
                        e.printStackTrace();
930
                }
931
                return null;
932
        } */
933

    
934
        /**
935
         * @throws DriverException
936
         * @see com.iver.cit.gvsig.fmap.layers.CommonOperations#getRecordset()
937
         */
938
        public SelectableDataSource getRecordset() throws DriverException {
939
                if (sds == null){
940
                        try {
941
                                SelectableDataSource ds = source.getRecordset();
942

    
943
                                if (ds == null) {
944
                                        return null;
945
                                }
946

    
947
                                sds = ds;
948
                                sds.setSelectionSupport(selectionSupport);
949

    
950
                        } catch (DriverLoadException e) {
951
                                throw new DriverException(e);
952
            }
953
                }
954
                return sds;
955
        }
956

    
957
        /* (non-Javadoc)
958
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setEditing(boolean)
959
         */
960
        public void setEditing(boolean b) {
961
                super.setEditing(b);
962
                if (b)
963
                {
964
                        VectorialEditableAdapter vea = null;
965
                        // TODO: Qu? pasa si hay m?s tipos de adapters?
966
                        if (getSource() instanceof VectorialDBAdapter)
967
                        {
968
                                vea = new VectorialEditableDBAdapter();
969
                        }else if (this instanceof FLyrAnnotation)
970
                        {
971
                                vea = new AnnotationEditableAdapter((FLyrAnnotation)this);
972
                        }
973
                        else
974
                        {
975
                                vea = new VectorialEditableAdapter();
976
                        }
977
            vea.setOriginalVectorialAdapter(getSource());
978
            try{
979
                    ///vea.setSpatialIndex(getSpatialIndex());
980
                    ///vea.setFullExtent(getFullExtent());
981
                    vea.startEdition();
982
                    setSource(vea);
983
                    getRecordset().setSelectionSupport(vea.getOriginalAdapter().getRecordset().getSelectionSupport());
984
            }catch (EditionException e) {
985
                                e.printStackTrace();
986
                        } catch (DriverLoadException e) {
987
                                // TODO Auto-generated catch block
988
                                e.printStackTrace();
989
                        } catch (DriverException e) {
990
                                // TODO Auto-generated catch block
991
                                e.printStackTrace();
992
                        }
993

    
994

    
995
                }
996
                else
997
                {
998
                        VectorialEditableAdapter vea = (VectorialEditableAdapter) getSource();
999
                        setSource(vea.getOriginalAdapter());
1000
                }
1001
                callEditionChanged(LayerEvent.createEditionChangedEvent(this, "edition"));
1002

    
1003
        }
1004

    
1005
    /**
1006
     * Para cuando haces una uni?n, sustituyes el recorset por el nuevo.
1007
     * De esta forma, podr?s poner leyendas basadas en el nuevo
1008
     * recordset
1009
     * @param newSds
1010
     */
1011
    public void setRecordset(SelectableDataSource newSds)
1012
    {
1013
        sds = newSds;
1014
        sds.setSelectionSupport(selectionSupport);
1015
    }
1016
        /*public SelectionSupport getSelectionSupport() {
1017
                return selectionSupport;
1018
        }
1019

1020
        public void setSelectionSupport(SelectionSupport selectionSupport) {
1021
                this.selectionSupport = selectionSupport;
1022
        }*/
1023

    
1024
}