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

History | View | Annotate | Download (51.3 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.ParsingException;
61
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
62
import org.gvsig.fmap.dal.coverage.exception.ROIException;
63
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
64
import org.gvsig.fmap.dal.coverage.exception.RmfSerializerException;
65
import org.gvsig.fmap.dal.coverage.exception.TimeException;
66
import org.gvsig.fmap.dal.coverage.grid.RasterFilter;
67
import org.gvsig.fmap.dal.coverage.grid.RasterFilterList;
68
import org.gvsig.fmap.dal.coverage.grid.RasterFilterListManager;
69
import org.gvsig.fmap.dal.coverage.grid.render.Render;
70
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
71
import org.gvsig.fmap.dal.coverage.store.parameter.MultiDimensionalStoreParameters;
72
import org.gvsig.fmap.dal.coverage.store.parameter.RasterDataParameters;
73
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
74
import org.gvsig.fmap.dal.coverage.store.props.ColorTable;
75
import org.gvsig.fmap.dal.coverage.store.props.HistogramComputer;
76
import org.gvsig.fmap.dal.coverage.store.props.Metadata;
77
import org.gvsig.fmap.dal.coverage.store.props.Statistics;
78
import org.gvsig.fmap.dal.coverage.store.props.TimeSeries;
79
import org.gvsig.fmap.dal.coverage.store.props.Transparency;
80
import org.gvsig.fmap.dal.exception.InitializeException;
81
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
82
import org.gvsig.fmap.dal.raster.spi.CoverageStoreProvider;
83
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
84
import org.gvsig.fmap.dal.spi.DataStoreProvider;
85
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
86
import org.gvsig.fmap.geom.GeometryLocator;
87
import org.gvsig.fmap.geom.exception.CreateEnvelopeException;
88
import org.gvsig.fmap.geom.primitive.Envelope;
89
import org.gvsig.raster.cache.tile.Tile;
90
import org.gvsig.raster.cache.tile.TileCacheLocator;
91
import org.gvsig.raster.cache.tile.TileCacheManager;
92
import org.gvsig.raster.cache.tile.exception.TileGettingException;
93
import org.gvsig.raster.impl.DefaultRasterManager;
94
import org.gvsig.raster.impl.buffer.DefaultRasterQuery;
95
import org.gvsig.raster.impl.buffer.cache.RasterReadOnlyBuffer;
96
import org.gvsig.raster.impl.datastruct.BandListImpl;
97
import org.gvsig.raster.impl.datastruct.DatasetBandImpl;
98
import org.gvsig.raster.impl.datastruct.ExtentImpl;
99
import org.gvsig.raster.impl.grid.roi.VectorialROIsReader;
100
import org.gvsig.raster.impl.provider.DefaultRasterProvider;
101
import org.gvsig.raster.impl.provider.RasterProvider;
102
import org.gvsig.raster.impl.provider.TiledRasterProvider;
103
import org.gvsig.raster.impl.store.properties.MultiDataStoreMetadata;
104
import org.gvsig.raster.roi.ROI;
105
import org.gvsig.raster.roi.ROIReader;
106
import org.gvsig.raster.util.persistence.PersistencyFilterParam;
107
import org.gvsig.timesupport.Interval;
108
import org.gvsig.timesupport.Time;
109
import org.gvsig.tools.ToolsLocator;
110
import org.gvsig.tools.dynobject.DynStruct;
111
import org.gvsig.tools.persistence.PersistenceManager;
112
import org.gvsig.tools.persistence.PersistentState;
113
import org.gvsig.tools.persistence.exception.PersistenceException;
114
import org.slf4j.Logger;
115
import org.slf4j.LoggerFactory;
116

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

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

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

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

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

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

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

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

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

    
283
                //Buffer ReadOnly
284

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

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

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

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

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

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

    
361
                //Buffer ReadOnly
362

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

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

    
400
                return raster;
401
        }
402

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

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

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

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

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

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

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

    
445
                //Buffer ReadOnly
446

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

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

    
485
                return raster;
486
        }
487

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

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

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

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

    
589
                //Buffer ReadOnly
590

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

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

    
626
                return raster;
627
        }
628

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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