Statistics
| Revision:

root / branches / v2_0_0_prep / libraries / libFMap_mapcontext / src / org / gvsig / fmap / mapcontext / layers / vectorial / FLyrVect.java @ 30187

History | View | Annotate | Download (45 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 org.gvsig.fmap.mapcontext.layers.vectorial;
42

    
43
import java.awt.Graphics2D;
44
import java.awt.Point;
45
import java.awt.geom.AffineTransform;
46
import java.awt.geom.Point2D;
47
import java.awt.image.BufferedImage;
48
import java.net.URI;
49
import java.util.Iterator;
50
import java.util.Set;
51
import java.util.TreeSet;
52

    
53
import org.cresques.cts.ICoordTrans;
54
import org.gvsig.compat.print.PrintAttributes;
55
import org.gvsig.fmap.dal.DALLocator;
56
import org.gvsig.fmap.dal.DataManager;
57
import org.gvsig.fmap.dal.DataStore;
58
import org.gvsig.fmap.dal.DataStoreParameters;
59
import org.gvsig.fmap.dal.DataTypes;
60
import org.gvsig.fmap.dal.exception.DataException;
61
import org.gvsig.fmap.dal.exception.ReadException;
62
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
63
import org.gvsig.fmap.dal.feature.FeatureQuery;
64
import org.gvsig.fmap.dal.feature.FeatureSet;
65
import org.gvsig.fmap.dal.feature.FeatureStore;
66
import org.gvsig.fmap.dal.feature.FeatureStoreNotification;
67
import org.gvsig.fmap.dal.feature.FeatureType;
68
import org.gvsig.fmap.dal.feature.exception.CreateGeometryException;
69
import org.gvsig.fmap.geom.Geometry;
70
import org.gvsig.fmap.geom.GeometryLocator;
71
import org.gvsig.fmap.geom.GeometryManager;
72
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
73
import org.gvsig.fmap.geom.Geometry.TYPES;
74
import org.gvsig.fmap.geom.exception.CreateEnvelopeException;
75
import org.gvsig.fmap.geom.primitive.Circle;
76
import org.gvsig.fmap.geom.primitive.Envelope;
77
import org.gvsig.fmap.geom.type.GeometryType;
78
import org.gvsig.fmap.geom.type.GeometryTypeNotSupportedException;
79
import org.gvsig.fmap.geom.type.GeometryTypeNotValidException;
80
import org.gvsig.fmap.mapcontext.MapContextLocator;
81
import org.gvsig.fmap.mapcontext.ViewPort;
82
import org.gvsig.fmap.mapcontext.exceptions.LegendLayerException;
83
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
84
import org.gvsig.fmap.mapcontext.exceptions.ReloadLayerException;
85
import org.gvsig.fmap.mapcontext.exceptions.ReprojectLayerException;
86
import org.gvsig.fmap.mapcontext.exceptions.StartEditionLayerException;
87
import org.gvsig.fmap.mapcontext.layers.AbstractLinkProperties;
88
import org.gvsig.fmap.mapcontext.layers.FLayer;
89
import org.gvsig.fmap.mapcontext.layers.FLyrDefault;
90
import org.gvsig.fmap.mapcontext.layers.LayerEvent;
91
import org.gvsig.fmap.mapcontext.layers.SpatialCache;
92
import org.gvsig.fmap.mapcontext.layers.operations.VectorialXMLItem;
93
import org.gvsig.fmap.mapcontext.layers.operations.XMLItem;
94
import org.gvsig.fmap.mapcontext.rendering.legend.ILegend;
95
import org.gvsig.fmap.mapcontext.rendering.legend.IVectorLegend;
96
import org.gvsig.fmap.mapcontext.rendering.legend.LegendException;
97
import org.gvsig.fmap.mapcontext.rendering.legend.events.FeatureDrawnNotification;
98
import org.gvsig.fmap.mapcontext.rendering.legend.events.LegendChangedEvent;
99
import org.gvsig.fmap.mapcontext.rendering.legend.events.LegendClearEvent;
100
import org.gvsig.fmap.mapcontext.rendering.legend.events.LegendContentsChangedListener;
101
import org.gvsig.fmap.mapcontext.rendering.legend.events.SymbolLegendEvent;
102
import org.gvsig.fmap.mapcontext.rendering.legend.styling.ILabelingStrategy;
103
import org.gvsig.fmap.mapcontext.rendering.symbols.CartographicSupport;
104
import org.gvsig.tools.ToolsLocator;
105
import org.gvsig.tools.dynobject.DynClass;
106
import org.gvsig.tools.dynobject.DynObjectManager;
107
import org.gvsig.tools.dynobject.exception.DynMethodException;
108
import org.gvsig.tools.dynobject.exception.DynMethodNotSupportedException;
109
import org.gvsig.tools.exception.BaseException;
110
import org.gvsig.tools.locator.LocatorException;
111
import org.gvsig.tools.observer.Observable;
112
import org.gvsig.tools.observer.Observer;
113
import org.gvsig.tools.persistence.PersistenceException;
114
import org.gvsig.tools.persistence.PersistentState;
115
import org.gvsig.tools.task.Cancellable;
116
import org.slf4j.LoggerFactory;
117

    
118

    
119
/**
120
 * Capa b?sica Vectorial.
121
 *
122
 * @author Fernando Gonz?lez Cort?s
123
 */
124

    
125
// TODO Cuando no sea para pruebas debe no ser public
126
public class FLyrVect extends FLyrDefault implements VectorLayer, LegendContentsChangedListener,
127
Observer {
128
        final static private org.slf4j.Logger logger = LoggerFactory.getLogger(FLyrVect.class);
129
        private static final GeometryManager geomManager = GeometryLocator.getGeometryManager();
130
        /** Leyenda de la capa vectorial */
131
        private IVectorLegend legend;
132
        private int typeShape = -1;
133
        private FeatureStore featureStore=null;
134
        private SpatialCache spatialCache = new SpatialCache();
135

    
136
        /**
137
         * An implementation of gvSIG spatial index
138
         */
139
        //    protected ISpatialIndex spatialIndex = null;
140
        private boolean bHasJoin = false;
141
        private IVectorLegend loadLegend = null;
142

    
143
        //Lo a?ado. Caracter?sticas de HyperEnlace (LINK)
144
        private FLyrVectLinkProperties linkProperties=new FLyrVectLinkProperties();
145

    
146
        public FLyrVect() {
147
                super();
148
        }
149
        /**
150
         * Devuelve el VectorialAdapater de la capa.
151
         *
152
         * @return VectorialAdapter.
153
         */
154
        public DataStore getDataStore() {
155
                if (!this.isAvailable()) {
156
                        return null;
157
                }
158
                return featureStore;
159
        }
160

    
161
        /**
162
         * If we use a persistent spatial index associated with this layer, and the
163
         * index is not intrisic to the layer (for example spatial databases) this
164
         * method looks for existent spatial index, and loads it.
165
         *
166
         */
167
        //    private void loadSpatialIndex() {
168
        //        //FIXME: Al abrir el indice en fichero...
169
        //        //?C?mo lo liberamos? un metodo Layer.shutdown()
170
        //
171
        //
172
        //        ReadableVectorial source = getSource();
173
        //        //REVISAR QUE PASA CON LOS DRIVERS DXF, DGN, etc.
174
        //        //PUES SON VECTORIALFILEADAPTER
175
        //        if (!(source instanceof VectorialFileAdapter)) {
176
        //            // we are not interested in db adapters
177
        //            return;
178
        //        }
179
        //        VectorialDriver driver = source.getDriver();
180
        //        if (!(driver instanceof BoundedShapes)) {
181
        //            // we dont spatially index layers that are not bounded
182
        //            return;
183
        //        }
184
        //        File file = ((VectorialFileAdapter) source).getFile();
185
        //        String fileName = file.getAbsolutePath();
186
        //        File sptFile = new File(fileName + ".qix");
187
        //        if (!sptFile.exists() || (!(sptFile.length() > 0))) {
188
        //            // before to exit, look for it in temp path
189
        //            String tempPath = System.getProperty("java.io.tmpdir");
190
        //            fileName = tempPath + File.separator + sptFile.getName();
191
        //            sptFile = new File(fileName);
192
        //            // it doesnt exists, must to create
193
        //            if (!sptFile.exists() || (!(sptFile.length() > 0))) {
194
        //                return;
195
        //            }// if
196
        //        }// if
197
        //
198
        //        try {
199
        //            source.start();
200
        //            spatialIndex = new QuadtreeGt2(FileUtils.getFileWithoutExtension(sptFile),
201
        //                    "NM", source.getFullExtent(), source.getShapeCount(), false);
202
        //            source.setSpatialIndex(spatialIndex);
203
        //        } catch (SpatialIndexException e) {
204
        //            spatialIndex = null;
205
        //            e.printStackTrace();
206
        //            return;
207
        //        } catch (ReadDriverException e) {
208
        //            spatialIndex = null;
209
        //            e.printStackTrace();
210
        //            return;
211
        //        }
212
        //
213
        //    }
214

    
215
        /**
216
         * Checks if it has associated an external spatial index
217
         * (an spatial index file).
218
         *
219
         * It looks for it in main file path, or in temp system path.
220
         * If main file is rivers.shp, it looks for a file called
221
         * rivers.shp.qix.
222

223
         * @return
224
         */
225
        //    public boolean isExternallySpatiallyIndexed() {
226
        //        /*
227
        //         * FIXME (AZABALA): Independizar del tipo de fichero de ?ndice
228
        //          * con el que se trabaje (ahora mismo considera la extension .qix,
229
        //         * pero esto depender? del tipo de ?ndice)
230
        //         * */
231
        //        ReadableVectorial source = getSource();
232
        //        if (!(source instanceof VectorialFileAdapter)) {
233
        //            // we are not interested in db adapters.
234
        //            // think in non spatial dbs, like HSQLDB
235
        //            return false;
236
        //        }
237
        //        File file = ((VectorialFileAdapter) source).getFile();
238
        //        String fileName = file.getAbsolutePath();
239
        //        File sptFile = new File(fileName + ".qix");
240
        //        if (!sptFile.exists() || (!(sptFile.length() > 0))) {
241
        //            // before to exit, look for it in temp path
242
        //            // it doesnt exists, must to create
243
        //            String tempPath = System.getProperty("java.io.tmpdir");
244
        //            fileName = tempPath + File.separator + sptFile.getName();
245
        //            sptFile = new File(fileName);
246
        //            if (!sptFile.exists() || (!(sptFile.length() > 0))) {
247
        //                return false;
248
        //            }// if
249
        //        }// if
250
        //        return true;
251
        //    }
252
        /**
253
         * Inserta el VectorialAdapter a la capa.
254
         *
255
         * @param va
256
         *            VectorialAdapter.
257
         *
258
         * @deprecated esto deber?a se ser protected
259
         */
260
          public void setDataStore(DataStore dataStore) throws LoadLayerException {
261
                if (this.featureStore != null && this.featureStore != dataStore){
262
                        this.featureStore.deleteObserver(this);
263
                }
264

    
265
                featureStore = (FeatureStore)dataStore;
266

    
267
                IVectorLegend legend = null;
268
                try {
269
                        legend = (IVectorLegend) dataStore.invokeDynMethod(
270
                                        "getLegend", null);
271

    
272
                } catch (DynMethodNotSupportedException e1) {
273
                        try {
274
                                legend = MapContextLocator.getMapContextManager()
275
                                                .createDefaultVectorLegend(getShapeType());
276
                        } catch (ReadException e) {
277
                                throw new LoadLayerException(this.getName(), e);
278
                        }
279

    
280
                } catch (DynMethodException e1) {
281
                        throw new LoadLayerException(this.getName(), e1);
282
                }
283
                this.setLegend((IVectorLegend) legend);
284

    
285

    
286
                ILabelingStrategy labeler = null;
287
                try {
288
                        labeler = (ILabelingStrategy) dataStore.invokeDynMethod(
289
                                        "getLabeling", null);
290
                } catch (DynMethodNotSupportedException e1) {
291
                        labeler = null;
292
                } catch (DynMethodException e1) {
293
                        throw new LoadLayerException(this.getName(), e1);
294
                }
295

    
296
                if (labeler != null) {
297
                        try {
298
                                labeler.setLayer(this);
299
                        } catch (ReadException e) {
300
                                throw new LoadLayerException(this.getName(), e);
301
                        }
302
                        this.setLabelingStrategy(labeler);
303
                        this.setIsLabeled(true); // TODO: ac? no s'hauria de detectar si t? etiquetes?????
304
                }
305

    
306
                this.delegate(dataStore);
307

    
308
                dataStore.addObserver(this);
309

    
310
                // azabala: we check if this layer could have a file spatial index
311
                // and load it if it exists
312
                //        loadSpatialIndex();
313
        }
314

    
315
        public Envelope getFullEnvelope() throws ReadException {
316
                Envelope rAux;
317
                try {
318
                        rAux = getFeatureStore().getEnvelope();
319
                } catch (BaseException e) {
320
                        throw new ReadException(getName(),e);
321
                }
322

    
323
                //Esto es para cuando se crea una capa nueva con el fullExtent de ancho y alto 0.
324
                if (rAux == null || rAux.getMaximum(0)-rAux.getMinimum(0)==0 && rAux.getMaximum(1)-rAux.getMinimum(1)==0) {
325
                        try {
326
                                rAux= geomManager.createEnvelope(0,0,100,100, SUBTYPES.GEOM2D);
327
                        } catch (CreateEnvelopeException e) {
328
                                logger.error("Error creating the envelope", e);
329
                                e.printStackTrace();
330
                        }
331
                }
332
                // Si existe reproyecci?n, reproyectar el extent
333
                ICoordTrans ct = getCoordTrans();
334
                try{
335
                        if (ct != null) {
336
                                Point2D pt1 = new Point2D.Double(rAux.getMinimum(0), rAux.getMinimum(1));
337
                                Point2D pt2 = new Point2D.Double(rAux.getMaximum(0), rAux.getMaximum(1));
338
                                pt1 = ct.convert(pt1, null);
339
                                pt2 = ct.convert(pt2, null);
340
                                try {
341
                                        rAux = geomManager.createEnvelope(pt1.getX(),pt1.getY(),pt2.getX(),pt2.getY(), SUBTYPES.GEOM2D);
342
                                } catch (CreateEnvelopeException e) {
343
                                        logger.error("Error creating the envelope", e);
344
                                        e.printStackTrace();
345
                                }//new Rectangle2D.Double();
346
                        }
347
                }catch (IllegalStateException e) {
348
                        this.setAvailable(false);
349
                        this.addError(new ReprojectLayerException(getName(), e));
350
                }
351
                return rAux;
352

    
353
        }
354

    
355
        /**
356
         * Draws using IFeatureIterator. This method will replace the old draw(...) one.
357
         * @autor jaume dominguez faus - jaume.dominguez@iver.es
358
         * @param image
359
         * @param g
360
         * @param viewPort
361
         * @param cancel
362
         * @param scale
363
         * @throws ReadDriverException
364
         */
365
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
366
                        Cancellable cancel, double scale) throws ReadException {
367
                
368
                if (legend == null) {
369
                        return;
370
                }
371
                
372
                if (!this.isWithinScale(scale)) {
373
                        return;
374
                }
375
                if (cancel.isCanceled()) {
376
                        return;
377
                }
378

    
379
                if (spatialCache.isEnabled()) {
380
                        spatialCache.clearAll();
381
                        legend.addDrawingObserver(this);
382
                }
383

    
384
                try {
385
                        legend.draw(image, g, viewPort, cancel, scale, null,
386
                                        getCoordTrans(), getFeatureStore());
387

    
388
                } catch (LegendException e) {
389
                        this.setVisible(false);
390
                        this.setActive(false);
391
                        throw new ReadException(getName(), e);
392
                } finally {
393
                        if (spatialCache.isEnabled()) {
394
                                legend.deleteDrawingObserver(this);
395
                        }
396
                }
397
        }
398
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
399
                        double scale, PrintAttributes properties) throws ReadException {
400
                if (!this.isWithinScale(scale)) {
401
                        return;
402
                }
403
                if (cancel.isCanceled()) {
404
                        return;
405
                }
406

    
407
                try {
408
                        legend.print( g, viewPort, cancel, scale, null,
409
                                        getCoordTrans(), getFeatureStore(), properties);
410

    
411
                } catch (LegendException e) {
412
                        this.setVisible(false);
413
                        this.setActive(false);
414
                        throw new ReadException(getName(), e);
415
                }
416
        }
417

    
418
        /**
419
         * <p>
420
         * Creates an spatial index associated to this layer.
421
         * The spatial index will used
422
         * the native projection of the layer, so if the layer is reprojected, it will
423
         * be ignored.
424
         * </p>
425
         * @param cancelMonitor instance of CancellableMonitorable that allows
426
         * to monitor progress of spatial index creation, and cancel the process
427
         */
428
        //    public void createSpatialIndex(CancellableMonitorable cancelMonitor){
429
        //         // FJP: ESTO HABR? QUE CAMBIARLO. PARA LAS CAPAS SECUENCIALES, TENDREMOS
430
        //        // QUE ACCEDER CON UN WHILE NEXT. (O mejorar lo de los FeatureVisitor
431
        //        // para que acepten recorrer sin geometria, solo con rectangulos.
432
        //
433
        //        //If this vectorial layer is based in a spatial database, the spatial
434
        //        //index is already implicit. We only will index file drivers
435
        //        ReadableVectorial va = getSource();
436
        //        //We must think in non spatial databases, like HSQLDB
437
        //        if(!(va instanceof VectorialFileAdapter)){
438
        //            return;
439
        //        }
440
        //        if (!(va.getDriver() instanceof BoundedShapes)) {
441
        //            return;
442
        //        }
443
        //        File file = ((VectorialFileAdapter) va).getFile();
444
        //        String fileName = file.getAbsolutePath();
445
        //        ISpatialIndex localCopy = null;
446
        //        try {
447
        //            va.start();
448
        //            localCopy = new QuadtreeGt2(fileName, "NM", va.getFullExtent(),
449
        //                    va.getShapeCount(), true);
450
        //
451
        //        } catch (SpatialIndexException e1) {
452
        //            // Probably we dont have writing permissions
453
        //            String directoryName = System.getProperty("java.io.tmpdir");
454
        //            File newFile = new File(directoryName +
455
        //                    File.separator +
456
        //                    file.getName());
457
        //            String newFileName = newFile.getName();
458
        //            try {
459
        //                localCopy = new QuadtreeGt2(newFileName, "NM", va.getFullExtent(),
460
        //                        va.getShapeCount(), true);
461
        //            } catch (SpatialIndexException e) {
462
        //                // if we cant build a file based spatial index, we'll build
463
        //                // a pure memory spatial index
464
        //                localCopy = new QuadtreeJts();
465
        //            } catch (ReadException e) {
466
        //                localCopy = new QuadtreeJts();
467
        //            }
468
        //
469
        //        } catch(Exception e){
470
        //            e.printStackTrace();
471
        //        }//try
472
        //        BoundedShapes shapeBounds = (BoundedShapes) va.getDriver();
473
        //        try {
474
        //            for (int i=0; i < va.getShapeCount(); i++)
475
        //            {
476
        //                if(cancelMonitor != null){
477
        //                    if(cancelMonitor.isCanceled())
478
        //                        return;
479
        //                    cancelMonitor.reportStep();
480
        //                }
481
        //                Rectangle2D r = shapeBounds.getShapeBounds(i);
482
        //                if(r != null)
483
        //                    localCopy.insert(r, i);
484
        //            } // for
485
        //            va.stop();
486
        //            if(localCopy instanceof IPersistentSpatialIndex)
487
        //                ((IPersistentSpatialIndex) localCopy).flush();
488
        //            spatialIndex = localCopy;
489
        //            //vectorial adapter needs a reference to the spatial index, to solve
490
        //            //request for feature iteration based in spatial queries
491
        //            source.setSpatialIndex(spatialIndex);
492
        //        } catch (ReadException e) {
493
        //            // TODO Auto-generated catch block
494
        //            e.printStackTrace();
495
        //        }
496
        //    }
497

    
498
        //    public void createSpatialIndex() {
499
        //        createSpatialIndex(null);
500
        //    }
501

    
502

    
503
        public void setLegend(IVectorLegend r) throws LegendLayerException {
504
                if (this.legend == r){
505
                        return;
506
                }
507
                if (this.legend != null && this.legend.equals(r)){
508
                        return;
509
                }
510
                IVectorLegend oldLegend = legend;
511
                legend = r;
512
//                try {
513
//                        legend.setFeatureStore(getFeatureStore());
514
//                } catch (ReadException e1) {
515
//                        throw new LegendLayerException(getName(),e1);
516
//                } catch (DataException e) {
517
//                        throw new LegendLayerException(getName(),e);
518
//                } finally{
519
//                        this.updateDrawVersion();
520
//                }
521

    
522
                if (oldLegend != null) {
523
                        oldLegend.removeLegendListener(this);
524
                        oldLegend.deleteDrawingObserver(this);
525
                }
526
                if (legend != null) {
527
                        legend.addLegendListener(this);
528
                }
529

    
530
                LegendChangedEvent e = LegendChangedEvent.createLegendChangedEvent(
531
                                oldLegend, legend);
532
                e.setLayer(this);
533
                callLegendChanged(e);
534
        }
535

    
536
        /**
537
         * Devuelve la Leyenda de la capa.
538
         *
539
         * @return Leyenda.
540
         */
541
        public ILegend getLegend() {
542
                return legend;
543
        }
544

    
545
        /**
546
         * Devuelve el tipo de shape que contiene la capa.
547
         *
548
         * @return tipo de shape.
549
         *
550
         * @throws ReadException
551
         */
552
        public int getShapeType() throws ReadException {
553
                if (typeShape == -1) {
554
                        FeatureType featureType;
555
                        try {
556
                                featureType = (((FeatureStore)getDataStore()).getDefaultFeatureType());
557
                        } catch (DataException e) {
558
                                throw new ReadException(getName(),e);
559
                        }
560
                        int indexGeom=featureType.getDefaultGeometryAttributeIndex();
561
                        typeShape=featureType.getAttributeDescriptor(indexGeom).getGeometryType();
562
                }
563
                return typeShape;
564
        }
565
        
566
        public void saveToState(PersistentState state) throws PersistenceException {
567

    
568
                if (!this.isAvailable()) {
569
                        return;
570
                }
571
                
572
                super.saveToState(state);
573

    
574
                if (getLegend()!=null) state.set("legend", getLegend());
575
                
576
                FeatureStore fst = null;
577
                fst = getFeatureStore();
578

    
579
                if (fst != null) state.set("featureStore", fst);
580
                if (strategy != null) {
581
                        state.set("isLabeled", isLabeled);
582
                        state.set("labelingStrategy", strategy);
583
                }                
584
                
585
                if (getLinkProperties() != null) state.set("linkProperties", getLinkProperties());
586
                
587
                state.set("bHasJoin", bHasJoin);
588
                state.set("typeShape", typeShape);
589
        }
590

    
591
//        public XMLEntity getXMLEntity() throws XMLException {
592
//
593
//                if (!this.isAvailable() && this.orgXMLEntity != null) {
594
//                        return this.orgXMLEntity;
595
//                }
596
//                XMLEntity xml = super.getXMLEntity();
597
//                if (getLegend()!=null){
598
//                        XMLEntity xmlLegend=getLegend().getXMLEntity();
599
//                        xmlLegend.putProperty("tagName","legend");
600
//                        xml.addChild(xmlLegend);
601
//                }
602
//                try {
603
//                        PersistenceManager manager = ToolsLocator.getPersistenceManager();
604
//                        PersistentState stateFeatureStore=manager.getState(getFeatureStore());
605
//                        stateFeatureStore.set("tagName","featureStore");
606
//                        xml.addChild(((XMLEntityState)stateFeatureStore).getXMLEntity());
607
//                } catch (ReadException e) {
608
//                        throw new XMLLayerException(getName(),e);
609
//                } catch (PersistenceException e) {
610
//                        throw new XMLLayerException(getName(),e);
611
//                }
612
//                // properties from ILabelable
613
//                xml.putProperty("isLabeled", isLabeled);
614
//                if (strategy != null) {
615
//                        XMLEntity strategyXML = strategy.getXMLEntity();
616
//                        strategyXML.putProperty("tagName", "labelingStrategy");
617
//                        xml.addChild(strategy.getXMLEntity());
618
//                }
619
//                xml.addChild(getLinkProperties().getXMLEntity());
620
//                return xml;
621
//        }
622
        
623
        
624
        
625

    
626
        public void loadFromState(PersistentState state) throws PersistenceException {
627
                
628
                super.loadFromState(state);
629
                
630
                DataStore store = (DataStore) state.get("featureStore");
631
                try {
632
                        this.setDataStore(store);
633
                } catch (LoadLayerException e) {
634
                        logger.error("While setting datastore: " + e.getMessage());
635
                }
636

    
637
                IVectorLegend lgnd = (IVectorLegend) state.get("legend");
638
                try {
639
                        this.setLegend(lgnd);
640
                } catch (LegendLayerException e) {
641
                        logger.error("While setting legend: " + e.getMessage());
642
                }
643

    
644
                Boolean isLbl = new Boolean(false);
645
                ILabelingStrategy lblst = null;
646
                
647
                try {
648
                        isLbl = (Boolean) state.get("isLabeled");
649
                        lblst = (ILabelingStrategy) state.get("labelingStrategy");
650
                } catch (Exception ex) {
651
                        logger.warn("While getting label/strategy: " + ex.getMessage());
652
                }
653
                
654
                /*
655
                String _labelFieldName = null;
656
                String _labelfield = null;
657
                */
658
                
659
                if (isLbl.booleanValue()) {
660
                        this.setIsLabeled(true);
661
                        this.setLabelingStrategy(lblst);
662
                } else {
663
                        this.setIsLabeled(false);
664
                        this.setLabelingStrategy(null);
665
                }
666
                        
667
                bHasJoin = state.getBoolean("bHasJoin");
668
                typeShape = state.getInt("typeShape");
669

    
670
//                        try { _labelFieldName = state.getString("labelFieldName"); } catch (PersistenceException ex) {
671
//                                _labelFieldName = null;
672
//                        }
673
//                        try { _labelfield = state.getString("labelfield"); } catch (PersistenceException ex) {
674
//                                _labelfield = null;
675
//                        }
676
                        
677
                        // ILabelingStrategy not implemented
678
//                        if (_labelFieldName != null) {
679
//                                
680
//                                AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy();
681
//                                try {
682
//                                        labeling.setLayer(this);
683
//                                } catch (ReadException e) {
684
//                                        logger.error("While setting layer to AttrInTableLabelingStrategy: " + e.getMessage());
685
//                                }
686
//                                labeling.setUsesFixedSize(true);
687
//                                labeling.setFixedSize(10);
688
//                                labeling.setTextField(_labelFieldName);
689
//                                labeling.setHeightField(state.getString("labelHeightFieldName"));
690
//                                labeling.setRotationField(state.getString("labelRotationFieldName"));
691
//                                setLabelingStrategy(labeling);
692
//                                setIsLabeled(true);
693
//                                
694
//                        } else {
695
//                                if (_labelfield != null) {
696
//                                        
697
//                                        AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy();
698
//                                        try {
699
//                                                labeling.setLayer(this);
700
//                                        } catch (ReadException e) {
701
//                                                logger.error("While setting layer to AttrInTableLabelingStrategy: " + e.getMessage());
702
//                                        }
703
//                                        labeling.setUsesFixedSize(true);
704
//                                        labeling.setFixedSize(10);
705
//                                        labeling.setTextField(_labelfield);
706
//                                        labeling.setHeightField(state.getString("labelFieldHeight"));
707
//                                        labeling.setRotationField(state.getString("labelFieldRotation"));
708
//                                        setLabelingStrategy(labeling);
709
//                                        setIsLabeled(true);
710
//                                }
711
//                        }
712
                        
713
        }
714

    
715
//        public void setXMLEntity(XMLEntity xml) throws XMLException {
716
//                try {
717
//                        super.setXMLEntity(xml);
718
//                        XMLEntity legendXML = xml.firstChild("tagName","legend");
719
//                        IVectorLegend leg = LegendFactory.createFromXML(legendXML);
720
//
721
//                        //            PersistentState persistentState=new XMLEntityState(new XMLEntityManager());
722
//                        XMLEntity xmlStore=xml.firstChild("tagName","featureStore");
723
//                        XMLEntityManager xmlManger = new XMLEntityManager();
724
//                        PersistentState state = xmlManger.createState(xmlStore);
725
//                        DataStore store = (DataStore) ToolsLocator.getPersistenceManager().create(state);
726
//                        //            persistentState.createState(xmlStore);
727
//
728
//                        //            DataManager dm=DALLocator.getDataManager();
729
//
730
//                        this.setDataStore(store);
731
//                        /* end patch */
732
//                        try {
733
//                                setLegend(leg);
734
//                        } catch (LegendLayerException e) {
735
//                                throw new XMLLegendException(e);
736
//                        }
737
//                        // set properties for ILabelable
738
//
739
//                        if (xml.contains("isLabeled")
740
//                                        && xml.getBooleanProperty(("isLabeled"))) {
741
//                                XMLEntity labelingXML = xml.firstChild("tagName", "labelingStrategy");
742
//                                if (labelingXML != null){
743
//
744
//                                        isLabeled = true;
745
//                                        try {
746
//                                                this.strategy = LabelingFactory.createStrategyFromXML(labelingXML, this);
747
//                                        } catch (NotExistInXMLEntity neXMLEX) {
748
//                                                // no strategy was set, just continue;
749
//                                                logger.warn("Reached what should be unreachable code");
750
//                                        }
751
//                                } else {
752
//                                        isLabeled = false;
753
//                                }
754
//                        } else if (legendXML.contains("labelFieldName")|| legendXML.contains("labelfield")) {
755
//                            /* (jaume) begin patch;
756
//                         * for backward compatibility purposes. Since gvSIG v1.1 labeling is
757
//                         * no longer managed by the Legend but by the ILabelingStrategy. The
758
//                         * following allows restoring older projects' labelings.
759
//                         */
760
//                                String labelTextField =        null;
761
//                            if (legendXML.contains("labelFieldName")){
762
//                                    labelTextField = legendXML.getStringProperty("labelFieldName");
763
//                                    if (labelTextField != null) {
764
//                                            AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy();
765
//                                            labeling.setLayer(this);
766
//                                            labeling.setUsesFixedSize(true);
767
//                                            labeling.setFixedSize(10);
768
//                                            labeling.setTextField(labelTextField);
769
//                                            labeling.setHeightField(legendXML.getStringProperty("labelHeightFieldName"));
770
//                                            labeling.setRotationField(legendXML.getStringProperty("labelRotationFieldName"));
771
//                                            this.setLabelingStrategy(labeling);
772
//                                            this.setIsLabeled(true);
773
//                                    }
774
//                            }else{
775
//                                    labelTextField = legendXML.getStringProperty("labelfield");
776
//                                    if (labelTextField != null) {
777
//                                            AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy();
778
//                                            labeling.setLayer(this);
779
//                                            labeling.setUsesFixedSize(true);
780
//                                            labeling.setFixedSize(10);
781
//                                            labeling.setTextField(labelTextField);
782
//                                            labeling.setHeightField(legendXML.getStringProperty("labelFieldHeight"));
783
//                                            labeling.setRotationField(legendXML.getStringProperty("labelFieldRotation"));
784
//                                            this.setLabelingStrategy(labeling);
785
//                                            this.setIsLabeled(true);
786
//                                    }
787
//                            }
788
//                }else{
789
//                                isLabeled = false;
790
//                        }
791
//                        XMLEntity xmlLinkProperties=xml.firstChild("typeChild","linkProperties");
792
//                        if (xmlLinkProperties != null){
793
//                                getLinkProperties().setXMLEntity(xmlLinkProperties);
794
//                        }
795
//                } catch (Exception e) {
796
//                        e.printStackTrace();
797
//                        this.setAvailable(false);
798
//                        this.orgXMLEntity = xml;
799
//
800
//                }
801
//                //
802
//
803
//        }
804

    
805

    
806

    
807

    
808
        /**
809
         * Sobreimplementaci?n del m?todo toString para que las bases de datos
810
         * identifiquen la capa.
811
         *
812
         * @return DOCUMENT ME!
813
         */
814
        public String toString() {
815
                /*
816
                 * Se usa internamente para que la parte de datos identifique de forma
817
                 * un?voca las tablas
818
                 */
819
                String ret = super.toString();
820

    
821
                return "layer" + ret.substring(ret.indexOf('@') + 1);
822
        }
823

    
824
        public boolean isJoined() {
825
                return bHasJoin;
826
        }
827

    
828
        /**
829
         * Returns if a layer is spatially indexed
830
         *
831
         * @return if this layer has the ability to proces spatial queries without
832
         *         secuential scans.
833
         */
834
        //    public boolean isSpatiallyIndexed() {
835
        //        ReadableVectorial source = getSource();
836
        //        if (source instanceof ISpatialDB)
837
        //            return true;
838
        //
839
        ////FIXME azabala
840
        ///*
841
        // * Esto es muy dudoso, y puede cambiar.
842
        // * Estoy diciendo que las que no son fichero o no son
843
        // * BoundedShapes estan indexadas. Esto es mentira, pero
844
        // * as? quien pregunte no querr? generar el indice.
845
        // * Esta por ver si interesa generar el indice para capas
846
        // * HSQLDB, WFS, etc.
847
        // */
848
        //        if(!(source instanceof VectorialFileAdapter)){
849
        //            return true;
850
        //        }
851
        //        if (!(source.getDriver() instanceof BoundedShapes)) {
852
        //            return true;
853
        //        }
854
        //
855
        //        if (getISpatialIndex() != null)
856
        //            return true;
857
        //        return false;
858
        //    }
859

    
860
        public void setIsJoined(boolean hasJoin) {
861
                bHasJoin = hasJoin;
862
        }
863

    
864
        //    /**
865
        //     * @return Returns the spatialIndex.
866
        //     */
867
        //    public ISpatialIndex getISpatialIndex() {
868
        //        return spatialIndex;
869
        //    }
870
        //    /**
871
        //     * Sets the spatial index. This could be useful if, for some
872
        //     * reasons, you want to work with a distinct spatial index
873
        //     * (for example, a spatial index which could makes nearest
874
        //     * neighbour querys)
875
        //     * @param spatialIndex
876
        //     */
877
        //    public void setISpatialIndex(ISpatialIndex spatialIndex){
878
        //        this.spatialIndex = spatialIndex;
879
        //    }
880

    
881
        public void setEditing(boolean b) throws StartEditionLayerException {
882
                super.setEditing(b);
883
                if (b){
884
                        try {
885
                                getFeatureStore().edit();
886
                        } catch (ReadException e) {
887
                                throw new StartEditionLayerException(getName(),e);
888
                        } catch (DataException e) {
889
                                throw new StartEditionLayerException(getName(),e);
890
                        }
891
                }
892
                setSpatialCacheEnabled(b);
893
                callEditionChanged(LayerEvent
894
                                .createEditionChangedEvent(this, "edition"));
895

    
896
        }
897

    
898
        
899
        /**
900
         * @deprecated Use {@link #getSpatialCache()}
901
         */
902
        public void clearSpatialCache()
903
        {
904
                spatialCache.clearAll();
905
        }
906

    
907
        /**
908
         * @deprecated Use {@link #getSpatialCache()}
909
         */
910
        public boolean isSpatialCacheEnabled() {
911
                return spatialCache.isEnabled();
912
        }
913

    
914
        /**
915
         * @deprecated Use {@link #getSpatialCache()}
916
         */
917
        public void setSpatialCacheEnabled(boolean spatialCacheEnabled) {
918
                spatialCache.setEnabled(spatialCacheEnabled);
919
        }
920

    
921
        public SpatialCache getSpatialCache() {
922
                return spatialCache;
923
        }
924

    
925
        /**
926
         * Siempre es un numero mayor de 1000
927
         * @param maxFeatures
928
         */
929
        public void setMaxFeaturesInEditionCache(int maxFeatures) {
930
                if (maxFeatures > spatialCache.getMaxFeatures()) {
931
                        spatialCache.setMaxFeatures(maxFeatures);
932
                }
933

    
934
        }
935

    
936
        /**
937
         * This method returns a boolean that is used by the FPopMenu
938
         * to make visible the properties menu or not. It is visible by
939
         * default, and if a later don't have to show this menu only
940
         * has to override this method.
941
         * @return
942
         * If the properties menu is visible (or not)
943
         */
944
        public boolean isPropertiesMenuVisible(){
945
                return true;
946
        }
947

    
948
        public void reload() throws ReloadLayerException {
949
                super.reload();
950
                try {
951
                        DataManager dataManager=DALLocator.getDataManager();
952
                        DataStoreParameters storeParameters;
953

    
954
                        storeParameters = getFeatureStore().getParameters();
955

    
956
                        DataStore dataStore=dataManager.createStore(storeParameters);
957
                        setDataStore(dataStore);
958
                        getFeatureStore().refresh();
959
                } catch (Exception e) {
960
                        throw new ReloadLayerException(getName(),e);
961
                }
962
                //        try {
963
                //            this.source.getDriver().reload();
964
                //            if (this.getLegend() == null) {
965
                //                if (this.getRecordset().getDriver() instanceof WithDefaultLegend) {
966
                //                    WithDefaultLegend aux = (WithDefaultLegend) this.getRecordset().getDriver();
967
                //                    this.setLegend((IVectorLegend) aux.getDefaultLegend());
968
                //                    this.setLabelingStrategy(aux.getDefaultLabelingStrategy());
969
                //                } else {
970
                //                    this.setLegend(LegendFactory.createSingleSymbolLegend(
971
                //                            this.getShapeType()));
972
                //                }
973
                //            }
974
                //
975
                //        } catch (LegendLayerException e) {
976
                //            this.setAvailable(false);
977
                //            throw new ReloadLayerException(getName(),e);
978
                //        } catch (ReadException e) {
979
                //            this.setAvailable(false);
980
                //            throw new ReloadLayerException(getName(),e);
981
                //        }
982

    
983

    
984
        }
985

    
986
        protected void setLoadSelection(Object xml) {
987
                // this.loadSelection = xml;
988
        }
989

    
990
        protected void setLoadLegend(IVectorLegend legend) {
991
                this.loadLegend = legend;
992
        }
993

    
994
        protected void putLoadSelection() {
995
                //        if (this.loadSelection == null) return;
996
                //        try {
997
                //            this.getRecordset().getSelectionSupport().setXMLEntity(this.loadSelection);
998
                //        } catch (ReadDriverException e) {
999
                //            throw new XMLException(e);
1000
                //        }
1001
                //        this.loadSelection = null;
1002

    
1003
        }
1004
        protected void putLoadLegend() throws LegendLayerException {
1005
                if (this.loadLegend == null) {
1006
                        return;
1007
                }
1008
                this.setLegend(this.loadLegend);
1009
                this.loadLegend = null;
1010
        }
1011

    
1012
        protected void cleanLoadOptions() {
1013
                this.loadLegend = null;
1014
                this.loadSelection = null;
1015
        }
1016

    
1017
        public boolean isWritable() {
1018
                return getFeatureStore().allowWrite();
1019
        }
1020

    
1021
        public FLayer cloneLayer() throws Exception {
1022
                FLyrVect clonedLayer = new FLyrVect();
1023
                clonedLayer.setDataStore(getDataStore());
1024
                if (isJoined()) {
1025
                        clonedLayer.setIsJoined(true);
1026
                }
1027
                clonedLayer.setVisible(isVisible());
1028
                //        clonedLayer.setISpatialIndex(getISpatialIndex());
1029
                clonedLayer.setName(getName());
1030
                clonedLayer.setCoordTrans(getCoordTrans());
1031

    
1032
                clonedLayer.setLegend((IVectorLegend)getLegend().cloneLegend());
1033

    
1034
                clonedLayer.setIsLabeled(isLabeled());
1035
                ILabelingStrategy labelingStrategy=getLabelingStrategy();
1036
        if (labelingStrategy!=null) {
1037
                        clonedLayer.setLabelingStrategy(labelingStrategy);
1038
                }
1039

    
1040
                return clonedLayer;
1041
        }
1042

    
1043

    
1044
        protected boolean isOnePoint(AffineTransform graphicsTransform, ViewPort viewPort, double dpi, CartographicSupport csSym, Geometry geom, int[] xyCoords) {
1045
                return isOnePoint(graphicsTransform, viewPort, geom, xyCoords) && csSym.getCartographicSize(viewPort, dpi, geom) <= 1;
1046
        }
1047

    
1048
        private boolean isOnePoint(AffineTransform graphicsTransform, ViewPort viewPort, Geometry geom, int[] xyCoords) {
1049
                boolean onePoint = false;
1050
                int type=geom.getType();
1051
                if (type == Geometry.TYPES.NULL) {
1052
                        return false;
1053
                }
1054
                if (type!=Geometry.TYPES.POINT && type!=Geometry.TYPES.MULTIPOINT) {
1055

    
1056
                        Envelope geomBounds = geom.getEnvelope();
1057

    
1058
                        ICoordTrans ct = getCoordTrans();
1059

    
1060
                        // Se supone que la geometria ya esta reproyectada
1061
                        // if (ct!=null) {
1062
                        // // geomBounds = ct.getInverted().convert(geomBounds);
1063
                        // geomBounds = geomBounds.convert(ct);
1064
                        // }
1065

    
1066
                        double dist1Pixel = viewPort.getDist1pixel();
1067

    
1068
                        onePoint = (geomBounds.getLength(0)  <= dist1Pixel
1069
                                        && geomBounds.getLength(1) <= dist1Pixel);
1070

    
1071
                        if (onePoint) {
1072
                                // avoid out of range exceptions
1073
                                org.gvsig.fmap.geom.primitive.Point p;
1074
                                try {
1075
                                        p = geomManager.createPoint(geomBounds.getMinimum(0), geomBounds.getMinimum(1), SUBTYPES.GEOM2D);
1076
                                        p.transform(viewPort.getAffineTransform());
1077
                                        p.transform(graphicsTransform);
1078
                                        xyCoords[0] = (int) p.getX();
1079
                                        xyCoords[1] = (int) p.getY();
1080
                                } catch (org.gvsig.fmap.geom.exception.CreateGeometryException e) {
1081
                                        logger.error("Error creating a point", e);
1082
                                }
1083

    
1084
                        }
1085

    
1086
                }
1087
                return onePoint;
1088
        }
1089
        /*
1090
         * jaume. Stuff from ILabeled.
1091
         */
1092
        private boolean isLabeled;
1093
        protected ILabelingStrategy strategy;
1094

    
1095
        public boolean isLabeled() {
1096
                return isLabeled;
1097
        }
1098

    
1099
        public void setIsLabeled(boolean isLabeled) {
1100
                this.isLabeled = isLabeled;
1101
        }
1102

    
1103
        public ILabelingStrategy getLabelingStrategy() {
1104
                return strategy;
1105
        }
1106

    
1107
        public void setLabelingStrategy(ILabelingStrategy strategy) {
1108
                this.strategy = strategy;
1109
                
1110
                if (strategy == null) {
1111
                        return;
1112
                }
1113
                
1114
                try {
1115
                        strategy.setLayer(this);
1116
                } catch (ReadException e) {
1117
                        logger.error("While setting layer to ILabelingStrategy: " + e.getMessage());
1118
                }
1119

    
1120
        }
1121

    
1122
        public void drawLabels(BufferedImage image, Graphics2D g, ViewPort viewPort,
1123
                        Cancellable cancel, double scale, double dpi) throws ReadException {
1124
                if (strategy!=null && isWithinScale(scale)) {
1125
                        strategy.draw(image, g, viewPort, cancel, dpi);
1126
                }
1127
        }
1128

    
1129
        public void printLabels(Graphics2D g, ViewPort viewPort,
1130
                        Cancellable cancel, double scale,
1131
                        PrintAttributes properties) throws ReadException {
1132
                if (strategy != null) {
1133
                        strategy.print(g, viewPort, cancel, properties);
1134
                }
1135
        }
1136
        //M?todos para el uso de HyperLinks en capas FLyerVect
1137

    
1138
        /**
1139
         * Return true, because a Vectorial Layer supports HyperLink
1140
         */
1141
        public boolean allowLinks()
1142
        {
1143
                return true;
1144
        }
1145

    
1146
        /**
1147
         * Returns an instance of AbstractLinkProperties that contains the information
1148
         * of the HyperLink
1149
         * @return Abstra
1150
         */
1151
        public AbstractLinkProperties getLinkProperties()
1152
        {
1153
                return linkProperties;
1154
        }
1155

    
1156
        /**
1157
         * Provides an array with URIs. Returns one URI by geometry that includes the point
1158
         * in its own geometry limits with a allowed tolerance.
1159
         * @param layer, the layer
1160
         * @param point, the point to check that is contained or not in the geometries in the layer
1161
         * @param tolerance, the tolerance allowed. Allowed margin of error to detect if the  point
1162
         *                 is contained in some geometries of the layer
1163
         * @return
1164
         * @throws ReadException
1165
         * @throws BehaviorException
1166
         */
1167
        public URI[] getLink(Point2D point, double tolerance) throws ReadException
1168
        {
1169
                //return linkProperties.getLink(this)
1170
                return linkProperties.getLink(this,point,tolerance);
1171
        }
1172

    
1173
        public void load() throws LoadLayerException {
1174
                super.load();
1175
        }
1176

    
1177
        public FeatureStore getFeatureStore() {
1178
                return (FeatureStore)getDataStore();
1179
        }
1180

    
1181
        public FeatureSet queryByPoint(Point2D mapPoint, double tol, FeatureType featureType) throws DataException {
1182
                GeometryManager manager = GeometryLocator.getGeometryManager();
1183
                org.gvsig.fmap.geom.primitive.Point center;
1184
                try {
1185
                        center = (org.gvsig.fmap.geom.primitive.Point)manager.create(TYPES.POINT, SUBTYPES.GEOM2D);
1186
                        center.setX(mapPoint.getX());
1187
                        center.setY(mapPoint.getY());
1188
                        Circle circle = (Circle)manager.create(TYPES.CIRCLE, SUBTYPES.GEOM2D);
1189
                        circle.setPoints(center, tol);
1190
                        return queryByGeometry(circle, featureType);
1191
                } catch (org.gvsig.fmap.geom.exception.CreateGeometryException e) {
1192
                        throw new CreateGeometryException(TYPES.CIRCLE, SUBTYPES.GEOM2D, e);
1193
                }
1194
        }
1195

    
1196

    
1197
        public FeatureSet queryByGeometry(Geometry geom, FeatureType featureType) throws DataException {
1198
                FeatureQuery featureQuery=featureStore.createFeatureQuery();
1199
                String geomName=featureStore.getDefaultFeatureType().getDefaultGeometryAttributeName();
1200
                featureQuery.setFeatureType(featureType);
1201
                IntersectsGeometryEvaluator iee=new IntersectsGeometryEvaluator(geom,getMapContext().getViewPort().getProjection(),featureStore.getDefaultFeatureType(),geomName);
1202
                featureQuery.setFilter(iee);
1203
                return getFeatureStore().getFeatureSet(featureQuery);
1204

    
1205
        }
1206

    
1207
        public FeatureSet queryByEnvelope(Envelope envelope, FeatureType featureType)
1208
        throws DataException {
1209
                return queryByEnvelope(envelope, featureType, null);
1210
        }
1211

    
1212
        public FeatureSet queryByEnvelope(Envelope envelope, FeatureType featureType, String[] names)
1213
        throws DataException {
1214
                FeatureQuery featureQuery=featureStore.createFeatureQuery();
1215
                if (names==null){
1216
                        featureQuery.setFeatureType(featureType);
1217
                }else{
1218
                        featureQuery.setAttributeNames(names);
1219
                        featureQuery.setFeatureTypeId(featureType.getId());
1220
                }
1221
                String geomName=featureStore.getDefaultFeatureType().getDefaultGeometryAttributeName();
1222
                ContainsEnvelopeEvaluator iee=new ContainsEnvelopeEvaluator(envelope,getMapContext().getViewPort().getProjection(),featureStore.getDefaultFeatureType(),geomName);
1223
                featureQuery.setFilter(iee);
1224
                return getFeatureStore().getFeatureSet(featureQuery);
1225

    
1226
        }
1227
        public Iterator getInfo(Point p, double tolerance, Cancellable cancel) throws LoadLayerException, DataException {
1228
                Point2D pReal = this.getMapContext().getViewPort().toMapPoint(p);
1229
                FeatureSet featureCollection=null;
1230
                try {
1231
                        featureCollection = queryByPoint(pReal, tolerance, getFeatureStore().getDefaultFeatureType());
1232
                } catch (DataException e) {
1233
                        // TODO Auto-generated catch block
1234
                        e.printStackTrace();
1235
                }
1236
//                VectorialXMLItem[] item = new VectorialXMLItem[1];
1237
//                item[0] = new VectorialXMLItem(featureCollection, this);
1238

    
1239
                return featureCollection.iterator();
1240
        }
1241

    
1242
        public void legendCleared(LegendClearEvent event) {
1243
                // this.updateDrawVersion(); TODO
1244
                LegendChangedEvent e = LegendChangedEvent.createLegendChangedEvent(
1245
                                legend, legend);
1246
                this.callLegendChanged(e);
1247
        }
1248

    
1249
        public boolean symbolChanged(SymbolLegendEvent e) {
1250
                LegendChangedEvent ev = LegendChangedEvent.createLegendChangedEvent(
1251
                                legend, legend);
1252
                this.callLegendChanged(ev);
1253
                return true;
1254
        }
1255

    
1256
        public void update(Observable observable, Object notification) {
1257
                if (observable.equals(this.featureStore)) {
1258
                        if (notification instanceof FeatureStoreNotification) {
1259
                                FeatureStoreNotification event = (FeatureStoreNotification) notification;
1260
                                if (event.getType() == FeatureStoreNotification.AFTER_CANCELEDITING
1261
                                                || event.getType() == FeatureStoreNotification.AFTER_DELETE
1262
                                                || event.getType() == FeatureStoreNotification.AFTER_UNDO
1263
                                                || event.getType() == FeatureStoreNotification.AFTER_REDO
1264
                                                || event.getType() == FeatureStoreNotification.AFTER_REFRESH
1265
                                                || event.getType() == FeatureStoreNotification.AFTER_UPDATE
1266
                                                || event.getType() == FeatureStoreNotification.AFTER_UPDATE_TYPE
1267
                                                || event.getType() == FeatureStoreNotification.SELECTION_CHANGE
1268
                                                || event.getType() == FeatureStoreNotification.AFTER_INSERT) {
1269
                                        this.updateDrawVersion();
1270

    
1271
                                } else if (event.getType() == FeatureStoreNotification.AFTER_FINISHEDITING
1272
                                                || event.getType() == FeatureStoreNotification.TRANSFORM_CHANGE
1273
                                                || event.getType() == FeatureStoreNotification.RESOURCE_CHANGED) {
1274
                                        this.setAvailable(false);
1275

    
1276
                                        //                                        try {
1277
                                        //                                                reload();
1278
                                        //                                        } catch (ReloadLayerException e) {
1279
                                        //                                                this.setAvailable(false);
1280
                                        //                                        }
1281
                                }
1282

    
1283
                        }
1284

    
1285
                }
1286
                // Only if its an event from our own legend
1287
                else if (observable == getLegend()) {
1288
                        if (notification instanceof FeatureDrawnNotification) {
1289
                                Geometry geometry = ((FeatureDrawnNotification) notification)
1290
                                                .getDrawnGeometry();
1291
                                spatialCache.insert(geometry.getEnvelope(), geometry);
1292
                        }
1293
                }
1294

    
1295
        }
1296

    
1297
        /*
1298
         * (non-Javadoc)
1299
         *
1300
         * @see org.gvsig.metadata.Metadata#getMetadataChildren()
1301
         */
1302
        public Set getMetadataChildren() {
1303
                Set ret = new TreeSet();
1304
                ret.add(this.featureStore);
1305
                return ret;
1306
        }
1307

    
1308
        /*
1309
         * (non-Javadoc)
1310
         *
1311
         * @see org.gvsig.metadata.Metadata#getMetadataID()
1312
         */
1313
        public Object getMetadataID() {
1314
                return "Layer(" + this.getName() + "):"
1315
                + this.featureStore.getMetadataID();
1316
        }
1317

    
1318
        /*
1319
         * (non-Javadoc)
1320
         *
1321
         * @see org.gvsig.metadata.Metadata#getMetadataName()
1322
         */
1323
        public String getMetadataName() {
1324
                return "Layer '" + this.getName() + "':"
1325
                + this.featureStore.getMetadataName();
1326
        }
1327

    
1328
        public GeometryType getTypeVectorLayer() throws DataException, LocatorException, GeometryTypeNotSupportedException, GeometryTypeNotValidException {
1329
                // FIXME Esto deberia de pedirse a FType!!!!
1330
                FeatureStore fs = this.getFeatureStore();
1331
                FeatureType fType = fs.getDefaultFeatureType();
1332
                FeatureAttributeDescriptor attr = fType.getAttributeDescriptor(fType
1333
                                .getDefaultGeometryAttributeIndex());
1334
                GeometryType geomType = GeometryLocator.getGeometryManager()
1335
                                .getGeometryType(attr.getGeometryType(),
1336
                                                attr.getGeometrySubType());
1337
                return geomType;
1338
        }
1339

    
1340
        public static void registerPersistent() {
1341
                
1342
                DynObjectManager dynMan = ToolsLocator.getDynObjectManager();
1343
                DynClass dynClass = dynMan.createDynClass(
1344
                "FLyrVect_Persistent",
1345
                "FLyrVect Persistent definition");
1346
                
1347
                FLyrDefault.registerPersistent();
1348
                dynClass.extend("FLyrDefault_Persistent");
1349

    
1350
                dynClass.addDynFieldSingle("legend", DataTypes.PERSISTENT, null, true, true);
1351
                dynClass.addDynFieldSingle("featureStore", DataTypes.PERSISTENT, null, true, true);
1352
                dynClass.addDynFieldSingle("isLabeled", DataTypes.BOOLEAN, null, true, true);
1353
                dynClass.addDynFieldSingle("bHasJoin", DataTypes.BOOLEAN, null, true, true);
1354
                dynClass.addDynFieldSingle("typeShape", DataTypes.INT, null, true, true);
1355
                
1356
                dynMan.add(dynClass);
1357

    
1358
                ToolsLocator.getPersistenceManager().registerClass(FLyrDefault.class, dynClass);        
1359
        }
1360

    
1361
}