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 @ 2125

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

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

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

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

    
245
                //Extent selectedExtent = new Extent(ulx, uly, lrx, lry);
246

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

    
250
                Point2D p1 = provider.worldToRaster(new Point2D.Double(q.getX(), q.getY()));
251
                Point2D p2 = provider.worldToRaster(new Point2D.Double(lrx, lry));
252
                adjustPoints(p1, p2);
253
                int width = (int)Math.abs(Math.ceil(p2.getX()) - Math.floor(p1.getX()));
254
                int height = (int)Math.abs(Math.floor(p1.getY()) - Math.ceil(p2.getY()));
255

    
256
                //Ajustamos por si nos hemos salido del raster
257
                if(((int)(p1.getX() + width)) > getWidth())
258
                        width = (int)(getWidth() - p1.getX());
259
                if(((int)(p1.getY() + height)) > getHeight())
260
                        height = (int)(getHeight() - p1.getY());
261

    
262
                if (p1.getX() < 0)
263
                        p1.setLocation(0, p1.getY());
264
                if (p1.getY() < 0)
265
                        p1.setLocation(p1.getX(), 0);
266
                if (p2.getX() > getWidth())
267
                        p2.setLocation(getWidth(), p2.getY());
268
                if (p2.getY() > getHeight())
269
                        p2.setLocation(p2.getX(), getHeight());
270

    
271
                int mallocNBands = 0;
272
                if(bandList.getDrawableBands() != null)
273
                        mallocNBands = bandList.getDrawableBands().length;
274
                else
275
                        mallocNBands = bandList.getDrawableBandsCount();
276

    
277
                //Buffer ReadOnly
278

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

    
301
                //Buffer RW
302
                Buffer raster = null;
303
                
304
                if(forceToMemory) //Fuerza siempre buffer en memoria
305
                        raster = DefaultRasterManager.getInstance().createMemoryBuffer(getDataType()[0], width, height, mallocNBands, true);
306
                else
307
                        raster = DefaultRasterManager.getInstance().createBuffer(getDataType()[0], width, height, mallocNBands, true);
308

    
309
                if(!q.isAdjustToExtent())
310
                         initBufferToNoData(raster, bandList);
311
                
312
                q.setAreaOfInterest(wc1.getX(), wc1.getY(), Math.abs(wc2.getX() - wc1.getX()), Math.abs(wc2.getY() - wc1.getY()));
313
                q.setBandList(bandList);
314
                q.setBuffer(raster);
315
                raster = ((DefaultRasterProvider)provider).getDataSet(q);
316

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

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

    
349
                int mallocNBands = 0;
350
                if(bandList.getDrawableBands() != null)
351
                        mallocNBands = bandList.getDrawableBands().length;
352
                else
353
                        mallocNBands = bandList.getDrawableBandsCount();
354

    
355
                //Buffer ReadOnly
356

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

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

    
394
                return raster;
395
        }
396

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

    
406
                Point2D p1 = provider.worldToRaster(new Point2D.Double(q.getBBox().getULX(), q.getBBox().getULY()));
407
                Point2D p2 = provider.worldToRaster(new Point2D.Double(q.getBBox().getLRX(), q.getBBox().getLRY()));
408

    
409
                //Para el valor mayor redondeamos por arriba. Para el valor menor redondeamos por abajo.
410
                double p1X = (p1.getX() > p2.getX()) ? Math.ceil(p1.getX()) : Math.floor(p1.getX());
411
                double p1Y = (p1.getY() > p2.getY()) ? Math.ceil(p1.getY()) : Math.floor(p1.getY());
412
                double p2X = (p2.getX() > p1.getX()) ? Math.ceil(p2.getX()) : Math.floor(p2.getX());
413
                double p2Y = (p2.getY() > p1.getY()) ? Math.ceil(p2.getY()) : Math.floor(p2.getY());
414

    
415
                int width = (int)Math.abs(p1X - p2X);
416
                int height = (int)Math.abs(p1Y - p2Y);
417

    
418
                //Ajustamos por si nos hemos salido del raster
419
                if(((int)(Math.min(p1X, p2X) + width)) > getWidth())
420
                        width = (int)(getWidth() - Math.min(p1X, p2X));
421
                if(((int)(Math.min(p1Y, p2Y) + height)) > getHeight())
422
                        height = (int)(getHeight() - Math.min(p1Y, p2Y));
423

    
424
                if (p1X < 0)
425
                        p1X = 0;
426
                if (p1Y < 0)
427
                        p1Y = 0;
428
                if (p2X > getWidth())
429
                        p2X = getWidth();
430
                if (p2Y > getHeight())
431
                        p2Y = getHeight();
432

    
433
                int mallocNBands = 0;
434
                if(bandList.getDrawableBands() != null)
435
                        mallocNBands = bandList.getDrawableBands().length;
436
                else
437
                        mallocNBands = bandList.getDrawableBandsCount();
438

    
439
                //Buffer ReadOnly
440

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

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

    
479
                return raster;
480
        }
481

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

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

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

    
573
                dataExtent = new ExtentImpl(rasterToWorld(new Point2D.Double(q.getPixelX(), q.getPixelY())),
574
                                rasterToWorld(new Point2D.Double(q.getPixelX() + q.getPixelW(), q.getPixelY() + q.getPixelH())));
575
                
576
                if(        q.getType() == DefaultRasterQuery.TYPE_PX || 
577
                        q.getType() == DefaultRasterQuery.TYPE_ENTIRE || 
578
                        q.getBufWidth() <= 0 || q.getBufHeight() <= 0) {
579
                        q.setBufWidth(q.getPixelW());
580
                        q.setBufHeight(q.getPixelH());
581
                }
582

    
583
                //Buffer ReadOnly
584

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

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

    
620
                return raster;
621
        }
622

    
623
        //******************************
624
        //Setters and Getters
625
        //******************************
626

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

    
645
        public double getHeight() {
646
                return provider.getHeight();
647
        }
648

    
649
        public double getWidth() {
650
                return provider.getWidth();
651
        }
652

    
653
        public double getCellSize() {
654
                try {
655
                        Extent e = getExtent();
656
                        double dCellsize = (e.getMax().getX() - e.getMin().getX() ) / getWidth();
657
                        return dCellsize;
658
                } catch (NullPointerException e) {
659
                        return 1;
660
                }
661
        }
662

    
663
        public int getBandCount() {
664
                return provider.getBandCount();
665
        }
666

    
667
        public int[] getDataType() {
668
                return provider.getDataType();
669
        }
670

    
671
        public BandList getBands() {
672
                return bandList;
673
        }
674

    
675
        /**
676
         * Obtiene la coordenada X m?nima de toda la lista
677
         * @return Coordenada X m?nima
678
         */
679
        public double getMinX() {
680
                return provider.getExtent().getMin().getX();
681
        }
682

    
683
        /**
684
         * Obtiene la coordenada Y m?nima de toda la lista
685
         * @return Coordenada Y m?nima
686
         */
687
        public double getMinY() {
688
                return provider.getExtent().getMin().getY();
689
        }
690

    
691
        /**
692
         * Obtiene la coordenada Y m?xima de toda la lista
693
         * @return Coordenada Y m?xima
694
         */
695
        public double getMaxX() {
696
                return provider.getExtent().getMax().getX();        }
697

    
698
        /**
699
         * Obtiene la coordenada Y m?xima de toda la lista
700
         * @return Coordenada Y m?xima
701
         */
702
        public double getMaxY() {
703
                return provider.getExtent().getMax().getY();
704
        }
705

    
706
        public NoData getNoDataValue() {
707
                if(provider != null)
708
                        return provider.getNoDataValue();
709
                return null;
710
        }
711

    
712
        public void setNoDataValue(NoData value) {
713
                provider.setNoDataValue(value);
714
        }
715

    
716
        public Extent getExtent() {
717
                Extent e = provider.getExtent();
718
                if (coordTrans != null) {
719
                        e = e.convert(coordTrans);
720
                }
721
                return e;
722
        }
723

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

    
737
        public Extent getLastSelectedView(){
738
                return provider.getView();
739
        }
740

    
741
        public ColorTable getColorTable(int i){
742
                return provider.getColorTable();
743
        }
744

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

    
769
        public ColorTable getColorTable(String fileName){
770
                return provider.getColorTable();
771
        }
772

    
773
        public Point2D rasterToWorld(Point2D pt) {
774
                return provider.rasterToWorld(pt);
775
        }
776

    
777
        public Point2D worldToRaster(Point2D pt) {
778
                return provider.worldToRaster(pt);
779
        }
780

    
781
        public double[] calcSteps(double dWorldTLX, double dWorldTLY, double dWorldBRX, double dWorldBRY,
782
                        double nWidth, double nHeight, int bufWidth, int bufHeight){
783
                return provider.calcSteps(dWorldTLX, dWorldTLY, dWorldBRX, dWorldBRY, nWidth, nHeight, bufWidth, bufHeight);
784
        }
785

    
786
        public boolean isGeoreferenced() {
787
                return provider.isGeoreferenced();
788
        }
789

    
790
        public double getPixelSizeX() {
791
                return provider.getPixelSizeX();
792
        }
793

    
794
        public double getPixelSizeY() {
795
                return provider.getPixelSizeY();
796
        }
797

    
798
        public Object getData(int x, int y, int band)throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
799
                return provider.getData(x, y, band);
800
        }
801

    
802
        public String getWktProjection() throws RasterDriverException {
803
                if(provider != null)
804
                        return provider.getWktProjection();
805
                return null;
806
        }
807

    
808
        public boolean isInside(Point2D p) {
809
                if(provider != null)
810
                        return provider.isInside(p);
811
                return false;
812
        }
813
        
814
        public RasterDataStore getDataStore() {
815
                return this;
816
        }
817

    
818
        public AffineTransform getAffineTransform(int band){
819
                return provider.getAffineTransform();
820
        }
821

    
822
        public void setAffineTransform(AffineTransform transf) {
823
                provider.setAffineTransform(transf);
824
        }
825

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

    
839
        public boolean isRotated() {
840
                if(provider != null)
841
                        return provider.isRotated();
842
                return false;
843
        }
844

    
845
        public void setDrawableBands(int[] db) {
846
                getBands().setDrawableBands(db);
847
        }
848
        
849
        public int[] getDrawableBands() {
850
                return getBands().getDrawableBands();
851
        }
852

    
853
        public void clearDrawableBands() {
854
                getBands().clearDrawableBands();
855
        }
856

    
857
        public void addDrawableBand(int posRasterBuf, int imageBand) {
858
                getBands().addDrawableBand(posRasterBuf, imageBand);
859
        }
860

    
861
        /**
862
         * 
863
         * @return
864
         */
865
        public boolean isReadOnly() {
866
                return readOnly;
867
        }
868

    
869
        /**
870
         * 
871
         * @param readOnly
872
         */
873
        public void setReadOnly(boolean readOnly) {
874
                this.readOnly = readOnly;
875
                if(readOnly)
876
                        this.forceToMemory = false;
877
        }
878

    
879
        public void setMemoryBuffer(boolean memory) {
880
                this.forceToMemory = memory;
881
                if(memory)
882
                        this.readOnly = false;
883
        }
884

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

    
905
        public int getOverviewHeight(int band, int overview) throws BandAccessException, RasterDriverException {
906
                return provider.getOverviewHeight(band, overview);
907
        }
908

    
909
        public int getOverviewCount(int band) throws BandAccessException, RasterDriverException {
910
                if(band >= getBandCount())
911
                        throw new BandAccessException("Wrong band");
912
                return provider.getOverviewCount(band);
913
        }
914

    
915
        public boolean overviewsSupport() {
916
                if(provider != null)
917
                        return provider.isOverviewsSupported();
918
                return false;
919
        }
920
        
921
        public void saveGeoreferencingToRmf() throws RmfSerializerException {
922
                provider.saveObjectToRmf(DefaultRasterProvider.class, provider);
923
        }
924
        
925
        public void saveSerialInfoToRmf(TimeSeries serialInfo) throws RmfSerializerException {
926
                provider.saveObjectToRmf(TimeSeries.class, serialInfo);
927
        }
928

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

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

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

    
1080
        public CoverageStoreProvider getProvider() {
1081
                return provider;
1082
        }
1083
        
1084
        public String getInfoByPoint(double x, double y, ICancellable cancellable) throws InfoByPointException {
1085
                return ((RasterProvider)getProvider()).getInfoByPoint(x, y, cancellable);
1086
        }
1087
        
1088
        public String getInfoByPoint(double x, double y, Extent bbox, int w, int h, ICancellable cancellable) throws InfoByPointException {
1089
                return ((RasterProvider)getProvider()).getInfoByPoint((int)x, (int)y, bbox, w, h, cancellable);
1090
        }
1091

    
1092
        public void goTo(int position) throws OperationNotSupportedException {
1093
                if(!isTimeSupportedByTheProvider())
1094
                        throw new OperationNotSupportedException("Not supported for a MultiRasterDataset");
1095
                if(getParameters() instanceof MultiDimensionalStoreParameters) {
1096
                        ((MultiDimensionalStoreParameters)getParameters()).goTo(position);
1097
                }
1098
        }
1099

    
1100
        public void selectNext() throws OperationNotSupportedException {
1101
                if(!isTimeSupportedByTheProvider())
1102
                        throw new OperationNotSupportedException("Not supported for a MultiRasterDataset");
1103
                if(getParameters() instanceof MultiDimensionalStoreParameters) {
1104
                        ((MultiDimensionalStoreParameters)getParameters()).selectNextInstant();
1105
                }
1106
        }
1107

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

    
1138
        public Extent getCoordsInLevel(Point2D viewCenter, int level, int w, int h) {
1139
                try {
1140
                        return ((TiledRasterProvider)provider).getCoordsInLevel(viewCenter, level, w, h);
1141
                } catch (ClassCastException e) {
1142
                        return null;
1143
                }
1144
        }
1145

    
1146
        public Extent getCoordsInTheNearestLevel(Extent extent, int w, int h) {
1147
                try {
1148
                        return ((TiledRasterProvider)provider).getCoordsInTheNearestLevel(extent, w, h);
1149
                } catch (ClassCastException e) {
1150
                        return null;
1151
                }
1152
        }
1153

    
1154
        public int getZoomLevels() {
1155
                try {
1156
                        return ((TiledRasterProvider)provider).getZoomLevels();
1157
                } catch (ClassCastException e) {
1158
                        return -1;
1159
                }
1160
        }
1161

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

    
1176
        public RasterDataParameters getInternalParameters() {
1177
                if(provider instanceof TiledRasterProvider) {
1178
                        DefaultRasterProvider prov = (DefaultRasterProvider)((TiledRasterProvider)provider).getInternalProvider();
1179
                        return prov.getDataParameters();
1180
                }
1181
                return (RasterDataParameters)getParameters();
1182
        }
1183

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

    
1205
        public String[] getURIByProvider() {
1206
                return provider.getURIByProvider();
1207
        }
1208

    
1209
        public long[] getFileSizeByProvider() {
1210
                return provider.getFileSizeByProvider();
1211
        }
1212

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

    
1394
        public void setRois(List<ROI> rois) {
1395
                this.rois = rois;
1396
        }
1397
        
1398
        public void setROIsFiles(List<File> file) throws RmfSerializerException {
1399
                getDataStore().saveROIFileListToRmf(file);
1400
        }
1401
        
1402
        public List<File> getROIsFiles() throws RmfSerializerException {
1403
                return getDataStore().getROIFileListFromRmf();
1404
        }
1405

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

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