Statistics
| Revision:

gvsig-raster / org.gvsig.raster / branches / org.gvsig.raster_dataaccess_refactoring / org.gvsig.raster.lib / org.gvsig.raster.lib.impl / src / main / java / org / gvsig / raster / impl / provider / AbstractRasterProvider.java @ 2236

History | View | Annotate | Download (36.9 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.provider;
23

    
24
import java.awt.Image;
25
import java.awt.geom.AffineTransform;
26
import java.awt.geom.NoninvertibleTransformException;
27
import java.awt.geom.Point2D;
28
import java.io.File;
29
import java.security.NoSuchAlgorithmException;
30
import java.util.Collection;
31
import java.util.Date;
32
import java.util.Iterator;
33
import java.util.List;
34

    
35
import org.cresques.cts.IProjection;
36
import org.gvsig.compat.net.ICancellable;
37
import org.gvsig.fmap.dal.DALLocator;
38
import org.gvsig.fmap.dal.DataServerExplorer;
39
import org.gvsig.fmap.dal.DataStoreParameters;
40
import org.gvsig.fmap.dal.coverage.RasterLibrary;
41
import org.gvsig.fmap.dal.coverage.RasterLocator;
42
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
43
import org.gvsig.fmap.dal.coverage.datastruct.BandList;
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.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.FileNotOpenException;
51
import org.gvsig.fmap.dal.coverage.exception.InfoByPointException;
52
import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
53
import org.gvsig.fmap.dal.coverage.exception.InvalidSourceException;
54
import org.gvsig.fmap.dal.coverage.exception.ParsingException;
55
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
56
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
57
import org.gvsig.fmap.dal.coverage.exception.RmfSerializerException;
58
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
59
import org.gvsig.fmap.dal.coverage.store.RasterQuery;
60
import org.gvsig.fmap.dal.coverage.store.parameter.RasterDataParameters;
61
import org.gvsig.fmap.dal.coverage.store.parameter.RasterFileStoreParameters;
62
import org.gvsig.fmap.dal.coverage.store.parameter.RemoteStoreParameters;
63
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
64
import org.gvsig.fmap.dal.coverage.store.props.ColorTable;
65
import org.gvsig.fmap.dal.coverage.store.props.HistogramComputer;
66
import org.gvsig.fmap.dal.coverage.store.props.Metadata;
67
import org.gvsig.fmap.dal.coverage.store.props.Statistics;
68
import org.gvsig.fmap.dal.coverage.store.props.TimeSeries;
69
import org.gvsig.fmap.dal.coverage.store.props.Transparency;
70
import org.gvsig.fmap.dal.coverage.util.FileUtils;
71
import org.gvsig.fmap.dal.coverage.util.RasterUtils;
72
import org.gvsig.fmap.dal.exception.InitializeException;
73
import org.gvsig.fmap.dal.exception.OpenException;
74
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
75
import org.gvsig.fmap.dal.exception.ReadException;
76
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
77
import org.gvsig.fmap.dal.raster.spi.AbstractCoverageStoreProvider;
78
import org.gvsig.fmap.dal.resource.spi.ResourceProvider;
79
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemServerExplorer;
80
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemServerExplorerParameters;
81
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemStoreParameters;
82
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
83
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
84
import org.gvsig.raster.cache.tile.provider.TileServer;
85
import org.gvsig.raster.impl.buffer.SpiRasterQuery;
86
import org.gvsig.raster.impl.datastruct.BandListImpl;
87
import org.gvsig.raster.impl.datastruct.DatasetBandImpl;
88
import org.gvsig.raster.impl.datastruct.DefaultNoData;
89
import org.gvsig.raster.impl.datastruct.ExtentImpl;
90
import org.gvsig.raster.impl.datastruct.serializer.ColorTableRmfSerializer;
91
import org.gvsig.raster.impl.datastruct.serializer.NoDataRmfSerializer;
92
import org.gvsig.raster.impl.store.AbstractRasterDataParameters;
93
import org.gvsig.raster.impl.store.DefaultRasterStore;
94
import org.gvsig.raster.impl.store.properties.DataStoreColorInterpretation;
95
import org.gvsig.raster.impl.store.properties.SimpleProviderHistogramComputer;
96
import org.gvsig.raster.impl.store.properties.SimpleProviderStatistics;
97
import org.gvsig.raster.impl.store.rmf.ClassSerializer;
98
import org.gvsig.raster.impl.store.rmf.RmfBlocksManager;
99
import org.gvsig.raster.impl.store.serializer.ColorInterpretationRmfSerializer;
100
import org.gvsig.raster.impl.store.serializer.GeoInfoRmfSerializer;
101
import org.gvsig.raster.impl.store.serializer.GeoPointListRmfSerializer;
102
import org.gvsig.raster.impl.store.serializer.ProjectionRmfSerializer;
103
import org.gvsig.raster.impl.store.serializer.StatisticsRmfSerializer;
104
import org.gvsig.raster.util.DefaultProviderServices;
105
import org.gvsig.timesupport.Interval;
106
import org.gvsig.timesupport.Time;
107
import org.gvsig.tools.dynobject.DynObject;
108
import org.gvsig.tools.locator.LocatorException;
109
import org.slf4j.Logger;
110
import org.slf4j.LoggerFactory;
111

    
112
/**
113
 * Base class for all raster providers. 
114
 * @author Nacho Brodin (nachobrodin@gmail.com)
115
 */
116
public abstract class AbstractRasterProvider extends AbstractCoverageStoreProvider implements RasterProvider {
117
        /**
118
         * Flags que representan a las bandas visualizables
119
         */
120
        public static final int                   RED_BAND               = 0x01;
121
        public static final int                   GREEN_BAND             = 0x02;
122
        public static final int                   BLUE_BAND              = 0x04;
123
        public static final int                   ALPHA_BAND             = 0x08;
124
        
125
        protected int                             bandCount              = 1;
126
        private int[]                             dataType               = null;
127
        protected NoData                          noData                 = null;
128

    
129
        protected Statistics                      stats                  = null;
130
        protected HistogramComputer               histogram              = null;
131
        protected DataStoreParameters             param                  = null;
132
        protected DataStoreProviderServices       storeServices          = null;
133
        protected RmfBlocksManager                rmfBlocksManager       = null;
134
        protected ColorTable                      colorTable             = null;
135
        private ColorInterpretation               colorInterpretation    = null;
136
        protected TimeSeries                      serialInfo             = null;
137
        protected Transparency                    transparency           = null;
138
        protected TileServer                      tileServer             = null;
139
        protected GeoPointList                    geoPointList           = null;
140
        
141
        protected FileUtils                       fileUtil               = RasterLocator.getManager().getFileUtils();
142
        protected RasterUtils                     rasterUtil             = RasterLocator.getManager().getRasterUtils();
143
        
144
        protected IProjection                     proj                   = null;
145
        protected long                            fileSize               = 0;
146
        protected long                            bytesReaded            = 0;
147
        protected long                            lineCnt                = 0;
148
        protected String                          uri;
149
        protected String                          selectedSubdatasetID   = null;
150
        /**
151
         * Transformaci�n creada a partir de la informaci�n de georreferencia de la
152
         * propia imagen. Esta informaci�n est� en la cabecera o en ficheros
153
         * worldfile.
154
         */
155
        protected AffineTransform                 ownTransformation      = null;
156
        /**
157
         * Transformaci�n asignada de forma externa, bien desde el fichero rmf o
158
         * asignada directamente por el usuario.
159
         */
160
        protected AffineTransform                 externalTransformation = null;
161
        private static Logger                     logger                 = LoggerFactory.getLogger(AbstractRasterProvider.class.getName());
162
        
163
        public AbstractRasterProvider(AbstractRasterDataParameters params,
164
                        DataStoreProviderServices storeServices, DynObject metadata) {
165
                super(params, storeServices, metadata);
166
                if(params.getURI() != null) {
167
                        File f = new File(params.getURI());
168
                        if(f.exists())
169
                                setFileSize(f.length());
170
                }
171
                
172
                if(params.getURI() != null)
173
                        uri = translateFileName(params.getURI());
174
                
175
                ownTransformation = new AffineTransform();
176
                externalTransformation = new AffineTransform();
177
        }
178
        
179
        public AbstractRasterProvider(DataStoreParameters params,
180
                        DataStoreProviderServices storeServices, DynObject metadata) {
181
                super(params, storeServices, metadata);
182
                if(((RasterDataParameters)params).getURI() != null) {
183
                        File f = new File(((RasterDataParameters)params).getURI());
184
                        if(f.exists())
185
                                setFileSize(f.length());
186
                        if(params instanceof RemoteStoreParameters)
187
                                uri = translateFileName(((RasterDataParameters)params).getURI());
188
                }
189
                
190
                ownTransformation = new AffineTransform();
191
                externalTransformation = new AffineTransform();
192
        }
193
        
194
        public AbstractRasterProvider(String params) {
195
                super();
196
        }
197
        
198
        public AbstractRasterProvider() {
199
                super(null, null, null);
200
        }
201
        
202
        public String getFullName() {
203
                return getName();
204
        }
205
        
206
        public String getProviderName() {
207
                return getName();
208
        }
209
        
210
        public String[] getFormatList() {
211
                return null;
212
        }
213
        
214
        /**
215
         * Acciones de inicilizaci�n comunes a todos los drivers.
216
         * Este m�todo debe ser llamado explicitamente por el constructor de cada driver.
217
         * Estas son acciones de inicializaci�n que se ejecutan despu�s del constructor de cada driver.
218
         * Las acciones que hayan de ser realizadas antes se definen en el constructor de RasterDataset.
219
         */
220
        protected void init() {
221
        }
222
        
223
        public boolean isTiled() {
224
                return false;
225
        }
226
        
227
        public boolean isTimeSupported() {
228
                return false;
229
        }
230
        
231
        public RasterProvider cloneProvider() throws CloneException {
232
                try {
233
                        DataManagerProviderServices dataManager = (DataManagerProviderServices)DALLocator.getDataManager();
234
                        AbstractRasterProvider provider = (AbstractRasterProvider)dataManager.createProvider(storeServices, param);
235
                        //DefaultRasterProvider provider = singleDatasetInstance(storeServices, param);
236
                        // Estas van por referencia
237
                        provider.histogram = histogram;
238
                        provider.stats = stats;
239
                        return provider;
240
                } catch (ProviderNotRegisteredException e) {
241
                        e.printStackTrace();
242
                } catch (InitializeException e) {
243
                        e.printStackTrace();
244
                }
245
                return null;
246
        }
247
        
248
        /**
249
         * Factoria para abrir distintos tipos de raster.
250
         * @param fName Nombre del fichero.
251
         *
252
         * @return SingleDataset, o null si hay problemas.
253
         */
254
        @SuppressWarnings("unchecked")
255
        public static AbstractRasterProvider singleDatasetInstance(DataStoreProviderServices storeServices, String param) throws RasterDriverException {
256
                DataManagerProviderServices dataManager = (DataManagerProviderServices)DALLocator.getDataManager();
257
                //We have to locate a provider's name which manages the selected file
258
                //A FilesystemServerExplorer will give a getProviderNames service
259
                
260
                FilesystemServerExplorer serverExplorer = null;
261
                try {
262
                        FilesystemServerExplorerParameters paramsExplorer = (FilesystemServerExplorerParameters)dataManager.createServerExplorerParameters(FilesystemServerExplorer.NAME);
263
                        paramsExplorer.setRoot(File.separator);
264
                        serverExplorer = (FilesystemServerExplorer)dataManager.openServerExplorer(FilesystemServerExplorer.NAME, paramsExplorer);
265
                } catch (ValidateDataParametersException e) {
266
                        throw new RasterDriverException("Error validating parameters", e);
267
                } catch (InitializeException e) {
268
                        throw new RasterDriverException("Error creating a server explorer ", e);
269
                } catch (ProviderNotRegisteredException e) {
270
                        throw new RasterDriverException("Provider not registered", e);
271
                }
272
                
273
                //Gets the list of provider's name to manage the file
274
                File file = new File(param);
275
                List<String> provName = serverExplorer.getProviderNameList(file);
276
                if(provName.size() > 0) {
277
                        for (int i = 0; i < provName.size(); i++) {
278
                                //Gets the first provider what is not a TileProvider
279
                                if(provName.get(i).compareTo("Tile Store") != 0) {
280
                                        DataStoreParameters newparams;
281
                                        try {
282
                                                newparams = dataManager.createStoreParameters(provName.get(i));
283
                                                ((FilesystemStoreParameters)newparams).setFile(file); 
284
                                                if(storeServices == null)
285
                                                        storeServices = new DefaultRasterStore();
286
                                                return (AbstractRasterProvider)dataManager.createProvider(storeServices, newparams);
287
                                        } catch (InitializeException e) {
288
                                                throw new RasterDriverException("Error creating a server explorer ", e);
289
                                        } catch (ProviderNotRegisteredException e) {
290
                                                throw new RasterDriverException("Provider not registered", e);
291
                                        }
292
                                }
293
                        }
294
                }
295
                return null;
296
        }
297

    
298
        /**
299
         * Carga un fichero raster. Puede usarse para calcular el extent e instanciar
300
         * un objeto de este tipo.
301
         */
302
        abstract public RasterProvider load();
303

    
304
        /**
305
         * Obtiene el ancho de la imagen
306
         * @return Ancho de la imagen
307
         */
308
        abstract public double getWidth();
309

    
310
        /**
311
         * Obtiene el ancho de la imagen
312
         * @return Ancho de la imagen
313
         */
314
        abstract public double getHeight();
315

    
316
        /**
317
         * Asigna un nuevo Extent
318
         * @param e        Extent
319
         */
320
        public abstract void setView(Extent e);
321

    
322
        /**
323
         * Obtiene el extent asignado
324
         * @return        Extent
325
         */
326
        public abstract Extent getView();
327

    
328
        /**
329
         * Obtiene el valor del raster en la coordenada que se le pasa.
330
         * El valor ser� Double, Int, Byte, etc. dependiendo del tipo de
331
         * raster.
332
         * @param x        coordenada X
333
         * @param y coordenada Y
334
         * @return
335
         */
336
        abstract public Object getData(int x, int y, int band)throws InvalidSetViewException, FileNotOpenException, RasterDriverException;
337

    
338
        /**
339
         * Gets the set of data selected in the {@link RasterQuery}
340
         * @param q
341
         * @return
342
         * @throws RasterDriverException 
343
         * @throws ProcessInterruptedException 
344
         */
345
        public Buffer getDataSet(RasterQuery query) throws ProcessInterruptedException, RasterDriverException {
346
                SpiRasterQuery q = (SpiRasterQuery)query;
347
                loadBuffer(q);
348
                return q.getBufferForProviders();
349
        }
350
        
351
        /**
352
         * Load a buffer with the parameters. The buffer should already have been created 
353
         * inside the query structure <code>SpiRasterQuery</code> by the <code>RasterDataStore</code>. The other
354
         * parameters have been calculated too, all of them adjusted to the raster limits. The provider only 
355
         * have to read the parameters and load the buffer.
356
         * 
357
         * @param query
358
         * @throws ProcessInterruptedException
359
         * @throws RasterDriverException
360
         */
361
        abstract public void loadBuffer(SpiRasterQuery query) throws ProcessInterruptedException, RasterDriverException;
362

    
363
        abstract public int getBlockSize();
364
        
365
        abstract public int getOverviewHeight(int band, int overview) throws BandAccessException, RasterDriverException;
366

    
367
        /**
368
         * Informa de si el dataset soporta overviews o no.
369
         * @return true si soporta overviews y false si no las soporta.
370
         */
371
        abstract public boolean isOverviewsSupported();
372
        
373
        public void reload() {
374
                try {
375
                        loadFromRmf(getRmfBlocksManager());
376
                } catch (ParsingException e) {
377
                        logger.debug("No se ha podido leer el RMF", e);
378
                }
379
        }
380
        
381
        /**
382
         * Carga metadatos desde el fichero Rmf si estos existen
383
         * @param fName Nombre del fichero
384
         * @throws ParsingException
385
         */
386
        protected void loadFromRmf(RmfBlocksManager manager) throws ParsingException {
387
                if (!manager.checkRmf())
388
                        return;
389

    
390
                if (!new File(manager.getPath()).exists())
391
                        return;
392
                
393
                GeoInfoRmfSerializer geoInfoSerializer = new GeoInfoRmfSerializer(this);
394
                ColorTableRmfSerializer colorTableSerializer = new ColorTableRmfSerializer();
395
                GeoPointListRmfSerializer gcpSerializer = new GeoPointListRmfSerializer();
396
                NoDataRmfSerializer noDataSerializer = null;
397
                if(noData == null)
398
                        noData = new DefaultNoData(null, null, manager.getPath(), getBandCount());
399
                noDataSerializer = new NoDataRmfSerializer((DefaultNoData)noData);                        
400
                ColorInterpretationRmfSerializer colorInterpSerializer = new ColorInterpretationRmfSerializer();
401
                ProjectionRmfSerializer projectionRmfSerializer = new ProjectionRmfSerializer();
402
                StatisticsRmfSerializer statsRmfSerializer = new StatisticsRmfSerializer(getStatistics());
403

    
404
                manager.addClient(geoInfoSerializer);
405
                manager.addClient(colorTableSerializer);
406
                manager.addClient(gcpSerializer);
407
                manager.addClient(noDataSerializer);
408
                manager.addClient(colorInterpSerializer);
409
                manager.addClient(projectionRmfSerializer);
410
                manager.addClient(statsRmfSerializer);
411

    
412
                manager.read(null);
413

    
414
                manager.removeAllClients();
415

    
416
                if (colorTableSerializer.getResult() != null)
417
                        setColorTable((ColorTable) colorTableSerializer.getResult());
418

    
419
                if (colorInterpSerializer.getResult() != null) {
420
                        DataStoreColorInterpretation ci = (DataStoreColorInterpretation) colorInterpSerializer.getResult();
421
                        setColorInterpretation(ci);
422
                        getTransparency().setTransparencyBand(ci.getBand(DataStoreColorInterpretation.ALPHA_BAND));
423
                }
424

    
425
                if (projectionRmfSerializer.getResult() != null) {
426
                        proj = (IProjection) projectionRmfSerializer.getResult();
427
                }
428
                
429
                if( gcpSerializer.getResult() != null && 
430
                        gcpSerializer.getResult() instanceof GeoPointList && 
431
                        ((GeoPointList)gcpSerializer.getResult()).size() > 0) {
432
                        setGeoPointList((GeoPointList)gcpSerializer.getResult());
433
                }
434
        }
435

    
436
        /**
437
         * Obtiene el n�nero de bandas del fichero
438
         * @return Entero que representa el n�mero de bandas
439
         */
440
        public int getBandCount() {
441
                return bandCount;
442
        }
443

    
444
        /**
445
         * @return Returns the dataType.
446
         */
447
        public int[] getDataType() {
448
                return dataType;
449
        }
450

    
451
        /**
452
         * @param dataType The dataType to set.
453
         */
454
        public void setDataType(int[] dataType) {
455
                this.dataType = dataType;
456
        }
457

    
458
        public double getPixelSizeX() {
459
                return externalTransformation.getScaleX();
460
        }
461

    
462
        public double getPixelSizeY() {
463
                return externalTransformation.getScaleY();
464
        }
465

    
466
        public NoData getNoDataValue() {
467
                if(noData == null) {
468
                        noData = RasterLocator.getManager().getDataStructFactory().createNoData(null, null, getRMFFile(), getBandCount());
469
                        noData.setDataType(getDataType()[0]);
470
                }
471
                return noData;
472
        }
473
        
474
        public void setNoDataValue(NoData value) {
475
                this.noData = value;
476
        }
477

    
478
        /**
479
         * Dice si el fichero tiene georreferenciaci�n o no.
480
         * @return true si tiene georreferenciaci�n y false si no la tiene
481
         */
482
        public boolean isGeoreferenced() {
483
                return true;
484
        }
485

    
486
        /**
487
         * Convierte un punto desde coordenadas pixel a coordenadas del mundo.
488
         * @param pt Punto a transformar
489
         * @return punto transformado en coordenadas del mundo
490
         */
491
        public Point2D rasterToWorld(Point2D pt) {
492
                Point2D p = new Point2D.Double();
493
                externalTransformation.transform(pt, p);
494
                return p;
495
        }
496

    
497
        /**
498
         * Convierte un punto desde del mundo a coordenadas pixel.
499
         * @param pt Punto a transformar
500
         * @return punto transformado en coordenadas pixel
501
         */
502
        public Point2D worldToRaster(Point2D pt) {
503
                Point2D p = new Point2D.Double();
504
                try {
505
                        externalTransformation.inverseTransform(pt, p);
506
                } catch (NoninvertibleTransformException e) {
507
                        return pt;
508
                }
509
                return p;
510
        }
511

    
512
        /**
513
         * Calcula el extent en coordenadas del mundo real
514
         * @return Extent
515
         */
516
        public Extent getExtent() {
517
                return new ExtentImpl(        rasterToWorld(new Point2D.Double(0, 0)),
518
                                                        rasterToWorld(new Point2D.Double(getWidth(), getHeight())),
519
                                                        rasterToWorld(new Point2D.Double(getWidth(), 0)),
520
                                                        rasterToWorld(new Point2D.Double(0, getHeight())));
521
        }
522

    
523
        /**
524
         * Calcula el extent en coordenadas del mundo real sin rotaci�n. Solo coordenadas y tama�o de pixel
525
         * @return Extent
526
         */
527
        public Extent getExtentWithoutRot() {
528
                AffineTransform at = new AffineTransform(        externalTransformation.getScaleX(), 0,
529
                                                                                                        0, externalTransformation.getScaleY(),
530
                                                                                                        externalTransformation.getTranslateX(), externalTransformation.getTranslateY());
531
                Point2D p1 = new Point2D.Double(0, 0);
532
                Point2D p2 = new Point2D.Double(getWidth(), getHeight());
533
                at.transform(p1, p1);
534
                at.transform(p2, p2);
535
                return new ExtentImpl(p1, p2);
536
        }
537

    
538
        /**
539
         * ASigna el par�metro de inicializaci�n del driver.
540
         */
541
        public void setParam(DataStoreProviderServices provServices, DataStoreParameters param) {
542
                if(param instanceof RasterDataParameters)
543
                        this.uri = ((RasterDataParameters)param).getURI();
544
                this.param = param;
545
                this.storeServices = provServices;
546
        }
547

    
548
        abstract public int getOverviewWidth(int band, int overview) throws BandAccessException, RasterDriverException;
549
        
550
        public void selectSubdataset() {}
551
        
552
        /**
553
         * Selects the subdataset. This method will select
554
         * the rmf file. 
555
         */
556
        protected void selectSubdataset(String subdataset) {
557
                selectedSubdatasetID = subdataset;
558
                getRmfBlocksManager().setPath(getRMFFile());
559
        }
560

    
561
        /**
562
         * Obtiene el gestor de ficheros RMF
563
         * @return RmfBloksManager
564
         */
565
        public RmfBlocksManager getRmfBlocksManager() {
566
                String fileRMF = getRMFFile();
567
                if(fileRMF != null) {
568
                        if (rmfBlocksManager == null || fileRMF.compareTo(rmfBlocksManager.getPath()) != 0) {
569
                                rmfBlocksManager = new RmfBlocksManager(fileRMF);
570
                        }
571
                }
572
                return rmfBlocksManager;
573
        }
574
        
575
        public String getRMFFile() {
576
                String tail = selectedSubdatasetID == null ? ".rmf" : "-sd" + selectedSubdatasetID + ".rmf";
577
                File rmfFolder = (getDataParameters() != null && getDataParameters() instanceof RasterDataParameters) ? 
578
                                                ((RasterDataParameters)getDataParameters()).getRMFFolder() : 
579
                                                null;
580
                        
581
                String fileName = getURI();
582
                if(fileName.contains(File.separator)) {
583
                        if(!fileName.endsWith(File.separator)) {
584
                                fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1);
585
                                fileName = fileUtil.getNameWithoutExtension(fileName);
586
                        }
587
                }
588
                
589
                if(rmfFolder == null) {
590
                        if(getURI().contains(File.separator)) {
591
                                if(!getURI().endsWith(File.separator)) {
592
                                        String folder = getURI().substring(0, getURI().lastIndexOf(fileName));
593
                                        if((getDataParameters() != null && getDataParameters() instanceof RasterDataParameters))
594
                                                ((RasterDataParameters)getDataParameters()).setRMFFolder(new File(folder));
595
                                }
596
                        }
597
                        return fileUtil.getNameWithoutExtension(getURI()) + tail;
598
                } else {
599
                        return rmfFolder.getAbsolutePath() + File.separator + fileName + tail;
600
                }
601
                
602
        }
603
        
604
        protected String getRMFFileForRemoteServices(String layerName) {
605
                String md5 = "";
606
                try {
607
                        md5 = RasterLocator.getManager().getFileUtils().convertPathToMD5(uri);
608
                } catch (LocatorException e) {
609
                        logger.debug("Error getting the Locator", e);
610
                } catch (NoSuchAlgorithmException e) {
611
                        logger.debug("Error getting the algorithm MD5", e);
612
                }
613
                File path = new File(RasterLibrary.pathRMFRemote);
614
                if(!path.exists())
615
                        path.mkdir();
616
                return RasterLibrary.pathRMFRemote + File.separator + md5 + "-" + layerName + ".rmf";
617
        }
618

    
619
        public boolean isInside(Point2D p){
620
                //Realizamos los calculos solo si el punto est� dentro del extent de la imagen rotada, as� nos ahorramos los calculos
621
                //cuando el puntero est� fuera
622

    
623
                Point2D pt = new Point2D.Double();
624
                try {
625

    
626
                        getAffineTransform().inverseTransform(p, pt);
627
                        if(        pt.getX() >= 0 && pt.getX() < getWidth() &&
628
                                        pt.getY() >= 0 && pt.getY() < getHeight())
629
                                return true;
630
                } catch (NoninvertibleTransformException e) {
631
                        return false;
632
                }
633

    
634
                return false;
635
        }
636

    
637
        /**
638
         * Consulta de si un raster tiene rotaci�n o no.
639
         * @return true si tiene rotaci�n y false si no la tiene.
640
         */
641
        public boolean isRotated() {
642
                if(externalTransformation.getShearX() != 0 || externalTransformation.getShearY() != 0)
643
                        return true;
644
                return false;
645
        }
646
        
647
        public boolean isMultiFile() {
648
                return false;
649
        }
650
        
651
        public boolean isMosaic() {
652
                return false;
653
        }
654

    
655
        /**
656
         * Devuelve si el Dataset es reproyectable
657
         * @return
658
         */
659
        public boolean isReproyectable() {
660
                return true;
661
        }
662

    
663
        public String getWktProjection() {
664
                if(proj != null && RasterLocator.getManager().isCRSUtilSupported())
665
                        return RasterLocator.getManager().getCRSUtils().convertIProjectionToWkt((IProjection) proj);
666
                return null;
667
        }
668

    
669
        public void saveObjectToRmf(Class<?> class1, Object value) throws RmfSerializerException {
670
                ((DefaultProviderServices)RasterLocator.getManager().getProviderServices()).saveObjectToRmfFile(getRmfBlocksManager(), class1, value);
671
        }
672

    
673
        /**
674
         * Carga un objecto desde un serializador del tipo class1. Usa value para iniciar dicho
675
         * serializador
676
         *
677
         * @param class1
678
         * @param value
679
         * @return
680
         * @throws RmfSerializerException
681
         */
682
        private static Object loadObjectFromRmfFile(RmfBlocksManager blocksManager, Class<?> class1, Object value) throws RmfSerializerException {
683
                ClassSerializer serializerObject = ((DefaultProviderServices)RasterLocator.getManager().getProviderServices()).getSerializerObject(class1, value);
684

    
685
                if (serializerObject == null)
686
                        throw new RmfSerializerException("No se ha podido encontrar el serializador para el Rmf");
687

    
688
                if (!blocksManager.checkRmf())
689
                        throw new RmfSerializerException("Error al comprobar el fichero Rmf");
690

    
691
                blocksManager.addClient(serializerObject);
692
                try {
693
                        blocksManager.read(null);
694
                } catch (ParsingException e) {
695
                        throw new RmfSerializerException("Error al leer el fichero Rmf", e);
696
                }
697
                blocksManager.removeAllClients();
698

    
699
                return serializerObject.getResult();
700
        }
701

    
702
        public Object loadObjectFromRmf(Class<?> class1, Object value) throws RmfSerializerException {
703
                return loadObjectFromRmfFile(getRmfBlocksManager(), class1, value);
704
        }
705

    
706
        /**
707
         * Carga un objeto del fichero RMF especificado por parametro
708
         * @param file
709
         * @param class1
710
         * @param value
711
         * @return
712
         * @throws RmfSerializerException
713
         */
714
        public static Object loadObjectFromRmfFile(String file, Class<?> class1, Object value) throws RmfSerializerException {
715
                String fileRMF = RasterLocator.getManager().getFileUtils().getNameWithoutExtension(file) + ".rmf";
716
                RmfBlocksManager blocksManager = new RmfBlocksManager(fileRMF);
717
                return loadObjectFromRmfFile(blocksManager, class1, value);
718
        }
719

    
720
        /**
721
         * Guarda en el RMF el objecto actual en caso de que exista un serializador para el
722
         * @param value
723
         * @throws RmfSerializerException
724
         */
725
        public void saveObjectToRmf(Object value) throws RmfSerializerException {
726
                saveObjectToRmf(value.getClass(), value);
727
        }
728

    
729
        /**
730
         * Carga un objecto desde un serializador usando el tipo del mismo objeto pasado por parametro.
731
         * Usa value para iniciar dicho serializador
732
         * @param value
733
         * @return
734
         * @throws RmfSerializerException
735
         */
736
        public Object loadObjectFromRmf(Object value) throws RmfSerializerException {
737
                return loadObjectFromRmf(value.getClass(), value);
738
        }
739
        
740

    
741
        public double getCellSize() {
742
                try {
743
                        Extent e = getExtent();
744
                        double dCellsize = (e.getMax().getX() - e.getMin().getX() ) / getWidth();
745
                        return dCellsize;
746
                } catch (NullPointerException e) {
747
                        return 1;
748
                }
749
        }
750
        
751
        
752
        public RasterProvider newProvider() {
753
                return null;
754
        }
755
        
756
        public ColorTable getColorTable() {
757
                return colorTable;
758
        }
759
        
760
        public Image getImageLegend() {
761
                return null;
762
        }
763
        
764
        public void setColorTable(ColorTable value) {
765
                colorTable = value;
766
        }
767

    
768
        public Transparency getTransparency() {
769
                return transparency;
770
        }
771
        
772
        public Metadata getMetadata() {
773
                return null;
774
        }
775
        
776
        public ColorInterpretation getColorInterpretation() {
777
                return this.colorInterpretation;
778
        }
779

    
780
        /**
781
         * Asigna el objeto que contiene que contiene la interpretaci�n de
782
         * color por banda
783
         * @param DataStoreColorInterpretation
784
         */
785
        public void setColorInterpretation(ColorInterpretation colorInterpretation) {
786
                this.colorInterpretation = colorInterpretation;
787
        }
788
        
789
        /*
790
         * (non-Javadoc)
791
         * @see org.gvsig.raster.impl.dataset.RasterProvider#getStatistics()
792
         */
793
        public Statistics getStatistics() {
794
                if(stats == null) {
795
                        stats = new SimpleProviderStatistics(this);
796
                }
797
                return stats;
798
        }
799
        
800
        public void setStatistics(Statistics stats) throws RmfSerializerException {
801
                this.stats = stats;
802
                saveObjectToRmf(Statistics.class, stats);
803
        }
804
        
805
        public HistogramComputer getHistogramComputer() {
806
                if (histogram == null)
807
                        histogram = new SimpleProviderHistogramComputer(this);
808
                return histogram;
809
        }
810
        
811
    //****************************************************
812
        //*********Implementing Disposable methods************
813
        //****************************************************
814
    
815
    public void doDispose() {
816
            
817
    }
818
    
819
    //****************************************************
820
        //*****Implementing DataStoreProvider methods*********
821
        //****************************************************
822
    
823
        @Override
824
        public DataServerExplorer getExplorer() throws ReadException,
825
                        ValidateDataParametersException {
826
            /*DataManager manager = DALLocator.getDataManager();
827
                FilesystemServerExplorerParameters params;
828
                try {
829
                        params = (FilesystemServerExplorerParameters) manager
830
                                        .createServerExplorerParameters(FilesystemServerExplorer.NAME);
831
                        params.setRoot(((AbstractRasterStoreParameters)this.getDataParameters()).getFile().getParent());
832
                        return manager.createServerExplorer(params);
833
                } catch (DataException e) {
834
                        throw new ReadException(this.getName(), e);
835
                }*/
836
            return null;
837
        }
838
  
839
        
840
        /**
841
         * Returs the DataParameters
842
         * @return
843
         */
844
        public RasterDataParameters getDataParameters() {
845
                if(getDataStoreParameters() instanceof RasterDataParameters)
846
                        return (RasterDataParameters)getDataStoreParameters();
847
                return null;
848
        }
849

    
850
        public Iterator<?> getChilds() {
851
                return null;
852
        }
853

    
854
        public ResourceProvider getResource() {
855
                return null;
856
        }
857

    
858
        public Object getSourceId() {
859
                if( this.getDataParameters() instanceof RasterFileStoreParameters)
860
                        return ((RasterFileStoreParameters)this.getDataParameters()).getFile();
861
                else
862
                        return this.getDataParameters().getURI();
863
        }
864

    
865
        public void open() throws OpenException {
866
        }
867
        
868
        /**
869
         * Traduce el nombre del fichero por un alias asignado por el propio driver.
870
         * Cuando es traducido por un alias el driver intentar� abrir el alias y no el
871
         * fichero. Esto es util porque algunos formatos tienen la extensi�n en el
872
         * fichero de cabecera pero lo que se abre realmente es el fichero de datos.
873
         * @param fileName
874
         * @return
875
         */
876
        public String translateFileName(String fileName) {
877
                return fileName;
878
        }
879
        
880
        public String getFileSuffix() {
881
                return getURIOfFirstProvider().substring(getURIOfFirstProvider().lastIndexOf(".") + 1, getURIOfFirstProvider().length());
882
        }
883

    
884
        public String getURIOfFirstProvider() {
885
                return RasterLocator.getManager().getFileUtils().getFormatedRasterFileName(uri);
886
        }
887

    
888
        public String getURI() {
889
                return uri;
890
        }
891
        
892
        public void setFName(String n) {
893
                uri = n;
894
        }
895

    
896
        /**
897
         * Gets the size of the file if exists in Bytes
898
         * @return
899
         */
900
        public long getFileSize() {
901
                return fileSize;
902
        }
903

    
904
        public void setFileSize(long sz) {
905
                fileSize = sz;
906
        }
907

    
908
        public IProjection getProjection() {
909
                return proj;
910
        }
911

    
912
        public void setProjection(IProjection proj, boolean persist) throws RmfSerializerException {
913
                this.proj = proj;
914
                if(persist)
915
                        saveObjectToRmf(IProjection.class, proj);
916
        }
917

    
918
        protected long getTime() {
919
                return (new Date()).getTime();
920
        }
921

    
922
        public void setAffineTransform(AffineTransform t) {
923
                externalTransformation = (AffineTransform) t.clone();
924
        }
925

    
926
        public AffineTransform getAffineTransform() {
927
                return externalTransformation;
928
        }
929

    
930
        /**
931
         * Elimina la matriz de transformaci�n asociada al raster y que se tiene en
932
         * cuenta para el setView. Este reseteo tendr� en cuenta que si el raster
933
         * tiene asociado un rmf esta transformaci�n no ser� eliminada sino que se
934
         * asignar� la correspondiente al rmf existente.
935
         * @return devuelve true si tiene fichero rmf asociado y false si no lo tiene.
936
         */
937
        public void resetAffineTransform() {
938
                externalTransformation.setToIdentity();
939
        }
940

    
941
        public AffineTransform getOwnAffineTransform() {
942
                return ownTransformation;
943
        }
944

    
945
        public String getInfoByPoint(double x, double y, ICancellable cancellable) throws InfoByPointException {
946
                return null;
947
        }
948
        
949
        public String getInfoByPoint(int x, int y, Extent bbox, int w, int h, ICancellable cancellable) throws InfoByPointException {
950
                return null;
951
        }
952
        
953
        public void setTileServer(Class<?> tileServer) throws InitializeException {
954
                
955
        }
956
        
957
        public int[] getTileSize(int level) {
958
                return new int[]{0, 0};
959
        }
960
        
961
        public boolean isRasterEnclosed() {
962
                return false;
963
        }
964
        
965
        public int getSourceType() {
966
                if(getURI().startsWith("PG:host"))
967
                        return RasterDataStore.POSTGIS;
968
                if(getURI().startsWith("http:") || getURI().startsWith("https:"))
969
                        return RasterDataStore.REMOTE;
970
                return RasterDataStore.FILE;
971
        }
972
        
973
        /**
974
         * Most of providers don't need tiles. It those cases this method
975
         * won't execute anything. Only providers that use tile cache will need
976
         * implement this function, for instance TileProvider and MosaicProvider.
977
         */
978
        public void deleteLayerFromCache() {
979
                
980
        }
981
        
982
        public TimeSeries getTimeSerials() throws RmfSerializerException {
983
                if(serialInfo == null) {
984
                        serialInfo =  new DefaultTimeSerials();
985
                        loadObjectFromRmf(TimeSeries.class, serialInfo);
986
                        //Seleccionamos la primera serie por defecto. El usuario seleccionar� otra si la necesita
987
                        serialInfo.selectSerial(0);
988
                }
989
                return serialInfo;
990
        }
991
        
992
        public void setTimeSerials(TimeSeries serialInfo) throws RmfSerializerException {
993
                this.serialInfo = serialInfo;
994
                saveObjectToRmf(TimeSeries.class, serialInfo);
995
        }
996
        
997
        public long[] getFileSizeByProvider() {
998
                return new long[]{getFileSize()};
999
        }
1000
        
1001
        public String[] getURIByProvider() {
1002
                //For providers with one file
1003
                return new String[]{getURIOfFirstProvider()};
1004
        }
1005
        
1006
        public int[] getBandCountByProvider() {
1007
                return new int[]{getBandCount()};
1008
        }
1009
        
1010
        public int getInternalProviderCount() {
1011
                return 1;
1012
        }
1013
        
1014
        public RasterProvider getInternalProvider(int i) {
1015
                return this;
1016
        }
1017
        
1018
        public String getURIByBand(int band) {
1019
                //No matter which band be selected. In providers with one file is always the first URI
1020
                return getURIOfFirstProvider();
1021
        }
1022
        
1023
        public int getBandPositionByProvider(int band) {
1024
                return band;
1025
        }
1026
        
1027
        public int getSubdatasetCount() {
1028
                return 0;
1029
        }
1030
        
1031
        public void addFile(String file) throws InvalidSourceException {
1032
                //Do nothing
1033
        }
1034
        
1035
        public void removeFile(String file) {
1036
                //Do nothing                
1037
        }
1038
        
1039
        public boolean needEnhanced() {
1040
                return false;
1041
        }
1042
        
1043
        /**
1044
         * Gets the {@link Interval} of the store, that means the temporal
1045
         * interval where the store has valid data.
1046
         * In raster this method has sense in a mosaic. Therefore this has to be implemented 
1047
         * by the provider.
1048
         * @return
1049
         *         a time interval or null if there is not time support
1050
         */
1051
        public Interval getInterval() {
1052
                return null;
1053
        }
1054
        
1055
        /**
1056
         * Gets all the possible values of time for which the store has data.  
1057
         * In raster this method has sense in a mosaic. Therefore this has to be implemented 
1058
         * by the provider.
1059
         * @return
1060
         *         a collection of {@link Time} objects.
1061
         */
1062
        public Collection<?> getTimes() {
1063
                return null;
1064
        }
1065
        
1066
        /**
1067
         * Gets all the possible values of time for which the store has data
1068
         * and intersects with an interval.
1069
         * In raster this method has sense in a mosaic. Therefore this has to be implemented 
1070
         * by the provider.
1071
         * @param interval
1072
         *         the interval of time
1073
         * @return
1074
         *         a collection of {@link Time} objects.
1075
         */
1076
        public Collection<?> getTimes(Interval interval) {
1077
                return null;
1078
        }
1079
        
1080
        /**
1081
         * Gets the list of geo points associated to this provider
1082
         * @return
1083
         */
1084
        public GeoPointList getGeoPointList() {
1085
                return geoPointList;
1086
        }
1087
        
1088
        /**
1089
         * Sets the list of geo points associated to this provider
1090
         */
1091
        public void setGeoPointList(GeoPointList geoPointList) {
1092
                this.geoPointList = geoPointList;
1093
        }
1094
        
1095
        /**
1096
         * @deprecated This method should not be used. The store have a getDefaultBandList
1097
         * @return
1098
         */
1099
        public BandList getDefaultBandList() {
1100
                BandList bandList = new BandListImpl();
1101
                String[] uriByProvider = getURIByProvider();
1102
                int[] nBandsByProvider = getBandCountByProvider();
1103
                
1104
                for (int iProvider = 0; iProvider < uriByProvider.length; iProvider++) {
1105
                        for (int iBand = 0; iBand < nBandsByProvider[iProvider]; iBand++) {
1106
                                try {
1107
                                        bandList.addBand(new DatasetBandImpl(uriByProvider[iProvider], iBand, getDataType()[0], nBandsByProvider[iProvider]));
1108
                                } catch (BandNotFoundInListException e1) {
1109
                                }
1110
                        }
1111
                }
1112
                
1113
                int[] drawableBands = new int[bandList.getBandCount()];
1114
                for (int i = 0; i < bandList.getBandCount(); i++) {
1115
                        drawableBands[i] = i;
1116
                }
1117
                
1118
                bandList.setDrawableBands(drawableBands);
1119
                return bandList;
1120
        }
1121
        
1122
        public void close() {
1123
                if(transparency != null)
1124
                        transparency.dispose();
1125
                try {
1126
                        finalize();
1127
                } catch (Throwable e) {
1128
                }
1129
        }
1130
        
1131
        protected void finalize() throws Throwable {
1132
                dataType               = null;
1133
                noData                 = null;
1134
                stats                  = null;
1135
                histogram              = null;
1136
                param                  = null;
1137
                storeServices          = null;
1138
                rmfBlocksManager       = null;
1139
                colorTable             = null;
1140
                colorInterpretation    = null;
1141
                serialInfo             = null;
1142
                transparency           = null;
1143
                tileServer             = null;
1144
                fileUtil               = null;
1145
                rasterUtil             = null;
1146
                proj                   = null;
1147
                uri                    = null;
1148
                selectedSubdatasetID   = null;
1149
                ownTransformation      = null;
1150
                externalTransformation = null;
1151
        }
1152
}