Statistics
| Revision:

gvsig-raster / org.gvsig.raster / trunk / org.gvsig.raster / org.gvsig.raster.lib / org.gvsig.raster.lib.impl / src / main / java / org / gvsig / raster / impl / store / DefaultRasterStore.java @ 2215

History | View | Annotate | Download (51.2 KB)

1
/* gvSIG. Geographic Information System of the Valencian Government
2
 *
3
 * Copyright (C) 2007-2008 Infrastructures and Transports Department
4
 * of the Valencian Government (CIT)
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 2
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 */
22
package org.gvsig.raster.impl.store;
23

    
24
import java.awt.Image;
25
import java.awt.geom.AffineTransform;
26
import java.awt.geom.Point2D;
27
import java.awt.geom.Rectangle2D;
28
import java.io.File;
29
import java.util.ArrayList;
30
import java.util.Collection;
31
import java.util.List;
32

    
33
import org.cresques.cts.IProjection;
34
import org.gvsig.compat.net.ICancellable;
35
import org.gvsig.fmap.crs.CRSFactory;
36
import org.gvsig.fmap.dal.DALLocator;
37
import org.gvsig.fmap.dal.DataStoreParameters;
38
import org.gvsig.fmap.dal.coverage.RasterLibrary;
39
import org.gvsig.fmap.dal.coverage.RasterLocator;
40
import org.gvsig.fmap.dal.coverage.RasterManager;
41
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
42
import org.gvsig.fmap.dal.coverage.datastruct.BandList;
43
import org.gvsig.fmap.dal.coverage.datastruct.DatasetBand;
44
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
45
import org.gvsig.fmap.dal.coverage.datastruct.GeoPointList;
46
import org.gvsig.fmap.dal.coverage.datastruct.NoData;
47
import org.gvsig.fmap.dal.coverage.datastruct.Params;
48
import org.gvsig.fmap.dal.coverage.exception.BandAccessException;
49
import org.gvsig.fmap.dal.coverage.exception.BandNotFoundInListException;
50
import org.gvsig.fmap.dal.coverage.exception.CloneException;
51
import org.gvsig.fmap.dal.coverage.exception.FileNotExistsException;
52
import org.gvsig.fmap.dal.coverage.exception.FileNotOpenException;
53
import org.gvsig.fmap.dal.coverage.exception.FilterManagerException;
54
import org.gvsig.fmap.dal.coverage.exception.FilterTypeException;
55
import org.gvsig.fmap.dal.coverage.exception.InfoByPointException;
56
import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
57
import org.gvsig.fmap.dal.coverage.exception.InvalidSourceException;
58
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
59
import org.gvsig.fmap.dal.coverage.exception.OperationNotSupportedException;
60
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
61
import org.gvsig.fmap.dal.coverage.exception.ROIException;
62
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
63
import org.gvsig.fmap.dal.coverage.exception.RmfSerializerException;
64
import org.gvsig.fmap.dal.coverage.exception.TimeException;
65
import org.gvsig.fmap.dal.coverage.grid.RasterFilter;
66
import org.gvsig.fmap.dal.coverage.grid.RasterFilterList;
67
import org.gvsig.fmap.dal.coverage.grid.RasterFilterListManager;
68
import org.gvsig.fmap.dal.coverage.grid.render.Render;
69
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
70
import org.gvsig.fmap.dal.coverage.store.parameter.MultiDimensionalStoreParameters;
71
import org.gvsig.fmap.dal.coverage.store.parameter.RasterDataParameters;
72
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
73
import org.gvsig.fmap.dal.coverage.store.props.ColorTable;
74
import org.gvsig.fmap.dal.coverage.store.props.HistogramComputer;
75
import org.gvsig.fmap.dal.coverage.store.props.Metadata;
76
import org.gvsig.fmap.dal.coverage.store.props.Statistics;
77
import org.gvsig.fmap.dal.coverage.store.props.TimeSeries;
78
import org.gvsig.fmap.dal.coverage.store.props.Transparency;
79
import org.gvsig.fmap.dal.exception.InitializeException;
80
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
81
import org.gvsig.fmap.dal.raster.spi.CoverageStoreProvider;
82
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
83
import org.gvsig.fmap.dal.spi.DataStoreProvider;
84
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
85
import org.gvsig.fmap.geom.GeometryLocator;
86
import org.gvsig.fmap.geom.exception.CreateEnvelopeException;
87
import org.gvsig.fmap.geom.primitive.Envelope;
88
import org.gvsig.raster.cache.tile.Tile;
89
import org.gvsig.raster.cache.tile.TileCacheLocator;
90
import org.gvsig.raster.cache.tile.TileCacheManager;
91
import org.gvsig.raster.cache.tile.exception.TileGettingException;
92
import org.gvsig.raster.impl.DefaultRasterManager;
93
import org.gvsig.raster.impl.buffer.DefaultRasterQuery;
94
import org.gvsig.raster.impl.buffer.cache.RasterReadOnlyBuffer;
95
import org.gvsig.raster.impl.datastruct.BandListImpl;
96
import org.gvsig.raster.impl.datastruct.DatasetBandImpl;
97
import org.gvsig.raster.impl.datastruct.ExtentImpl;
98
import org.gvsig.raster.impl.grid.roi.VectorialROIsReader;
99
import org.gvsig.raster.impl.provider.DefaultRasterProvider;
100
import org.gvsig.raster.impl.provider.RasterProvider;
101
import org.gvsig.raster.impl.provider.TiledRasterProvider;
102
import org.gvsig.raster.impl.store.properties.MultiDataStoreMetadata;
103
import org.gvsig.raster.roi.ROI;
104
import org.gvsig.raster.roi.ROIReader;
105
import org.gvsig.raster.util.persistence.PersistencyFilterParam;
106
import org.gvsig.timesupport.Interval;
107
import org.gvsig.timesupport.Time;
108
import org.gvsig.tools.ToolsLocator;
109
import org.gvsig.tools.dynobject.DynStruct;
110
import org.gvsig.tools.persistence.PersistenceManager;
111
import org.gvsig.tools.persistence.PersistentState;
112
import org.gvsig.tools.persistence.exception.PersistenceException;
113
import org.slf4j.Logger;
114
import org.slf4j.LoggerFactory;
115

    
116
/**
117
 * Default data store for raster
118
 *
119
 * @author Nacho Brodin (nachobrodin@gmail.com)
120
 */
121
public class DefaultRasterStore extends AbstractRasterDataStore {
122
        public static final String              PERSISTENT_NAME        = "DefaultRasterStore_Persistent";
123
    public static final String              PERSISTENT_DESCRIPTION = "DefaultRasterStore Persistent";
124
    private static final Logger             logger                 = LoggerFactory.getLogger(DefaultRasterStore.class);
125
    
126
        protected RasterProvider                provider               = null;
127
        protected BandListImpl                  bandList               = new BandListImpl();
128
        protected Metadata                      metadata               = null;
129
        private RasterManager                   rManager               = RasterLocator.getManager();
130
        
131
        /*
132
         * TODO: Refactoring de ROIS 
133
         * Una capa r?ster deber?a poder tener ROIs de tipo r?ster y de tipo vectorial asociados. Adem?s
134
         * debe poder tener una lista de estos por lo que ser?a necesario un interfaz en la que se pueda
135
         * seleccionar la capa de ROIs a utilizar.
136
         * 
137
         * Por otro lado, las ROIs deben ser del proveedor de datos. Este con tendr? una lista de estos.
138
         * Las ROIs deber?an modelarse como proveedores de datos de tipo r?ster o de tipo vectorial, ya que 
139
         * tener una lista de geometr?as en memoria como hasta ahora puede ser muy poco eficiente en caso
140
         * de que la lista de ROIs sea muy grande. Adem?s deber?a optimizarse el acceso isInside para que las
141
         * operaciones con ROIs asociados sean lo m?s r?pidas posible.
142
         */
143
        private List<ROI>               rois                           = null;
144
        
145
        /**
146
         * Flag que fuerza al buffer en memoria
147
         */
148
        protected boolean                       forceToMemory = false;
149
        
150
        public DefaultRasterStore() {
151
                super();
152
        }
153
        
154
        public void reload() {
155
                provider.reload();
156
        }
157

    
158
        public void setProvider(RasterProvider provider) {
159
                this.provider = provider;
160
                parameters = (DataStoreParameters)provider.getDataParameters();
161
                bandList.clear();
162
                for(int i = 0; i < provider.getBandCount(); i++) {
163
                        try {
164
                                int dataType = provider.getDataType()[i];
165
                                DatasetBand band = new DatasetBandImpl(provider.getURIByBand(i), 
166
                                                                                                        provider.getBandPositionByProvider(i), 
167
                                                                                                        dataType, 
168
                                                                                                        provider.getBandCount());
169
                                bandList.addBand(band, i);
170
                        } catch(BandNotFoundInListException ex) {
171
                                //No a?adimos la banda
172
                        }
173
                }
174
        }
175
        
176
        public void intializePhase2(DataStoreProvider provider)
177
                        throws InitializeException {
178
                setProvider((RasterProvider)provider);
179
        }
180
        
181
        public void setParameters(DataStoreParameters p) {
182
                this.parameters = p;
183
        }
184
        
185
        public void setProvider(CoverageStoreProvider prov) {
186
                if(prov instanceof RasterProvider)
187
                        setProvider((RasterProvider)prov);
188
        }
189
        
190
        public String getName() {
191
                if(provider != null)
192
                        return provider.getURI();
193
                return null;
194
        }
195
        
196
        public boolean needEnhanced() {
197
                if(provider != null)
198
                        return provider.needEnhanced();
199
                return false;
200
        }
201

    
202
        /**
203
         * Inicializa el buffer a valores NoData
204
         * @param raster Buffer a inicializar
205
         * @param bandList Lista de bandas
206
         */
207
        private void initBufferToNoData(Buffer buf, BandList bandList) {
208
                for(int i = 0; i < bandList.getDrawableBandsCount(); i++) {
209
                        switch(getDataType()[0]) {
210
                        case Buffer.TYPE_BYTE:buf.assign(i, 
211
                                        buf.getNoDataValue().isDefined() ? buf.getNoDataValue().getValue().byteValue() : RasterLibrary.defaultByteNoDataValue);
212
                        break;
213
                        case Buffer.TYPE_SHORT:buf.assign(i, 
214
                                        buf.getNoDataValue().isDefined() ? buf.getNoDataValue().getValue().shortValue() : RasterLibrary.defaultShortNoDataValue);
215
                        break;
216
                        case Buffer.TYPE_INT:buf.assign(i, 
217
                                        buf.getNoDataValue().isDefined() ? buf.getNoDataValue().getValue().intValue() : RasterLibrary.defaultIntegerNoDataValue);
218
                        break;
219
                        case Buffer.TYPE_FLOAT:buf.assign(i, 
220
                                        buf.getNoDataValue().isDefined() ? buf.getNoDataValue().getValue().floatValue() : RasterLibrary.defaultFloatNoDataValue);
221
                        break;
222
                        case Buffer.TYPE_DOUBLE:buf.assign(i, 
223
                                        buf.getNoDataValue().isDefined() ? buf.getNoDataValue().getValue().doubleValue() : RasterLibrary.defaultDoubleNoDataValue);
224
                        break;
225
                        }
226
                }
227
        }
228
        
229
        public boolean isTiled() {
230
                return provider.isTiled();
231
        }
232
        
233
        public boolean isMosaic() {
234
                return provider.isMosaic();
235
        }
236
        
237
        public Buffer getWindowWithoutResampling(DefaultRasterQuery q)
238
                throws InvalidSetViewException, ProcessInterruptedException, RasterDriverException {
239
                
240
                //El incremento o decremento de las X e Y depende de los signos de rotaci?n y escala en la matriz de transformaci?n. Por esto
241
                //tenemos que averiguar si lrx es x + w o x -w, asi como si lry es y + h o y - h
242
                Extent ext = getExtent();
243
                Point2D pInit = provider.rasterToWorld(new Point2D.Double(0, 0));
244
                Point2D pEnd = provider.rasterToWorld(new Point2D.Double((int)getWidth(), (int)getHeight()));
245
                double wRaster = Math.abs(pEnd.getX() - pInit.getX());
246
                double hRaster = Math.abs(pEnd.getY() - pInit.getY());
247
                double lrx = (((int)(ext.getULX() - wRaster)) == ((int)ext.getLRX())) ? (q.getX() - q.getW()) : (q.getX() + q.getW());
248
                double lry = (((int)(ext.getULY() - hRaster)) == ((int)ext.getLRY())) ? (q.getY() - q.getH()) : (q.getY() + q.getH());
249

    
250
                //Extent selectedExtent = new Extent(ulx, uly, lrx, lry);
251

    
252
                //Leemos pixels completos aunque el valor obtenido sea decimal. Esto se consigue redondeando
253
                //por arriba el m?s alto y por abajo el menor y luego restandolos
254

    
255
                Point2D p1 = provider.worldToRaster(new Point2D.Double(q.getX(), q.getY()));
256
                Point2D p2 = provider.worldToRaster(new Point2D.Double(lrx, lry));
257
                adjustPoints(p1, p2);
258
                int width = (int)Math.abs(Math.ceil(p2.getX()) - Math.floor(p1.getX()));
259
                int height = (int)Math.abs(Math.floor(p1.getY()) - Math.ceil(p2.getY()));
260

    
261
                //Ajustamos por si nos hemos salido del raster
262
                if(((int)(p1.getX() + width)) > getWidth())
263
                        width = (int)(getWidth() - p1.getX());
264
                if(((int)(p1.getY() + height)) > getHeight())
265
                        height = (int)(getHeight() - p1.getY());
266

    
267
                if (p1.getX() < 0)
268
                        p1.setLocation(0, p1.getY());
269
                if (p1.getY() < 0)
270
                        p1.setLocation(p1.getX(), 0);
271
                if (p2.getX() > getWidth())
272
                        p2.setLocation(getWidth(), p2.getY());
273
                if (p2.getY() > getHeight())
274
                        p2.setLocation(p2.getX(), getHeight());
275

    
276
                int mallocNBands = 0;
277
                if(bandList.getDrawableBands() != null)
278
                        mallocNBands = bandList.getDrawableBands().length;
279
                else
280
                        mallocNBands = bandList.getDrawableBandsCount();
281

    
282
                //Buffer ReadOnly
283

    
284
                if(isReadOnly()) {
285
                        Buffer rb = DefaultRasterManager.getInstance().createReadOnlyBuffer(getDataType()[0], width, height, getBandCount());
286
                        if(rb instanceof RasterReadOnlyBuffer) {
287
                                try {
288
                                        ((RasterReadOnlyBuffer)rb).setBufferParams(this, 
289
                                                        (int)p1.getX(), (int)p1.getY(), (int)p2.getX(), (int)p2.getY(), bandList);
290
                                } catch (FileNotExistsException e) {
291
                                        //Esto no debe darse ya que se comprueba al hacer el open.
292
                                        return null;
293
                                } catch (NotSupportedExtensionException e) {
294
                                        //Esto no debe darse ya que se comprueba al hacer el open
295
                                        return null;
296
                                }
297
                                return rb;
298
                        }
299
                }
300
                
301
                //Si hemos redondeado los pixeles de la petici?n (p1 y p2) por arriba y por abajo deberemos calcular un extent mayor
302
                //equivalente a los pixeles redondeados.
303
                Point2D wc1 = provider.rasterToWorld(new Point2D.Double(Math.floor(p1.getX()), Math.floor(p1.getY())));
304
                Point2D wc2 = provider.rasterToWorld(new Point2D.Double(Math.ceil(p2.getX()), Math.ceil(p2.getY())));
305

    
306
                //Buffer RW
307
                Buffer raster = null;
308
                
309
                if(forceToMemory) //Fuerza siempre buffer en memoria
310
                        raster = DefaultRasterManager.getInstance().createMemoryBuffer(getDataType()[0], width, height, mallocNBands, true);
311
                else
312
                        raster = DefaultRasterManager.getInstance().createBuffer(getDataType()[0], width, height, mallocNBands, true);
313

    
314
                if(!q.isAdjustToExtent())
315
                         initBufferToNoData(raster, bandList);
316
                
317
                q.setAreaOfInterest(wc1.getX(), wc1.getY(), Math.abs(wc2.getX() - wc1.getX()), Math.abs(wc2.getY() - wc1.getY()));
318
                q.setBandList(bandList);
319
                q.setBuffer(raster);
320
                raster = ((DefaultRasterProvider)provider).getDataSet(q);
321

    
322
                return raster;
323
        }
324
        
325
        private void adjustPoints(Point2D ul, Point2D lr) {
326
                double a = (ul.getX() - (int)ul.getX());
327
                double b = (ul.getY() - (int)ul.getY());
328
                ul.setLocation(        (a > 0.99 || a < 0.005) ? Math.round(ul.getX()) : ul.getX(), 
329
                                                (b > 0.99 || b < 0.005) ? Math.round(ul.getY()) : ul.getY());
330
                lr.setLocation(        (a > 0.99 || a < 0.005) ? Math.round(lr.getX()) : lr.getX(), 
331
                                                (b > 0.99 || b < 0.005) ? Math.round(lr.getY()) : lr.getY());
332
        }
333
        
334
        public Buffer getWindowWithResampling(DefaultRasterQuery q)
335
                throws InvalidSetViewException, ProcessInterruptedException, RasterDriverException {
336

    
337
                Point2D p1 = worldToRaster(new Point2D.Double(q.getBBox().getULX(), q.getBBox().getULY()));
338
                Point2D p2 = worldToRaster(new Point2D.Double(q.getBBox().getLRX(), q.getBBox().getLRY()));;
339
                
340
                if(p1.getX() > p2.getX())
341
                        p1.setLocation(p1.getX() - 1, p1.getY());
342
                else
343
                        p2.setLocation(p2.getX() - 1, p2.getY());
344
                
345
                if(p1.getY() > p2.getY())
346
                        p1.setLocation(p1.getX(), p1.getY() - 1);
347
                else
348
                        p2.setLocation(p2.getX(), p2.getY() - 1);
349
                
350
                if(        ((int)p1.getX()) < 0 || ((int)p2.getX()) > getWidth() ||
351
                                ((int)p2.getY()) > getHeight() || ((int)p2.getY()) < 0)
352
                                throw new InvalidSetViewException("");
353

    
354
                int mallocNBands = 0;
355
                if(bandList.getDrawableBands() != null)
356
                        mallocNBands = bandList.getDrawableBands().length;
357
                else
358
                        mallocNBands = bandList.getDrawableBandsCount();
359

    
360
                //Buffer ReadOnly
361

    
362
                if(isReadOnly()) {
363
                        Buffer rb = DefaultRasterManager.getInstance().createReadOnlyBuffer(getDataType()[0], q.getBufWidth(), q.getBufHeight(), getBandCount());
364
                        if(rb instanceof RasterReadOnlyBuffer) {
365
                                try {
366
                                        ((RasterReadOnlyBuffer)rb).setBufferParams(this, 
367
                                                        (int)p1.getX(), (int)p1.getY(), (int)p2.getX(), (int)p2.getY(), bandList);
368
                                } catch (FileNotExistsException e) {
369
                                        //Esto no debe darse ya que se comprueba al hacer el open.
370
                                        return null;
371
                                } catch (NotSupportedExtensionException e) {
372
                                        //Esto no debe darse ya que se comprueba al hacer el open
373
                                        return null;
374
                                }
375
                                return rb;
376
                        }
377
                }
378

    
379
                double ulx = q.getBBox().getULX();
380
                double uly = q.getBBox().getULY();
381
                double lrx = q.getBBox().getLRX();
382
                double lry = q.getBBox().getLRY();
383
                
384
                //Buffer RW
385
                Buffer raster = null;
386
                
387
                if(forceToMemory) //Fuerza siempre buffer en memoria
388
                        raster = DefaultRasterManager.getInstance().createMemoryBuffer(getDataType()[0], q.getBufWidth(), q.getBufHeight(), mallocNBands, true);
389
                else
390
                        raster = DefaultRasterManager.getInstance().createBuffer(getDataType()[0], q.getBufWidth(), q.getBufHeight(), mallocNBands, true);
391
                
392
                Extent ex = rManager.getDataStructFactory().createExtent(ulx, uly, lrx, lry);
393
                 
394
                q.setBBox(ex);
395
                q.setBandList(bandList);
396
                q.setBuffer(raster);
397
                raster = ((DefaultRasterProvider)provider).getDataSet(q);
398

    
399
                return raster;
400
        }
401

    
402
        public Buffer getWindowWC(DefaultRasterQuery q)
403
                throws InvalidSetViewException, ProcessInterruptedException, RasterDriverException {
404
                
405
                if(q.getBufWidth() > 0 && q.getBufHeight() > 0)
406
                        return getWindowWithResampling(q);
407
                
408
                //Leemos pixels completos aunque el valor obtenido sea decimal. Esto se consigue redondeando
409
                //por arriba el m?s alto y por abajo el menor y luego restandolos
410

    
411
                Point2D p1 = provider.worldToRaster(new Point2D.Double(q.getBBox().getULX(), q.getBBox().getULY()));
412
                Point2D p2 = provider.worldToRaster(new Point2D.Double(q.getBBox().getLRX(), q.getBBox().getLRY()));
413

    
414
                //Para el valor mayor redondeamos por arriba. Para el valor menor redondeamos por abajo.
415
                double p1X = (p1.getX() > p2.getX()) ? Math.ceil(p1.getX()) : Math.floor(p1.getX());
416
                double p1Y = (p1.getY() > p2.getY()) ? Math.ceil(p1.getY()) : Math.floor(p1.getY());
417
                double p2X = (p2.getX() > p1.getX()) ? Math.ceil(p2.getX()) : Math.floor(p2.getX());
418
                double p2Y = (p2.getY() > p1.getY()) ? Math.ceil(p2.getY()) : Math.floor(p2.getY());
419

    
420
                int width = (int)Math.abs(p1X - p2X);
421
                int height = (int)Math.abs(p1Y - p2Y);
422

    
423
                //Ajustamos por si nos hemos salido del raster
424
                if(((int)(Math.min(p1X, p2X) + width)) > getWidth())
425
                        width = (int)(getWidth() - Math.min(p1X, p2X));
426
                if(((int)(Math.min(p1Y, p2Y) + height)) > getHeight())
427
                        height = (int)(getHeight() - Math.min(p1Y, p2Y));
428

    
429
                if (p1X < 0)
430
                        p1X = 0;
431
                if (p1Y < 0)
432
                        p1Y = 0;
433
                if (p2X > getWidth())
434
                        p2X = getWidth();
435
                if (p2Y > getHeight())
436
                        p2Y = getHeight();
437

    
438
                int mallocNBands = 0;
439
                if(bandList.getDrawableBands() != null)
440
                        mallocNBands = bandList.getDrawableBands().length;
441
                else
442
                        mallocNBands = bandList.getDrawableBandsCount();
443

    
444
                //Buffer ReadOnly
445

    
446
                if(isReadOnly()) {
447
                        Buffer rb = DefaultRasterManager.getInstance().createReadOnlyBuffer(getDataType()[0], width, height, getBandCount());
448
                        if(rb instanceof RasterReadOnlyBuffer) {
449
                                try {
450
                                        ((RasterReadOnlyBuffer)rb).setBufferParams(this, 
451
                                                        (int)p1.getX(), (int)p1.getY(), (int)p2.getX(), (int)p2.getY(), bandList);
452
                                } catch (FileNotExistsException e) {
453
                                        //Esto no debe darse ya que se comprueba al hacer el open.
454
                                        return null;
455
                                } catch (NotSupportedExtensionException e) {
456
                                        //Esto no debe darse ya que se comprueba al hacer el open
457
                                        return null;
458
                                }
459
                                return rb;
460
                        }
461
                }
462

    
463
                //Buffer RW
464
                Buffer raster = null;
465
                
466
                //Si hemos redondeado los pixeles de la petici?n (p1 y p2) por arriba y por abajo deberemos calcular un extent mayor
467
                //equivalente a los pixeles redondeados.
468
                Point2D wc1 = provider.rasterToWorld(new Point2D.Double(p1X, p1Y));
469
                Point2D wc2 = provider.rasterToWorld(new Point2D.Double(p2X, p2Y));
470
                
471
                if(forceToMemory) //Fuerza siempre buffer en memoria
472
                        raster = DefaultRasterManager.getInstance().createMemoryBuffer(getDataType()[0], width, height, mallocNBands, true);
473
                else
474
                        raster = DefaultRasterManager.getInstance().createBuffer(getDataType()[0], width, height, mallocNBands, true);
475
                
476
                Extent ex = rManager.getDataStructFactory().createExtent(wc1.getX(), wc1.getY(), wc2.getX(), wc2.getY());
477
                q.setType(DefaultRasterQuery.TYPE_COORDS);
478
                q.setBBox(ex);
479
                q.setBandList(bandList);
480
                q.setBuffer(raster);
481
                raster = ((DefaultRasterProvider)provider).getDataSet(q);
482
                //raster = ((DefaultRasterProvider)provider).getWindow(ex, bandList, raster);
483

    
484
                return raster;
485
        }
486

    
487
        public void getWindowTiled(DefaultRasterQuery q)
488
                throws InvalidSetViewException, ProcessInterruptedException, RasterDriverException {
489
                if(isTiled()) { 
490
                        //Extent ex = q.getBBox();//new ExtentImpl(ulx, uly, lrx, lry);
491
                        q.setBandList(bandList);
492
                        ((DefaultRasterProvider)provider).getDataSet(q);
493
                        //((DefaultRasterProvider)provider).getWindow(ex, q.getBufWidth(), q.getBufHeight(), bandList, listener);
494
                        return;
495
                }
496
                                
497
                double[] step = null;
498
                Buffer buf = null;
499
                
500
                double ulx = q.getBBox().getULX();
501
                double uly = q.getBBox().getULY();
502
                double lrx = q.getBBox().getLRX();
503
                double lry = q.getBBox().getLRY();
504
                
505
                //Esta secci?n es para que no supersamplee el driver y pueda hacerse en el cliente
506
                if(!currentQuery.isSupersamplingLoadingBuffer()) {
507
                        //nWidth = ((adjustedDataExtent.width() * mDataset.getDataset(0).getWidth()) / mDataset.getExtentForRequest().width());
508
                        //nHeight = ((adjustedDataExtent.height() * mDataset.getDataset(0).getHeight()) / mDataset.getExtentForRequest().height());
509
                        Point2D p1 = worldToRaster(new Point2D.Double(ulx, uly));
510
                        Point2D p2 = worldToRaster(new Point2D.Double(lrx, lry));
511
                        nWidth = Math.abs(p1.getX() - p2.getX());
512
                        nHeight = Math.abs(p1.getY() - p2.getY());
513

    
514
                        if(q.getBufWidth() > Math.ceil(nWidth) && q.getBufHeight() > Math.ceil(nHeight)) {
515
                                step = calcSteps(ulx, uly, lrx, lry, nWidth, nHeight, q.getBufWidth(), q.getBufHeight());
516
                                buf = getWindowWC(q);
517
                        }
518
                } 
519
                
520
                if(buf == null) {
521
                        q.setAdjustToExtent(true);
522
                        buf = getWindowWithResampling(q);
523
                }
524
                
525
                buf.setDataExtent(new Rectangle2D.Double(ulx, uly, Math.abs(ulx - lrx), Math.abs(uly - lry)));
526
                
527
                Buffer alphaBand = null;
528
                if(currentQuery.getAlphaBandNumber() != -1) {
529
                        int[] drawableBands = bandList.getDrawableBands();
530
                        bandList.setDrawableBands(new int[]{currentQuery.getAlphaBandNumber(), -1, -1});
531
                        for(int i = 0; i < provider.getInternalProviderCount(); i++)
532
                                ((AbstractRasterDataParameters)((DefaultRasterProvider)provider.getInternalProvider(i)).getDataParameters()).setAlphaBand(currentQuery.getAlphaBandNumber());
533
                        q.setAdjustToExtent(true);
534
                        alphaBand = getWindowWithResampling(q);
535
                        bandList.setDrawableBands(drawableBands);
536
                }
537
                
538
                TileCacheManager m = TileCacheLocator.getManager();
539
                org.gvsig.raster.cache.tile.Tile t = m.createTile(-1, 0, 0);
540
                t.setData(new Object[]{buf, alphaBand});
541
                t.setUl(new Point2D.Double(ulx, uly));
542
                t.setLr(new Point2D.Double(lrx, lry));
543
                if(provider.getDataParameters() instanceof MultiDimensionalStoreParameters) {
544
                        MultiDimensionalStoreParameters par = (MultiDimensionalStoreParameters)provider.getDataParameters();
545
                        t.setVariable(par.getStringVariable());
546
                        t.setZ(par.getStringLevel());
547
                        t.setTimeInstant(par.getStringTime());
548
                }
549
                t.setDownloaderParams("AffineTransform", getAffineTransform());
550
                t.setDownloaderParams("Tiling", new Boolean(true));
551
                t.setDownloaderParams("Step", step);
552
                try {
553
                        q.getTileListener().tileReady(t);
554
                } catch (TileGettingException e) {
555
                        throw new RasterDriverException("Error getting a tile", e);
556
                }
557
                
558
                //listener.nextBuffer(buf, alphaBand, new ExtentImpl(ulx, uly, lrx, lry), this.getAffineTransform(), step, false);
559
                q.getTileListener().endReading();
560
        }
561
        
562
        public Tile getTile(DefaultRasterQuery q) throws TileGettingException {
563
                TiledRasterProvider tiledProv = ((TiledRasterProvider)provider);
564
                return tiledProv.getTile(q);
565
        }
566

    
567
        public Buffer getWindowPx(DefaultRasterQuery q)
568
                throws InvalidSetViewException, ProcessInterruptedException, RasterDriverException {
569
                step = null;
570
                if(q.getPixelX() < 0 || q.getPixelY() < 0 || q.getPixelW() > getWidth() || q.getPixelH() > getHeight())
571
                        throw new InvalidSetViewException("Out of image");
572
                
573
                q.setPixelX((q.getPixelX() < 0) ? 0 : q.getPixelX());
574
                q.setPixelY((q.getPixelY() < 0) ? 0 : q.getPixelY());
575
                q.setPixelW((q.getPixelW() > getWidth()) ? (int)getWidth() : q.getPixelW());
576
                q.setPixelH((q.getPixelH() > getHeight()) ? (int)getHeight() : q.getPixelH());
577

    
578
                dataExtent = new ExtentImpl(rasterToWorld(new Point2D.Double(q.getPixelX(), q.getPixelY())),
579
                                rasterToWorld(new Point2D.Double(q.getPixelX() + q.getPixelW(), q.getPixelY() + q.getPixelH())));
580
                
581
                if(        q.getType() == DefaultRasterQuery.TYPE_PX || 
582
                        q.getType() == DefaultRasterQuery.TYPE_ENTIRE || 
583
                        q.getBufWidth() <= 0 || q.getBufHeight() <= 0) {
584
                        q.setBufWidth(q.getPixelW());
585
                        q.setBufHeight(q.getPixelH());
586
                }
587

    
588
                //Buffer ReadOnly
589

    
590
                if(isReadOnly()) {
591
                        Buffer rb = DefaultRasterManager.getInstance().createReadOnlyBuffer(getDataType()[0], 
592
                                        q.getBufWidth(), q.getBufHeight(), getBandCount());
593
                        if(rb instanceof RasterReadOnlyBuffer) {
594
                                try {
595
                                        ((RasterReadOnlyBuffer)rb).setBufferParams((QueryableRaster)this, 
596
                                                        q.getPixelX(), 
597
                                                        q.getPixelY(), 
598
                                                        q.getPixelX() + q.getPixelW() - 1, 
599
                                                        q.getPixelY() + q.getPixelH() - 1, 
600
                                                        bandList);
601
                                } catch (FileNotExistsException e) {
602
                                        //Esto no debe darse ya que se comprueba al hacer el open.
603
                                        return null;
604
                                } catch (NotSupportedExtensionException e) {
605
                                        //Esto no debe darse ya que se comprueba al hacer el open
606
                                        return null;
607
                                }
608
                                return rb;
609
                        }
610
                }
611

    
612
                //Buffer RW
613
                Buffer raster = null;
614
                
615
                if(forceToMemory) //Fuerza siempre buffer en memoria
616
                        raster = DefaultRasterManager.getInstance().createMemoryBuffer(getDataType()[0], q.getBufWidth(), q.getBufHeight(), bandList.getDrawableBandsCount(), true);
617
                else
618
                        raster = DefaultRasterManager.getInstance().createBuffer(getDataType()[0], q.getBufWidth(), q.getBufHeight(), bandList.getDrawableBandsCount(), true);
619
                
620
                q.setBandList(bandList);
621
                q.setBuffer(raster);
622
                raster = ((DefaultRasterProvider)provider).getDataSet(q);
623
                //raster = ((DefaultRasterProvider)provider).getWindow(q.getPixelX(), q.getPixelY(), q.getPixelW(), q.getPixelH(), bandList, raster);
624

    
625
                return raster;
626
        }
627

    
628
        //******************************
629
        //Setters and Getters
630
        //******************************
631

    
632
        /**
633
         * Calcula el tama?o de los ficheros en disco
634
         * @return tama?o en bytes de todos los ficheros de la lista
635
         */
636
        public long getFileSize() {
637
                if(provider != null) {
638
                        long size = 0;
639
                        long[] fSize = provider.getFileSizeByProvider();
640
                        if(fSize != null && fSize.length > 0) {
641
                                for (int j = 0; j < fSize.length; j++) {
642
                                        size += fSize[j];        
643
                                }
644
                        }
645
                        return size;
646
                }
647
                return 0;
648
        }
649

    
650
        public double getHeight() {
651
                return provider.getHeight();
652
        }
653

    
654
        public double getWidth() {
655
                return provider.getWidth();
656
        }
657

    
658
        public double getCellSize() {
659
                try {
660
                        Extent e = getExtent();
661
                        double dCellsize = (e.getMax().getX() - e.getMin().getX() ) / getWidth();
662
                        return dCellsize;
663
                } catch (NullPointerException e) {
664
                        return 1;
665
                }
666
        }
667

    
668
        public int getBandCount() {
669
                return provider.getBandCount();
670
        }
671

    
672
        public int[] getDataType() {
673
                return provider.getDataType();
674
        }
675

    
676
        public BandList getBands() {
677
                return bandList;
678
        }
679

    
680
        /**
681
         * Obtiene la coordenada X m?nima de toda la lista
682
         * @return Coordenada X m?nima
683
         */
684
        public double getMinX() {
685
                return provider.getExtent().getMin().getX();
686
        }
687

    
688
        /**
689
         * Obtiene la coordenada Y m?nima de toda la lista
690
         * @return Coordenada Y m?nima
691
         */
692
        public double getMinY() {
693
                return provider.getExtent().getMin().getY();
694
        }
695

    
696
        /**
697
         * Obtiene la coordenada Y m?xima de toda la lista
698
         * @return Coordenada Y m?xima
699
         */
700
        public double getMaxX() {
701
                return provider.getExtent().getMax().getX();        }
702

    
703
        /**
704
         * Obtiene la coordenada Y m?xima de toda la lista
705
         * @return Coordenada Y m?xima
706
         */
707
        public double getMaxY() {
708
                return provider.getExtent().getMax().getY();
709
        }
710

    
711
        public NoData getNoDataValue() {
712
                if(provider != null)
713
                        return provider.getNoDataValue();
714
                return null;
715
        }
716

    
717
        public void setNoDataValue(NoData value) {
718
                provider.setNoDataValue(value);
719
        }
720

    
721
        public Extent getExtent() {
722
                Extent e = provider.getExtent();
723
                if (coordTrans != null) {
724
                        e = e.convert(coordTrans);
725
                }
726
                return e;
727
        }
728

    
729
        /**
730
         * Este es el extent sobre el que se ajusta una petici?n para que esta no exceda el
731
         * extent m?ximo del raster. Para un raster sin rotar ser? igual al extent
732
         * pero para un raster rotado ser? igual al extent del raster como si no
733
         * tuviera rotaci?n. Esto ha de ser as? ya que la rotaci?n solo se hace sobre la
734
         * vista y las peticiones han de hacerse en coordenadas de la imagen sin shearing
735
         * aplicado.
736
         * @return Extent
737
         */
738
        public Extent getExtentForRequest() {
739
                return provider.getExtentWithoutRot();
740
        }
741

    
742
        public Extent getLastSelectedView(){
743
                return provider.getView();
744
        }
745

    
746
        public ColorTable getColorTable(int i){
747
                return provider.getColorTable();
748
        }
749

    
750
        /**
751
         * Obtiene la lista de paletas correspondiente a todos los ficheros que forman el GeoMultiRasterFile
752
         * @return Paleta asociada a este o null si no tiene. Una posici?n null en el array tambi?n indica que
753
         * para ese fichero no hay paletas asociadas.
754
         */
755
        public ColorTable getColorTables() {
756
                return provider.getColorTable();
757
        }
758
        
759
        public ColorTable getColorTable() {
760
                //Solo tiene sentido si tiene un fichero y ese fichero tiene una sola banda
761
                if(provider != null)
762
                        return provider.getColorTable();
763
                return null;
764
        }
765
        
766
        /**
767
         * Sets the color table
768
         * @param colorTable
769
         */
770
        public void setColorTable(ColorTable colorTable) {
771
                provider.setColorTable(colorTable);
772
        }
773

    
774
        public ColorTable getColorTable(String fileName){
775
                return provider.getColorTable();
776
        }
777

    
778
        public Point2D rasterToWorld(Point2D pt) {
779
                return provider.rasterToWorld(pt);
780
        }
781

    
782
        public Point2D worldToRaster(Point2D pt) {
783
                return provider.worldToRaster(pt);
784
        }
785

    
786
        public double[] calcSteps(double dWorldTLX, double dWorldTLY, double dWorldBRX, double dWorldBRY,
787
                        double nWidth, double nHeight, int bufWidth, int bufHeight){
788
                return provider.calcSteps(dWorldTLX, dWorldTLY, dWorldBRX, dWorldBRY, nWidth, nHeight, bufWidth, bufHeight);
789
        }
790

    
791
        public boolean isGeoreferenced() {
792
                return provider.isGeoreferenced();
793
        }
794

    
795
        public double getPixelSizeX() {
796
                return provider.getPixelSizeX();
797
        }
798

    
799
        public double getPixelSizeY() {
800
                return provider.getPixelSizeY();
801
        }
802

    
803
        public Object getData(int x, int y, int band)throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
804
                return provider.getData(x, y, band);
805
        }
806

    
807
        public String getWktProjection() throws RasterDriverException {
808
                if(provider != null)
809
                        return provider.getWktProjection();
810
                return null;
811
        }
812

    
813
        public boolean isInside(Point2D p) {
814
                if(provider != null)
815
                        return provider.isInside(p);
816
                return false;
817
        }
818
        
819
        public RasterDataStore getDataStore() {
820
                return this;
821
        }
822

    
823
        public AffineTransform getAffineTransform(int band){
824
                return provider.getAffineTransform();
825
        }
826

    
827
        public void setAffineTransform(AffineTransform transf) {
828
                provider.setAffineTransform(transf);
829
        }
830

    
831
        /**
832
         * Obtiene la matriz de transformaci?n del propio raster. Esta matriz es la encargada
833
         * de convertir las coordenadas de la petici?n en coordenadas a las que se pide a la libreria.
834
         * En gdal, por ejemplo, se piden las coordenadas a la libreria en coordenadas pixel por lo que
835
         * esta matriz tendr? la georreferenciaci?n asociada en el worldfile o cabecera. Otras librerias como
836
         * ermapper la petici?n a la libreria se hace en coordenadas geograficas que son las mismas en las
837
         * que pide el usuario de gvSIG por lo que esta matriz en este caso se inicializa con la identidad.
838
         * @return
839
         */
840
        public AffineTransform getOwnTransformation() {
841
                return provider.getOwnAffineTransform();
842
        }
843

    
844
        public boolean isRotated() {
845
                if(provider != null)
846
                        return provider.isRotated();
847
                return false;
848
        }
849

    
850
        public void setDrawableBands(int[] db) {
851
                getBands().setDrawableBands(db);
852
        }
853
        
854
        public int[] getDrawableBands() {
855
                return getBands().getDrawableBands();
856
        }
857

    
858
        public void clearDrawableBands() {
859
                getBands().clearDrawableBands();
860
        }
861

    
862
        public void addDrawableBand(int posRasterBuf, int imageBand) {
863
                getBands().addDrawableBand(posRasterBuf, imageBand);
864
        }
865

    
866
        /**
867
         * 
868
         * @return
869
         */
870
        public boolean isReadOnly() {
871
                return readOnly;
872
        }
873

    
874
        /**
875
         * 
876
         * @param readOnly
877
         */
878
        public void setReadOnly(boolean readOnly) {
879
                this.readOnly = readOnly;
880
                if(readOnly)
881
                        this.forceToMemory = false;
882
        }
883

    
884
        public void setMemoryBuffer(boolean memory) {
885
                this.forceToMemory = memory;
886
                if(memory)
887
                        this.readOnly = false;
888
        }
889

    
890
        /**
891
         * 
892
         * @return
893
         */
894
        public boolean isMemoryBuffer() {
895
                return forceToMemory;
896
        }
897
        
898
        public void deleteLayerFromCache() {
899
                provider.deleteLayerFromCache();
900
        }
901
        
902
        public boolean isMultiFile() {
903
                return provider.isMultiFile();
904
        }
905
        
906
        public int getOverviewWidth(int band, int overview) throws BandAccessException, RasterDriverException {
907
                return provider.getOverviewWidth(band, overview);
908
        }
909

    
910
        public int getOverviewHeight(int band, int overview) throws BandAccessException, RasterDriverException {
911
                return provider.getOverviewHeight(band, overview);
912
        }
913

    
914
        public int getOverviewCount(int band) throws BandAccessException, RasterDriverException {
915
                if(band >= getBandCount())
916
                        throw new BandAccessException("Wrong band");
917
                return provider.getOverviewCount(band);
918
        }
919

    
920
        public boolean overviewsSupport() {
921
                if(provider != null)
922
                        return provider.isOverviewsSupported();
923
                return false;
924
        }
925
        
926
        public void saveGeoreferencingToRmf() throws RmfSerializerException {
927
                provider.saveObjectToRmf(DefaultRasterProvider.class, provider);
928
        }
929
        
930
        public void saveSerialInfoToRmf(TimeSeries serialInfo) throws RmfSerializerException {
931
                provider.saveObjectToRmf(TimeSeries.class, serialInfo);
932
        }
933

    
934
        public void saveColorTableToRmf(ColorTable table) throws RmfSerializerException {
935
                provider.saveObjectToRmf(ColorTable.class, table);
936
        }
937
        
938
        public void saveGeoPointListToRmf(GeoPointList pointList) throws RmfSerializerException {
939
                provider.saveObjectToRmf(GeoPointList.class, pointList);
940
        }
941
        
942
        public void saveROIFileListToRmf(List<File> fileList) throws RmfSerializerException {
943
                provider.saveObjectToRmf(List.class, fileList);
944
        }
945
        
946
        public List<File> getROIFileListFromRmf() {
947
                try {
948
                        List<File> fileList = new ArrayList<File>();
949
                        provider.loadObjectFromRmf(List.class, fileList);
950
                        return fileList;
951
                } catch (RmfSerializerException e) {
952
                }
953
                return null;
954
        }
955
        
956
        public boolean loadSerialInfoFromRmf(TimeSeries serialInfo) {
957
                try {
958
                        provider.loadObjectFromRmf(TimeSeries.class, serialInfo);
959
                        return true;
960
                } catch (RmfSerializerException e) {
961
                        //Prueba hasta que alguno tiene la informaci?n
962
                }
963
                return false;
964
        }
965

    
966
        public Extent getView() {
967
                if(provider != null)
968
                        return provider.getView();
969
                return null;
970
        }
971
        
972
        public Extent getExtentWithoutRot() {
973
                if(provider != null)
974
                        return provider.getExtentWithoutRot();
975
                return null;
976
        }
977
        
978
        public AffineTransform getOwnAffineTransform() {
979
                if(provider != null)
980
                        return provider.getOwnAffineTransform();
981
                return null;
982
        }
983
        
984
        public AffineTransform getAffineTransform() {
985
                if(provider != null) {
986
                        AffineTransform at = provider.getAffineTransform();
987
                        /*if (coordTrans != null) {
988
                                Point2D scale = new Point2D.Double(at.getTranslateX() + at.getScaleX(), at.getTranslateY() + at.getScaleY());
989
                                Point2D translate = new Point2D.Double(at.getTranslateX(), at.getTranslateY());
990
                                scale = coordTrans.convert(scale, scale);
991
                                translate = coordTrans.convert(translate, translate);
992
                                double sX = scale.getX() - translate.getX();
993
                                double sY = scale.getY() - translate.getY();
994
                                at = new AffineTransform(
995
                                                sX, 
996
                                                at.getShearY(), 
997
                                                at.getShearX(), 
998
                                                sY, 
999
                                                translate.getX(), 
1000
                                                translate.getY());
1001
                        }*/
1002
                        return at;
1003
                }
1004
                return null;
1005
        }
1006
        
1007
        public IProjection getProjection() {
1008
                if(provider != null)
1009
                        return provider.getProjection();
1010
                return null;
1011
        }
1012
        
1013
        public void setProjection(IProjection proj, boolean persist) throws RmfSerializerException {
1014
                if(provider != null)
1015
                        provider.setProjection(proj, persist);
1016
        }
1017
        
1018
        public Statistics getStatistics() {
1019
                if(provider != null)
1020
                        return provider.getStatistics();
1021
                return null;
1022
        }
1023
        
1024
        public void setStatistics(Statistics stats) throws RmfSerializerException {
1025
                if(provider != null)
1026
                        provider.setStatistics(stats);
1027
        }
1028
        
1029
        public HistogramComputer getHistogramComputer() {
1030
                if(provider != null)
1031
                        return provider.getHistogramComputer();
1032
                return null;
1033
        }
1034
        
1035
        public Metadata getMetadata() {
1036
                if(provider != null)
1037
                        return provider.getMetadata();
1038
                return null;
1039
        }
1040
        
1041
        public Transparency getTransparency() {
1042
                if(provider != null) {
1043
                        provider.getTransparency().setNoData(getNoDataValue());
1044
                        return provider.getTransparency();
1045
                }
1046
                return null;
1047
        }
1048
        
1049
        public ColorInterpretation getColorInterpretation() {
1050
                return provider.getColorInterpretation();
1051
        }
1052

    
1053
        public boolean isReproyectable() {
1054
                if(provider != null)
1055
                        return (provider.isReproyectable());
1056
                return false;
1057
        }
1058
        
1059
        public String getMetadataName() {
1060
                if(provider != null)
1061
                        return provider.getName();
1062
                return null;
1063
        }
1064
        
1065
        public RasterDataStore cloneDataStore() throws CloneException {
1066
                DefaultRasterStore ds = new DefaultRasterStore();
1067
                ds.parameters = getParameters();
1068
                ds.provider = provider.cloneProvider();
1069
                
1070
                int[] bands = new int[1];
1071
                bands[0] = provider.getBandCount();
1072
                ds.metadata = new MultiDataStoreMetadata(bands);
1073
                ((MultiDataStoreMetadata)ds.metadata).add(provider.getMetadata());
1074
                
1075
                ds.bandList = (BandListImpl)bandList.clone();
1076
                return ds;
1077
        }
1078
        
1079
        public boolean isOpen() {
1080
                if(provider == null)
1081
                        return false;
1082
                return provider.isOpen();
1083
        }
1084

    
1085
        public CoverageStoreProvider getProvider() {
1086
                return provider;
1087
        }
1088
        
1089
        public String getInfoByPoint(double x, double y, ICancellable cancellable) throws InfoByPointException {
1090
                return ((RasterProvider)getProvider()).getInfoByPoint(x, y, cancellable);
1091
        }
1092
        
1093
        public String getInfoByPoint(double x, double y, Extent bbox, int w, int h, ICancellable cancellable) throws InfoByPointException {
1094
                return ((RasterProvider)getProvider()).getInfoByPoint((int)x, (int)y, bbox, w, h, cancellable);
1095
        }
1096

    
1097
        public void goTo(int position) throws OperationNotSupportedException {
1098
                if(!isTimeSupportedByTheProvider())
1099
                        throw new OperationNotSupportedException("Not supported for a MultiRasterDataset");
1100
                if(getParameters() instanceof MultiDimensionalStoreParameters) {
1101
                        ((MultiDimensionalStoreParameters)getParameters()).goTo(position);
1102
                }
1103
        }
1104

    
1105
        public void selectNext() throws OperationNotSupportedException {
1106
                if(!isTimeSupportedByTheProvider())
1107
                        throw new OperationNotSupportedException("Not supported for a MultiRasterDataset");
1108
                if(getParameters() instanceof MultiDimensionalStoreParameters) {
1109
                        ((MultiDimensionalStoreParameters)getParameters()).selectNextInstant();
1110
                }
1111
        }
1112

    
1113
        public void selectPrev() throws OperationNotSupportedException {
1114
                if(!isTimeSupportedByTheProvider())
1115
                        throw new OperationNotSupportedException("Not supported for a MultiRasterDataset");
1116
                if(getParameters() instanceof MultiDimensionalStoreParameters) {
1117
                        ((MultiDimensionalStoreParameters)getParameters()).selectPrevInstant();
1118
                }
1119
        }
1120
        
1121
        public void setTime(Time time) throws TimeException, OperationNotSupportedException {
1122
                if(!isTimeSupportedByTheProvider())
1123
                        throw new OperationNotSupportedException("Not supported for a MultiRasterDataset");
1124
                
1125
        }
1126
        
1127
        /**
1128
         * Returns true whether all providers support time
1129
         * @return
1130
         */
1131
        private boolean isTimeSupportedByTheProvider() {
1132
                if(provider != null)
1133
                        return provider.isTimeSupported();
1134
                return false;
1135
        }
1136
        
1137
        public boolean isRasterEnclosed() {
1138
                if(provider != null)
1139
                        return provider.isRasterEnclosed();
1140
                return false;
1141
        }
1142

    
1143
        public Extent getCoordsInLevel(Point2D viewCenter, int level, int w, int h) {
1144
                try {
1145
                        return ((TiledRasterProvider)provider).getCoordsInLevel(viewCenter, level, w, h);
1146
                } catch (ClassCastException e) {
1147
                        return null;
1148
                }
1149
        }
1150

    
1151
        public Extent getCoordsInTheNearestLevel(Extent extent, int w, int h) {
1152
                try {
1153
                        return ((TiledRasterProvider)provider).getCoordsInTheNearestLevel(extent, w, h);
1154
                } catch (ClassCastException e) {
1155
                        return null;
1156
                }
1157
        }
1158

    
1159
        public int getZoomLevels() {
1160
                try {
1161
                        return ((TiledRasterProvider)provider).getZoomLevels();
1162
                } catch (ClassCastException e) {
1163
                        return -1;
1164
                }
1165
        }
1166

    
1167
        public int getNearestLevel(double pixelSize) {
1168
                try {
1169
                        return ((TiledRasterProvider)provider).getNearestLevel(pixelSize);
1170
                } catch (ClassCastException e) {
1171
                        return -1;
1172
                }
1173
        }
1174
        
1175
        public void setTileServer(Class<?> tileServer) throws InitializeException {
1176
                if(provider instanceof TiledRasterProvider) {
1177
                        ((TiledRasterProvider)provider).setTileServer(tileServer);
1178
                }
1179
        }
1180

    
1181
        public RasterDataParameters getInternalParameters() {
1182
                if(provider instanceof TiledRasterProvider) {
1183
                        DefaultRasterProvider prov = (DefaultRasterProvider)((TiledRasterProvider)provider).getInternalProvider();
1184
                        return prov.getDataParameters();
1185
                }
1186
                return (RasterDataParameters)getParameters();
1187
        }
1188

    
1189
        public RasterDataStore newDataStore() {
1190
                if(provider != null) {
1191
                        RasterManager manager = (DefaultRasterManager)RasterLocator.getManager();
1192
                        RasterDataStore newDataStore = null;
1193
                        try {
1194
                                newDataStore = manager.getProviderServices().open((DataStoreParameters)parameters);
1195
                                if(newDataStore instanceof DefaultRasterStore) {
1196
                                        ((DefaultRasterStore)newDataStore).setStatistics(getStatistics());
1197
                                }
1198
                                return newDataStore;
1199
                        } catch (NotSupportedExtensionException e) {
1200
                                return null;
1201
                        } catch (RasterDriverException e) {
1202
                                return null;
1203
                        } catch (RmfSerializerException e) {
1204
                                return newDataStore;
1205
                        }
1206
                }
1207
                return null;
1208
        }
1209

    
1210
        public String[] getURIByProvider() {
1211
                return provider.getURIByProvider();
1212
        }
1213

    
1214
        public long[] getFileSizeByProvider() {
1215
                return provider.getFileSizeByProvider();
1216
        }
1217

    
1218
        public int getProviderCount() {
1219
                return provider.getInternalProviderCount();
1220
        }
1221
        
1222
        public int[] getBandCountByProvider() {
1223
                return provider.getBandCountByProvider();
1224
        }
1225
        
1226
        public RasterDataParameters[] getDataParametersByProvider() {
1227
                RasterDataParameters[] res = new RasterDataParameters[getProviderCount()];
1228
                for (int i = 0; i < res.length; i++) {
1229
                        res[i] = (RasterDataParameters)provider.getInternalProvider(i).getDataParameters();                        
1230
                }
1231
                return res;
1232
        }
1233
        
1234
        public Metadata[] getMetadataByProvider() {
1235
                Metadata[] res = new Metadata[getProviderCount()];
1236
                for (int i = 0; i < res.length; i++) {
1237
                        res[i] = provider.getInternalProvider(i).getMetadata();                        
1238
                }
1239
                return res;
1240
        }
1241
        
1242
        public int[] getOverviewCountByProvider(int band) throws BandAccessException {
1243
                int[] res = new int[getProviderCount()];
1244
                for (int i = 0; i < res.length; i++) {
1245
                        try {
1246
                                res[i] = provider.getInternalProvider(i).getOverviewCount(band);
1247
                        } catch (RasterDriverException e) {
1248
                                throw new BandAccessException("", e);
1249
                        }                        
1250
                }
1251
                return res;
1252
        }
1253
        
1254
        public String[] getOverviewSizeByProvider(int band, int overview) throws BandAccessException {
1255
                String[] res = new String[getProviderCount()];
1256
                for (int i = 0; i < res.length; i++) {
1257
                        try {
1258
                                res[i] = provider.getInternalProvider(i).getOverviewWidth(band, overview) + 
1259
                                                 "x" + 
1260
                                                 provider.getInternalProvider(i).getOverviewHeight(band, overview);
1261
                        } catch (RasterDriverException e) {
1262
                                throw new BandAccessException("", e);
1263
                        }                        
1264
                }
1265
                return res;
1266
        }
1267
        
1268
        public AffineTransform[] getAffineTransformByProvider() {
1269
                AffineTransform[] res = new AffineTransform[getProviderCount()];
1270
                for (int i = 0; i < res.length; i++) {
1271
                        res[i] = provider.getInternalProvider(i).getAffineTransform();
1272
                }
1273
                return res;
1274
        }
1275
        
1276
        public double[] getHeightByProvider() {
1277
                double[] res = new double[getProviderCount()];
1278
                for (int i = 0; i < res.length; i++) {
1279
                        res[i] = provider.getInternalProvider(i).getHeight();
1280
                }
1281
                return res;
1282
        }
1283
        
1284
        public double[] getWidthByProvider() {
1285
                double[] res = new double[getProviderCount()];
1286
                for (int i = 0; i < res.length; i++) {
1287
                        res[i] = provider.getInternalProvider(i).getWidth();
1288
                }
1289
                return res;
1290
        }
1291
        
1292
        public void addFile(String file) throws InvalidSourceException {
1293
                provider.addFile(file);
1294
        }
1295
        
1296
        public void removeFile(String file) {
1297
                provider.removeFile(file);
1298
                bandList.removeBands(file);
1299
        }
1300
        
1301
        public String getURIByBand(int band) {
1302
                return provider.getURIByBand(band);
1303
        }
1304
        
1305
        /**
1306
         * Gets the {@link Interval} of the store, that means the temporal
1307
         * interval where the store has valid data.
1308
         * In raster this method has sense in a mosaic. Therefore this has to be implemented 
1309
         * by the provider.
1310
         * @return
1311
         *         a time interval or null if there is not time support
1312
         */
1313
        public Interval getInterval() {
1314
                return provider.getInterval();
1315
        }
1316
        
1317
        /**
1318
         * Gets all the possible values of time for which the store has data.  
1319
         * In raster this method has sense in a mosaic. Therefore this has to be implemented 
1320
         * by the provider.
1321
         * @return
1322
         *         a collection of {@link Time} objects.
1323
         */
1324
        public Collection<?> getTimes() {
1325
                return provider.getTimes();
1326
        }
1327
        
1328
        /**
1329
         * Gets all the possible values of time for which the store has data
1330
         * and intersects with an interval.
1331
         * In raster this method has sense in a mosaic. Therefore this has to be implemented 
1332
         * by the provider.
1333
         * @param interval
1334
         *         the interval of time
1335
         * @return
1336
         *         a collection of {@link Time} objects.
1337
         */
1338
        public Collection<?> getTimes(Interval interval) {
1339
                return provider.getTimes(interval);
1340
        }
1341
        
1342
        public Image getImageLegend() {
1343
                if(provider != null)
1344
                        return provider.getImageLegend();
1345
                return null;
1346
        }
1347
        
1348
        /**
1349
         * Gets the list of geo points associated to this provider
1350
         * @return
1351
         */
1352
        public GeoPointList getGeoPointList() {
1353
                return provider.getGeoPointList();
1354
        }
1355
        
1356
        /**
1357
         * Sets the list of geo points associated to this provider
1358
         */
1359
        public void setGeoPointList(GeoPointList geoPointList) {
1360
                provider.setGeoPointList(geoPointList);
1361
        }
1362
        
1363
        public Envelope getFullEnvelope() {
1364
                Rectangle2D e = getExtent().toRectangle2D();
1365
                try {
1366
                        return GeometryLocator.getGeometryManager().createEnvelope(e.getX(), e.getY(), e.getMaxX(), e
1367
                                        .getMaxY(), SUBTYPES.GEOM2D);
1368
                } catch (CreateEnvelopeException e1) {
1369
                        logger.error("Error creating the envelope", e);
1370
                        return null;
1371
                }
1372
        }
1373
        
1374
        public List<ROI> getRois(String epsg) throws ROIException {
1375
                IProjection proj = CRSFactory.getCRS(epsg);
1376
                return getRois(proj);
1377
        }
1378
        
1379
        public List<ROI> getRois(IProjection defaultProjection) throws ROIException {
1380
                if(rois == null) {
1381
                        try {
1382
                                List<File> fileList = getDataStore().getROIFileListFromRmf();
1383
                                if(fileList != null & fileList.size() > 0 && fileList.get(0) != null) {
1384
                                        File f = fileList.get(0);
1385
                                        IProjection proj = getProjection();
1386
                                        if(proj == null) {
1387
                                                proj = defaultProjection;
1388
                                        }
1389
                                        ROIReader reader = new VectorialROIsReader(
1390
                                                        f.getPath(), 
1391
                                                        getDataStore(),
1392
                                                        proj,
1393
                                                        getFullEnvelope());
1394
                                        rois = new ArrayList<ROI>();
1395
                                        rois = reader.read(rois);
1396
                                }
1397
                        } catch (Exception e) {
1398
                                throw new ROIException("error_getting_ROIS", e);
1399
                        }
1400
                }
1401
                return rois;
1402
        }
1403

    
1404
        public void setRois(List<ROI> rois) {
1405
                this.rois = rois;
1406
        }
1407
        
1408
        public void setROIsFiles(List<File> file) throws RmfSerializerException {
1409
                getDataStore().saveROIFileListToRmf(file);
1410
        }
1411
        
1412
        public List<File> getROIsFiles() throws RmfSerializerException {
1413
                return getDataStore().getROIFileListFromRmf();
1414
        }
1415

    
1416
        public void loadFromState(PersistentState state)
1417
                        throws PersistenceException {
1418
                if(parameters == null)
1419
                        this.parameters = (RasterDataParameters)state.get("parameters");
1420
                DataManagerProviderServices dataManager = (DataManagerProviderServices)DALLocator.getDataManager();
1421
                try {
1422
                        this.provider = (DefaultRasterProvider)dataManager.createProvider(this, this.parameters);
1423
                } catch (InitializeException e) {
1424
                        //throw new PersistenceException(e);
1425
                } catch (ProviderNotRegisteredException e) {
1426
                        throw new PersistenceException(e);
1427
                }
1428
                this.bandList = (BandListImpl)state.get("bandList");
1429
                if(parameters instanceof AbstractRasterFileDataParameters && !this.provider.isMultiFile()) {
1430
                        //Esto solo es por si al cargar un proyecto se ha cambiado el fichero de sitio y el usuario
1431
                        //lo introduce manualmente. En ese caso el bandList debe contener la misma ruta al fichero que el 
1432
                        //provider y no la que se grab? inicialmente
1433
                        for (int i = 0; i < bandList.getBandCount(); i++) {
1434
                                bandList.getBand(i).setFileName(provider.getURI());                                
1435
                        }
1436
                }
1437
                this.metadata = (Metadata)state.get("metadata");
1438
                setRender((Render)state.get("render"));
1439
                int[] rb = getRender().getRenderBands(); //Evitamos que las bandas que fueron cargadas se machaquen ahora
1440
                getRender().setDataStore(this);
1441
                getRender().setRenderBands(rb);
1442
                if(getRender().getLastTransparency() != null)
1443
                        getRender().getLastTransparency().setNoData(getNoDataValue());
1444
                
1445
                loadFiltersFromProject(state);
1446
                
1447
        }
1448
        
1449
        /*private void loadROIFromProject(PersistentState state) throws PersistenceException {
1450
                List<ROI> rois = state.getList("rois");
1451
                if(rois != null) {
1452
                        this.rois = new ArrayList<ROI>();
1453
                        this.rois.addAll(rois);
1454
                }
1455
        }*/
1456
        
1457
        @SuppressWarnings("unchecked")
1458
        private void loadFiltersFromProject(PersistentState state) throws PersistenceException {
1459
                RasterFilterList fList = (RasterFilterList)state.get("filterList");
1460
                fList.addEnvParam("IStatistics", getStatistics());
1461
                fList.addEnvParam("MultiRasterDataset", this);
1462
                getRender().setFilterList(fList);
1463
                
1464
                List<PersistencyFilterParam> listFilterUsed = state.getList("paramlist");
1465
                
1466
                ArrayList<Exception> exc = new ArrayList<Exception>();
1467
                for (int i = 0; i < listFilterUsed.size(); i++) {
1468
                        try {
1469
                                PersistencyFilterParam pfp = (PersistencyFilterParam) listFilterUsed.get(i);
1470
                                if(pfp != null && pfp.getFilterClass() != null && pfp.getFilterParam() != null) {
1471
                                        RasterFilterListManager filterManager = fList.getManagerByFilterClass(pfp.getFilterClass());
1472
                                        filterManager.setFilterList(fList);
1473
                                        if(filterManager != null)
1474
                                                filterManager.addFilter(pfp.getFilterClass(), pfp.getFilterParam());
1475
                                }
1476
                        } catch (FilterTypeException e) {
1477
                                exc.add(e);
1478
                        } catch (FilterManagerException e) {
1479
                                exc.add(e);
1480
                        }
1481
                }
1482
                
1483
                if(exc.size() != 0) {
1484
                        throw new PersistenceException("error_adding_filters", exc.get(0));
1485
                }
1486
        }
1487

    
1488
        public void saveToState(PersistentState state) throws PersistenceException {
1489
                state.set("parameters", provider.getDataParameters());                
1490
                state.set("bandList", bandList);
1491
                state.set("metadata", metadata);
1492
                state.set("render", getRender());
1493
                state.set("filterList", getRender().getFilterList());
1494
                
1495
                RasterFilterList list = getRender().getFilterList();
1496
                ArrayList<PersistencyFilterParam> filters = new ArrayList<PersistencyFilterParam>();
1497
                for (int i = 0; i < list.lenght(); i++) {
1498
                        RasterFilter f = list.get(i);
1499
                        Params uipar = f.getUIParams(f.getName());
1500
                        PersistencyFilterParam param = new PersistencyFilterParam();
1501
                        param.setFilterParam(uipar);
1502
                        param.setFilterClass(f.getClass());
1503
                        param.setFilterName(f.getName());
1504
                        filters.add(param);
1505
                }
1506
                state.set("paramlist", filters);
1507
                //state.set("rois", rois);
1508
        }        
1509
        
1510
        public static void registerPersistence() {
1511
                PersistenceManager manager = ToolsLocator.getPersistenceManager();
1512
                DynStruct definition = manager.getDefinition(PERSISTENT_NAME);
1513
                if( definition == null ) {
1514
                        definition = manager.addDefinition(
1515
                                        DefaultRasterStore.class,
1516
                                        PERSISTENT_NAME,
1517
                                        PERSISTENT_DESCRIPTION,
1518
                                        null, 
1519
                                        null
1520
                        );
1521
                        
1522
                        definition.addDynFieldObject("parameters").setClassOfValue(RasterDataParameters.class).setMandatory(true);
1523
                        definition.addDynFieldObject("bandList").setClassOfValue(BandList.class).setMandatory(false);
1524
                        definition.addDynFieldObject("metadata").setClassOfValue(Metadata.class).setMandatory(false);
1525
                        definition.addDynFieldObject("render").setClassOfValue(Render.class).setMandatory(true);
1526
                        
1527
                        definition.addDynFieldObject("filterList").setClassOfValue(RasterFilterList.class).setMandatory(false);
1528
                        definition.addDynFieldList("paramlist").setClassOfItems(PersistencyFilterParam.class).setMandatory(false);
1529
                        
1530
                        //definition.addDynFieldList("rois").setClassOfItems(ROI.class).setMandatory(false);
1531
                }
1532
        }
1533
        
1534
        public void close() {
1535
                if(provider != null)
1536
                        provider.close();
1537
                if(bandList != null)
1538
                        bandList.clear();
1539
                provider = null;
1540
                bandList = null;
1541
                super.close();
1542
                try {
1543
                        finalize();
1544
                } catch (Throwable e) {
1545
                }
1546
        }
1547
        
1548
        protected void finalize() throws Throwable {
1549
                provider               = null;
1550
                bandList               = null;
1551
                metadata               = null;
1552
                rManager               = null;
1553
                if(rois != null) {
1554
                        rois.clear();
1555
                        rois = null;
1556
                }
1557
                super.finalize();
1558
        }
1559
}