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 / provider / AbstractRasterProvider.java @ 4181

History | View | Annotate | Download (38.1 KB)

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

    
36
import org.apache.commons.io.FilenameUtils;
37
import org.cresques.cts.IProjection;
38
import org.slf4j.Logger;
39
import org.slf4j.LoggerFactory;
40

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

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

    
128
        protected int                             bandCount              = 1;
129
        private int[]                             dataType               = null;
130
        protected NoData                          noData                 = null;
131

    
132
        protected Statistics                      stats                  = null;
133
        protected HistogramComputer               histogram              = null;
134
        protected DataStoreParameters             param                  = null;
135
        protected DataStoreProviderServices       storeServices          = null;
136
        protected RmfBlocksManager                rmfBlocksManager       = null;
137
        protected ColorTable                      colorTable             = null;
138
        private ColorInterpretation               colorInterpretation    = null;
139
        protected TimeSeries                      serialInfo             = null;
140
        protected Transparency                    transparency           = null;
141
        protected TileServer                      tileServer             = null;
142
        protected GeoPointList                    geoPointList           = null;
143

    
144
        protected FileUtils                       fileUtil               = RasterLocator.getManager().getFileUtils();
145
        protected RasterUtils                     rasterUtil             = RasterLocator.getManager().getRasterUtils();
146

    
147
        protected IProjection                     proj                   = null;
148
        protected long                            fileSize               = 0;
149
        protected long                            bytesReaded            = 0;
150
        protected long                            lineCnt                = 0;
151
        protected URI                          uri;
152
        protected String                          selectedSubdatasetID   = null;
153
        /**
154
         * Transformaci?n creada a partir de la informaci?n de georreferencia de la
155
         * propia imagen. Esta informaci?n est? en la cabecera o en ficheros
156
         * worldfile.
157
         */
158
        protected AffineTransform                 ownTransformation      = null;
159
        /**
160
         * Transformaci?n asignada de forma externa, bien desde el fichero rmf o
161
         * asignada directamente por el usuario.
162
         */
163
        protected AffineTransform                 externalTransformation = null;
164
        private static Logger                     logger                 = LoggerFactory.getLogger(AbstractRasterProvider.class.getName());
165

    
166
        public AbstractRasterProvider(AbstractRasterDataParameters params,
167
                        DataStoreProviderServices storeServices, DynObject metadata) {
168
                super(params, storeServices, metadata);
169
                if(params.getURI() != null) {
170
                        File f = new File(params.getURI());
171
                        if(f.exists())
172
                                setFileSize(f.length());
173
                }
174

    
175
                if(params.getURI() != null)
176
                        uri = params.getURI();
177

    
178
                ownTransformation = new AffineTransform();
179
                externalTransformation = new AffineTransform();
180
        }
181

    
182
        public AbstractRasterProvider(DataStoreParameters params,
183
                        DataStoreProviderServices storeServices, DynObject metadata) {
184
                super(params, storeServices, metadata);
185
                URI uriParam = ((RasterDataParameters)params).getURI();
186
        if(uriParam != null) {
187
            if ("FILE".equalsIgnoreCase(uriParam.getScheme())) {
188
                File f = new File(uriParam);
189
                if (f.exists())
190
                    setFileSize(f.length());
191
            }
192
                        if(params instanceof RemoteStoreParameters)
193
                                uri = translateURI(uriParam);
194
                }
195

    
196
                ownTransformation = new AffineTransform();
197
                externalTransformation = new AffineTransform();
198
        }
199

    
200
        public AbstractRasterProvider(String params) {
201
                super();
202
        }
203

    
204
        public AbstractRasterProvider(URI uri) {
205
        super();
206
    }
207

    
208
        public AbstractRasterProvider() {
209
                super(null, null, null);
210
        }
211

    
212
        public String[] getFormatList() {
213
                return null;
214
        }
215

    
216
        /**
217
         * Acciones de inicilizaci?n comunes a todos los drivers.
218
         * Este m?todo debe ser llamado explicitamente por el constructor de cada driver.
219
         * Estas son acciones de inicializaci?n que se ejecutan despu?s del constructor de cada driver.
220
         * Las acciones que hayan de ser realizadas antes se definen en el constructor de RasterDataset.
221
         */
222
        protected void init() {
223
        }
224

    
225
        public boolean isRGB() {
226
                if(getDataType()[0] == Buffer.TYPE_BYTE) {
227
                        ColorInterpretation ci = getColorInterpretation();
228
                        return ci.isRGB();
229
                }
230
                return false;
231
        }
232

    
233
        public boolean isARGB() {
234
                if(getDataType()[0] == Buffer.TYPE_BYTE) {
235
                        ColorInterpretation ci = getColorInterpretation();
236
                        return ci.isRGBA();
237
                }
238
                return false;
239
        }
240

    
241
        public boolean isTiled() {
242
                return false;
243
        }
244

    
245
        public boolean isTimeSupported() {
246
                return false;
247
        }
248

    
249
        public RasterProvider cloneProvider() throws CloneException {
250
                try {
251
                        DataManagerProviderServices dataManager = (DataManagerProviderServices)DALLocator.getDataManager();
252
                        AbstractRasterProvider provider = (AbstractRasterProvider)dataManager.createProvider(storeServices, param);
253
                        //DefaultRasterProvider provider = singleDatasetInstance(storeServices, param);
254
                        // Estas van por referencia
255
                        provider.histogram = histogram;
256
                        provider.stats = stats;
257
                        return provider;
258
                } catch (ProviderNotRegisteredException e) {
259
                        e.printStackTrace();
260
                } catch (InitializeException e) {
261
                        e.printStackTrace();
262
                }
263
                return null;
264
        }
265

    
266
        /**
267
         * Factoria para abrir distintos tipos de raster.
268
         * @param fName Nombre del fichero.
269
         *
270
         * @return SingleDataset, o null si hay problemas.
271
         */
272
        @SuppressWarnings("unchecked")
273
        public static AbstractRasterProvider singleDatasetInstance(DataStoreProviderServices storeServices, String param) throws RasterDriverException {
274
                DataManagerProviderServices dataManager = (DataManagerProviderServices)DALLocator.getDataManager();
275
                //We have to locate a provider's name which manages the selected file
276
                //A FilesystemServerExplorer will give a getProviderNames service
277

    
278
                FilesystemServerExplorer serverExplorer = null;
279
                try {
280
                        FilesystemServerExplorerParameters paramsExplorer = (FilesystemServerExplorerParameters)dataManager.createServerExplorerParameters(FilesystemServerExplorer.NAME);
281
                        paramsExplorer.setRoot(File.separator);
282
                        serverExplorer = (FilesystemServerExplorer)dataManager.openServerExplorer(FilesystemServerExplorer.NAME, paramsExplorer);
283
                } catch (ValidateDataParametersException e) {
284
                        throw new RasterDriverException("Error validating parameters", e);
285
                } catch (InitializeException e) {
286
                        throw new RasterDriverException("Error creating a server explorer ", e);
287
                } catch (ProviderNotRegisteredException e) {
288
                        throw new RasterDriverException("Provider not registered", e);
289
                }
290

    
291
                //Gets the list of provider's name to manage the file
292
                File file = new File(param);
293
                List<String> provName = serverExplorer.getProviderNameList(file);
294
                if(provName.size() > 0) {
295
                        for (int i = 0; i < provName.size(); i++) {
296
                                //Gets the first provider what is not a TileProvider
297
                                if(provName.get(i).compareTo("Tile Store") != 0) {
298
                                        DataStoreParameters newparams;
299
                                        try {
300
                                                newparams = dataManager.createStoreParameters(provName.get(i));
301
                                                ((FilesystemStoreParameters)newparams).setFile(file);
302
                                                if(storeServices == null)
303
                                                        storeServices = new DefaultRasterStore();
304
                                                return (AbstractRasterProvider)dataManager.createProvider(storeServices, newparams);
305
                                        } catch (InitializeException e) {
306
                                                throw new RasterDriverException("Error creating a server explorer ", e);
307
                                        } catch (ProviderNotRegisteredException e) {
308
                                                throw new RasterDriverException("Provider not registered", e);
309
                                        }
310
                                }
311
                        }
312
                }
313
                return null;
314
        }
315

    
316
        /**
317
         * Carga un fichero raster. Puede usarse para calcular el extent e instanciar
318
         * un objeto de este tipo.
319
         */
320
        abstract public RasterProvider load();
321

    
322
        /**
323
         * Obtiene el ancho de la imagen
324
         * @return Ancho de la imagen
325
         */
326
        abstract public double getWidth();
327

    
328
        /**
329
         * Obtiene el ancho de la imagen
330
         * @return Ancho de la imagen
331
         */
332
        abstract public double getHeight();
333

    
334
        /**
335
         * Asigna un nuevo Extent
336
         * @param e        Extent
337
         */
338
        public abstract void setView(Extent e);
339

    
340
        /**
341
         * Obtiene el extent asignado
342
         * @return        Extent
343
         */
344
        public abstract Extent getView();
345

    
346
        /**
347
         * Obtiene el valor del raster en la coordenada que se le pasa.
348
         * El valor ser? Double, Int, Byte, etc. dependiendo del tipo de
349
         * raster.
350
         * @param x        coordenada X
351
         * @param y coordenada Y
352
         * @return
353
         */
354
        abstract public Object getData(int x, int y, int band)throws InvalidSetViewException, FileNotOpenException, RasterDriverException;
355

    
356
        /**
357
         * Gets the set of data selected in the {@link RasterQuery}
358
         * @param q
359
         * @return
360
         * @throws RasterDriverException
361
         * @throws ProcessInterruptedException
362
         */
363
        public Buffer getDataSet(SpiRasterQuery query) throws ProcessInterruptedException, RasterDriverException {
364
                SpiRasterQuery q = (SpiRasterQuery)query;
365
                loadBuffer(q);
366
                return q.getBufferForProviders();
367
        }
368

    
369
        /**
370
         * Load a buffer with the parameters. The buffer should already have been created
371
         * inside the query structure <code>SpiRasterQuery</code> by the <code>RasterDataStore</code>. The other
372
         * parameters have been calculated too, all of them adjusted to the raster limits. The provider only
373
         * have to read the parameters and load the buffer.
374
         *
375
         * @param query
376
         * @throws ProcessInterruptedException
377
         * @throws RasterDriverException
378
         */
379
        abstract public void loadBuffer(SpiRasterQuery query) throws ProcessInterruptedException, RasterDriverException;
380

    
381
        abstract public int getBlockSize();
382

    
383
        abstract public int getOverviewHeight(int band, int overview) throws BandAccessException, RasterDriverException;
384

    
385
        /**
386
         * Informa de si el dataset soporta overviews o no.
387
         * @return true si soporta overviews y false si no las soporta.
388
         */
389
        abstract public boolean isOverviewsSupported();
390

    
391
        public void reload() {
392
                try {
393
                        loadFromRmf(getRmfBlocksManager());
394
                } catch (ParsingException e) {
395
                        logger.debug("No se ha podido leer el RMF", e);
396
                }
397
        }
398

    
399
        /**
400
         * Carga metadatos desde el fichero Rmf si estos existen
401
         * @param fName Nombre del fichero
402
         * @throws ParsingException
403
         */
404
        protected void loadFromRmf(RmfBlocksManager manager) throws ParsingException {
405
                if (!manager.checkRmf())
406
                        return;
407

    
408
                if (!new File(manager.getPath()).exists())
409
                        return;
410

    
411
                GeoInfoRmfSerializer geoInfoSerializer = new GeoInfoRmfSerializer(this);
412
                ColorTableRmfSerializer colorTableSerializer = new ColorTableRmfSerializer();
413
                GeoPointListRmfSerializer gcpSerializer = new GeoPointListRmfSerializer();
414
                NoDataRmfSerializer noDataSerializer = null;
415
                if(noData == null)
416
                        noData = new DefaultNoData(null, null, manager.getPath(), getBandCount());
417
                noDataSerializer = new NoDataRmfSerializer((DefaultNoData)noData);
418
                ColorInterpretationRmfSerializer colorInterpSerializer = new ColorInterpretationRmfSerializer();
419
                ProjectionRmfSerializer projectionRmfSerializer = new ProjectionRmfSerializer();
420
                StatisticsRmfSerializer statsRmfSerializer = new StatisticsRmfSerializer(getStatistics());
421

    
422
                manager.addClient(geoInfoSerializer);
423
                manager.addClient(colorTableSerializer);
424
                manager.addClient(gcpSerializer);
425
                manager.addClient(noDataSerializer);
426
                manager.addClient(colorInterpSerializer);
427
                manager.addClient(projectionRmfSerializer);
428
                manager.addClient(statsRmfSerializer);
429

    
430
                manager.read(null);
431

    
432
                manager.removeAllClients();
433

    
434
                if (colorTableSerializer.getResult() != null)
435
                        setColorTable((ColorTable) colorTableSerializer.getResult());
436

    
437
                if (colorInterpSerializer.getResult() != null) {
438
                        DataStoreColorInterpretation ci = (DataStoreColorInterpretation) colorInterpSerializer.getResult();
439
                        setColorInterpretation(ci);
440
                        getTransparency().setColorInterpretation(ci);
441
                        getTransparency().setTransparencyBand(ci.getBand(DataStoreColorInterpretation.ALPHA_BAND));
442
                }
443

    
444
                if (projectionRmfSerializer.getResult() != null) {
445
                        proj = (IProjection) projectionRmfSerializer.getResult();
446
                }
447

    
448
                if( gcpSerializer.getResult() != null &&
449
                        gcpSerializer.getResult() instanceof GeoPointList &&
450
                        ((GeoPointList)gcpSerializer.getResult()).size() > 0) {
451
                        setGeoPointList((GeoPointList)gcpSerializer.getResult());
452
                }
453
        }
454

    
455
        /**
456
         * Obtiene el n?nero de bandas del fichero
457
         * @return Entero que representa el n?mero de bandas
458
         */
459
        public int getBandCount() {
460
                return bandCount;
461
        }
462

    
463
        /**
464
         * @return Returns the dataType.
465
         */
466
        public int[] getDataType() {
467
                return dataType;
468
        }
469

    
470
        /**
471
         * @param dataType The dataType to set.
472
         */
473
        public void setDataType(int[] dataType) {
474
                this.dataType = dataType;
475
        }
476

    
477
        public double getPixelSizeX() {
478
                return externalTransformation.getScaleX();
479
        }
480

    
481
        public double getPixelSizeY() {
482
                return externalTransformation.getScaleY();
483
        }
484

    
485
        public NoData getNoDataValue() {
486
                if(noData == null) {
487
                        noData = RasterLocator.getManager().getDataStructFactory().createDefaultNoData(getBandCount(), getDataType()[0]);
488
                        noData.setNoDataTransparent(false);
489
                        noData.setFileName(getRMFFile().getName());
490
                }
491
                return noData;
492
        }
493

    
494
        public void setNoDataValue(NoData value) {
495
                this.noData = value;
496
        }
497

    
498
        /**
499
         * Dice si el fichero tiene georreferenciaci?n o no.
500
         * @return true si tiene georreferenciaci?n y false si no la tiene
501
         */
502
        public boolean isGeoreferenced() {
503
                return true;
504
        }
505

    
506
        /**
507
         * Convierte un punto desde coordenadas pixel a coordenadas del mundo.
508
         * @param pt Punto a transformar
509
         * @return punto transformado en coordenadas del mundo
510
         */
511
        public Point2D rasterToWorld(Point2D pt) {
512
                Point2D p = new Point2D.Double();
513
                externalTransformation.transform(pt, p);
514
                return p;
515
        }
516

    
517
        /**
518
         * Convierte un punto desde del mundo a coordenadas pixel.
519
         * @param pt Punto a transformar
520
         * @return punto transformado en coordenadas pixel
521
         */
522
        public Point2D worldToRaster(Point2D pt) {
523
                Point2D p = new Point2D.Double();
524
                try {
525
                        externalTransformation.inverseTransform(pt, p);
526
                } catch (NoninvertibleTransformException e) {
527
                        return pt;
528
                }
529
                return p;
530
        }
531

    
532
        /**
533
         * Calcula el extent en coordenadas del mundo real
534
         * @return Extent
535
         */
536
        public Extent getExtent() {
537
                return new ExtentImpl(        rasterToWorld(new Point2D.Double(0, 0)),
538
                                                        rasterToWorld(new Point2D.Double(getWidth(), getHeight())),
539
                                                        rasterToWorld(new Point2D.Double(getWidth(), 0)),
540
                                                        rasterToWorld(new Point2D.Double(0, getHeight())));
541
        }
542

    
543
        /**
544
         * Calcula el extent en coordenadas del mundo real sin rotaci?n. Solo coordenadas y tama?o de pixel
545
         * @return Extent
546
         */
547
        public Extent getExtentWithoutRot() {
548
                AffineTransform at = new AffineTransform(        externalTransformation.getScaleX(), 0,
549
                                                                                                        0, externalTransformation.getScaleY(),
550
                                                                                                        externalTransformation.getTranslateX(), externalTransformation.getTranslateY());
551
                Point2D p1 = new Point2D.Double(0, 0);
552
                Point2D p2 = new Point2D.Double(getWidth(), getHeight());
553
                at.transform(p1, p1);
554
                at.transform(p2, p2);
555
                return new ExtentImpl(p1, p2);
556
        }
557

    
558
        /**
559
         * ASigna el par?metro de inicializaci?n del driver.
560
         */
561
        public void setParam(DataStoreProviderServices provServices, DataStoreParameters param) {
562
                if(param instanceof RasterDataParameters)
563
                        this.uri = ((RasterDataParameters)param).getURI();
564
                this.param = param;
565
                this.storeServices = provServices;
566
        }
567

    
568
        abstract public int getOverviewWidth(int band, int overview) throws BandAccessException, RasterDriverException;
569

    
570
        public void selectSubdataset() {}
571

    
572
        /**
573
         * Selects the subdataset. This method will select
574
         * the rmf file.
575
         */
576
        protected void selectSubdataset(String subdataset) {
577
                selectedSubdatasetID = subdataset;
578
                getRmfBlocksManager().setPath(getRMFFile().getPath());
579
        }
580

    
581
        /**
582
         * Obtiene el gestor de ficheros RMF
583
         * @return RmfBloksManager
584
         */
585
        public RmfBlocksManager getRmfBlocksManager() {
586
                File fileRMF = getRMFFile();
587
                if(fileRMF != null) {
588
                        if (rmfBlocksManager == null || !fileRMF.equals(rmfBlocksManager)) {
589
                                rmfBlocksManager = new RmfBlocksManager(fileRMF.getPath());
590
                        }
591
                }
592
                return rmfBlocksManager;
593
        }
594

    
595
    public File getRMFFile() {
596
        String tail = selectedSubdatasetID == null ? ".rmf" : "-sd" + selectedSubdatasetID + ".rmf";
597
        File rmfFolder =
598
            (getDataParameters() != null && getDataParameters() instanceof RasterDataParameters)
599
                ? ((RasterDataParameters) getDataParameters()).getRMFFolder() : null;
600

    
601
        String fileName;
602

    
603
        URI objUri = getURI();
604
        File file = new File(objUri);
605
        fileName = FilenameUtils.getBaseName(objUri.getPath());
606
        if (rmfFolder == null) {
607
            rmfFolder = file.getParentFile();
608
            if ((getDataParameters() != null && getDataParameters() instanceof RasterDataParameters)) {
609
                ((RasterDataParameters) getDataParameters()).setRMFFolder(rmfFolder);
610
            }
611
            return new File(fileName + tail);
612
        } else {
613
            return new File(rmfFolder.getAbsolutePath() + File.separator + fileName + tail);
614
        }
615
    }
616

    
617
        protected String getRMFFileForRemoteServices(String layerName) {
618
                String md5 = "";
619
                try {
620
                        md5 = RasterLocator.getManager().getFileUtils().convertPathToMD5(uri.getPath());
621
                } catch (LocatorException e) {
622
                        logger.debug("Error getting the Locator", e);
623
                } catch (NoSuchAlgorithmException e) {
624
                        logger.debug("Error getting the algorithm MD5", e);
625
                }
626
                File path = new File(RasterLibrary.pathRMFRemote);
627
                if(!path.exists())
628
                        path.mkdir();
629
                return RasterLibrary.pathRMFRemote + File.separator + md5 + "-" + layerName + ".rmf";
630
        }
631

    
632
        public boolean isInside(Point2D p){
633
                //Realizamos los calculos solo si el punto est? dentro del extent de la imagen rotada, as? nos ahorramos los calculos
634
                //cuando el puntero est? fuera
635

    
636
                Point2D pt = new Point2D.Double();
637
                try {
638

    
639
                        getAffineTransform().inverseTransform(p, pt);
640
                        if(        pt.getX() >= 0 && pt.getX() < getWidth() &&
641
                                        pt.getY() >= 0 && pt.getY() < getHeight())
642
                                return true;
643
                } catch (NoninvertibleTransformException e) {
644
                        return false;
645
                }
646

    
647
                return false;
648
        }
649

    
650
        /**
651
         * Consulta de si un raster tiene rotaci?n o no.
652
         * @return true si tiene rotaci?n y false si no la tiene.
653
         */
654
        public boolean isRotated() {
655
                if(externalTransformation.getShearX() != 0 || externalTransformation.getShearY() != 0)
656
                        return true;
657
                return false;
658
        }
659

    
660
        public boolean isMultiFile() {
661
                return false;
662
        }
663

    
664
        public boolean isMosaic() {
665
                return false;
666
        }
667

    
668
        /**
669
         * Devuelve si el Dataset es reproyectable
670
         * @return
671
         */
672
        public boolean isReproyectable() {
673
                return true;
674
        }
675

    
676
        public String getWktProjection() {
677
                if(proj != null && RasterLocator.getManager().isCRSUtilSupported())
678
                        return RasterLocator.getManager().getCRSUtils().convertIProjectionToWkt((IProjection) proj);
679
                return null;
680
        }
681

    
682
        public void saveObjectToRmf(Class<?> class1, Object value) throws RmfSerializerException {
683
        if (getRmfBlocksManager() != null) {
684
            ((DefaultProviderServices) RasterLocator.getManager().getProviderServices()).saveObjectToRmfFile(
685
                getRmfBlocksManager(), class1, value);
686
        }
687
        }
688

    
689
        /**
690
         * Carga un objecto desde un serializador del tipo class1. Usa value para iniciar dicho
691
         * serializador
692
         *
693
         * @param class1
694
         * @param value
695
         * @return
696
         * @throws RmfSerializerException
697
         */
698
        private static Object loadObjectFromRmfFile(RmfBlocksManager blocksManager, Class<?> class1, Object value) throws RmfSerializerException {
699
                ClassSerializer serializerObject = ((DefaultProviderServices)RasterLocator.getManager().getProviderServices()).getSerializerObject(class1, value);
700

    
701
                if (serializerObject == null)
702
                        throw new RmfSerializerException("No se ha podido encontrar el serializador para el Rmf");
703

    
704
                if (!blocksManager.checkRmf())
705
                        throw new RmfSerializerException("Error al comprobar el fichero Rmf");
706

    
707
                blocksManager.addClient(serializerObject);
708
                try {
709
                        blocksManager.read(null);
710
                } catch (ParsingException e) {
711
                        throw new RmfSerializerException("Error al leer el fichero Rmf", e);
712
                }
713
                blocksManager.removeAllClients();
714

    
715
                return serializerObject.getResult();
716
        }
717

    
718
        public Object loadObjectFromRmf(Class<?> class1, Object value) throws RmfSerializerException {
719
                return loadObjectFromRmfFile(getRmfBlocksManager(), class1, value);
720
        }
721

    
722
        /**
723
         * Carga un objeto del fichero RMF especificado por parametro
724
         * @param file
725
         * @param class1
726
         * @param value
727
         * @return
728
         * @throws RmfSerializerException
729
         */
730
        public static Object loadObjectFromRmfFile(String file, Class<?> class1, Object value) throws RmfSerializerException {
731
                String fileRMF = RasterLocator.getManager().getFileUtils().getNameWithoutExtension(file) + ".rmf";
732
                RmfBlocksManager blocksManager = new RmfBlocksManager(fileRMF);
733
                return loadObjectFromRmfFile(blocksManager, class1, value);
734
        }
735

    
736
        /**
737
         * Guarda en el RMF el objecto actual en caso de que exista un serializador para el
738
         * @param value
739
         * @throws RmfSerializerException
740
         */
741
        public void saveObjectToRmf(Object value) throws RmfSerializerException {
742
                saveObjectToRmf(value.getClass(), value);
743
        }
744

    
745
        /**
746
         * Carga un objecto desde un serializador usando el tipo del mismo objeto pasado por parametro.
747
         * Usa value para iniciar dicho serializador
748
         * @param value
749
         * @return
750
         * @throws RmfSerializerException
751
         */
752
        public Object loadObjectFromRmf(Object value) throws RmfSerializerException {
753
                return loadObjectFromRmf(value.getClass(), value);
754
        }
755

    
756

    
757
        public double getCellSize() {
758
                try {
759
                        Extent e = getExtent();
760
                        double dCellsize = (e.getMax().getX() - e.getMin().getX() ) / getWidth();
761
                        return dCellsize;
762
                } catch (NullPointerException e) {
763
                        return 1;
764
                }
765
        }
766

    
767

    
768
        public RasterProvider newProvider() {
769
                return null;
770
        }
771

    
772
        public ColorTable getColorTable() {
773
                return colorTable;
774
        }
775

    
776
        public Image getImageLegend() {
777
                return null;
778
        }
779

    
780
        public void setColorTable(ColorTable value) {
781
                colorTable = value;
782
        }
783

    
784
        public Transparency getTransparency() {
785
                return transparency;
786
        }
787

    
788
        public Metadata getMetadata() {
789
                return null;
790
        }
791

    
792
        public ColorInterpretation getColorInterpretation() {
793
                return this.colorInterpretation;
794
        }
795

    
796
        /**
797
         * Asigna el objeto que contiene que contiene la interpretaci?n de
798
         * color por banda
799
         * @param DataStoreColorInterpretation
800
         */
801
        public void setColorInterpretation(ColorInterpretation colorInterpretation) {
802
                this.colorInterpretation = colorInterpretation;
803
        }
804

    
805
        public Statistics getStatistics() {
806
                if(stats == null) {
807
                        stats = new SimpleProviderStatistics(this);
808
                }
809
                return stats;
810
        }
811

    
812
        public void setStatistics(Statistics stats) throws RmfSerializerException {
813
                this.stats = stats;
814
                saveObjectToRmf(Statistics.class, stats);
815
        }
816

    
817
        public HistogramComputer getHistogramComputer() {
818
                if (histogram == null)
819
                        histogram = new SimpleProviderHistogramComputer(this);
820
                return histogram;
821
        }
822

    
823
    //****************************************************
824
        //*********Implementing Disposable methods************
825
        //****************************************************
826

    
827
    public void doDispose() {
828

    
829
    }
830

    
831
    //****************************************************
832
        //*****Implementing DataStoreProvider methods*********
833
        //****************************************************
834

    
835
        @Override
836
        public DataServerExplorer getExplorer() throws ReadException,
837
                        ValidateDataParametersException {
838
            /*DataManager manager = DALLocator.getDataManager();
839
                FilesystemServerExplorerParameters params;
840
                try {
841
                        params = (FilesystemServerExplorerParameters) manager
842
                                        .createServerExplorerParameters(FilesystemServerExplorer.NAME);
843
                        params.setRoot(((AbstractRasterStoreParameters)this.getDataParameters()).getFile().getParent());
844
                        return manager.createServerExplorer(params);
845
                } catch (DataException e) {
846
                        throw new ReadException(this.getName(), e);
847
                }*/
848
            return null;
849
        }
850

    
851

    
852
        /**
853
         * Returs the DataParameters
854
         * @return
855
         */
856
        public RasterDataParameters getDataParameters() {
857
                if(getDataStoreParameters() instanceof RasterDataParameters)
858
                        return (RasterDataParameters)getDataStoreParameters();
859
                return null;
860
        }
861

    
862
        public Iterator<?> getChilds() {
863
                return null;
864
        }
865

    
866
        public ResourceProvider getResource() {
867
                return null;
868
        }
869

    
870
        public Object getSourceId() {
871
                if( this.getDataParameters() instanceof RasterFileStoreParameters)
872
                        return ((RasterFileStoreParameters)this.getDataParameters()).getFile();
873
                else
874
                        return this.getDataParameters().getURI();
875
        }
876

    
877
        public void open() throws OpenException {
878
        }
879

    
880
        /**
881
         * Traduce el nombre del fichero por un alias asignado por el propio driver.
882
         * Cuando es traducido por un alias el driver intentar? abrir el alias y no el
883
         * fichero. Esto es util porque algunos formatos tienen la extensi?n en el
884
         * fichero de cabecera pero lo que se abre realmente es el fichero de datos.
885
         * @param fileName
886
         * @return
887
         */
888
        public URI translateURI(URI uri) {
889
            return uri;
890
        }
891

    
892
        /*
893
         * Si alguna subclase necesita sobreescribir este m?todo, deber? hacerlo con el translateURI en lugar de este.
894
         */
895
        public final String translateFileName(String fileName) {
896
                return fileName;
897
        }
898

    
899

    
900
        public String getFileSuffix() {
901
            //FIXME: ?Sirve para algo?
902
                String path = getURIOfFirstProvider().getPath();
903
        return path.substring(path.lastIndexOf(".") + 1, path.length());
904
        }
905

    
906
        public URI getURIOfFirstProvider() {
907
            //FIXME: Esto que lo sobreescriban los proveedores que no son de archivo
908
//                return RasterLocator.getManager().getFileUtils().getFormatedRasterFileName(uri);
909
            return getURI();
910
        }
911

    
912
        public URI getURI() {
913
                return uri;
914
        }
915

    
916
        public void setFName(String n) {
917
            File file = new File(n);
918
            uri = file.toURI();
919
        }
920

    
921
    public String getName() {
922
        String pathName = null;
923
        try {
924
            URI x = this.getURI();
925
            pathName = x.getPath();
926
            return FilenameUtils.getBaseName(pathName);
927
        } catch (Throwable th1) {
928
            try {
929
                return FilenameUtils.getBaseName(this.uri.getPath());
930
            } catch (Throwable th2) {
931
                return this.uri.getPath();
932
            }
933
        }
934
    }
935

    
936
        public String getFullName() {
937
                return uri.getPath();
938
        }
939

    
940
        /**
941
         * Gets the size of the file if exists in Bytes
942
         * @return
943
         */
944
        public long getFileSize() {
945
                return fileSize;
946
        }
947

    
948
        public void setFileSize(long sz) {
949
                fileSize = sz;
950
        }
951

    
952
        public IProjection getProjection() {
953
                return proj;
954
        }
955

    
956
        public void setProjection(IProjection proj, boolean persist) throws RmfSerializerException {
957
                this.proj = proj;
958
                if(persist)
959
                        saveObjectToRmf(IProjection.class, proj);
960
        }
961

    
962
        protected long getTime() {
963
                return (new Date()).getTime();
964
        }
965

    
966
        public void setAffineTransform(AffineTransform t) {
967
                externalTransformation = (AffineTransform) t.clone();
968
        }
969

    
970
        public AffineTransform getAffineTransform() {
971
                return externalTransformation;
972
        }
973

    
974
        /**
975
         * Elimina la matriz de transformaci?n asociada al raster y que se tiene en
976
         * cuenta para el setView. Este reseteo tendr? en cuenta que si el raster
977
         * tiene asociado un rmf esta transformaci?n no ser? eliminada sino que se
978
         * asignar? la correspondiente al rmf existente.
979
         * @return devuelve true si tiene fichero rmf asociado y false si no lo tiene.
980
         */
981
        public void resetAffineTransform() {
982
                externalTransformation.setToIdentity();
983
        }
984

    
985
        public AffineTransform getOwnAffineTransform() {
986
                return ownTransformation;
987
        }
988

    
989
        public String getInfoByPoint(double x, double y, ICancellable cancellable) throws InfoByPointException {
990
                return null;
991
        }
992

    
993
        public String getInfoByPoint(int x, int y, Extent bbox, int w, int h, ICancellable cancellable) throws InfoByPointException {
994
                return null;
995
        }
996

    
997
        public void setTileServer(Class<?> tileServer) throws InitializeException {
998

    
999
        }
1000

    
1001
        public int[] getTileSize(int level) {
1002
                return new int[]{0, 0};
1003
        }
1004

    
1005
        public boolean isRasterEnclosed() {
1006
                return false;
1007
        }
1008

    
1009
        public int getSourceType() {
1010
            String scheme = getURI().getScheme();
1011
        if("PG".equalsIgnoreCase(scheme)){
1012
                   return RasterDataStore.POSTGIS;
1013
            } else if ("http".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme)) {
1014
            return RasterDataStore.REMOTE;
1015
            }
1016
        //"file".equalsIgnoreCase(scheme)
1017
                return RasterDataStore.FILE;
1018
        }
1019

    
1020
        /**
1021
         * Most of providers don't need tiles. It those cases this method
1022
         * won't execute anything. Only providers that use tile cache will need
1023
         * implement this function, for instance TileProvider and MosaicProvider.
1024
         */
1025
        public void deleteLayerFromCache() {
1026

    
1027
        }
1028

    
1029
        public TimeSeries getTimeSerials() throws RmfSerializerException {
1030
                if(serialInfo == null) {
1031
                        serialInfo =  new DefaultTimeSerials();
1032
                        loadObjectFromRmf(TimeSeries.class, serialInfo);
1033
                        //Seleccionamos la primera serie por defecto. El usuario seleccionar? otra si la necesita
1034
                        serialInfo.selectSerial(0);
1035
                }
1036
                return serialInfo;
1037
        }
1038

    
1039
        public void setTimeSerials(TimeSeries serialInfo) throws RmfSerializerException {
1040
                this.serialInfo = serialInfo;
1041
                saveObjectToRmf(TimeSeries.class, serialInfo);
1042
        }
1043

    
1044
        public long[] getFileSizeByProvider() {
1045
                return new long[]{getFileSize()};
1046
        }
1047

    
1048
        public URI[] getURIByProvider() {
1049
                //For providers with one file
1050
                return new URI[]{getURIOfFirstProvider()};
1051
        }
1052

    
1053
        public int[] getBandCountByProvider() {
1054
                return new int[]{getBandCount()};
1055
        }
1056

    
1057
        public int getInternalProviderCount() {
1058
                return 1;
1059
        }
1060

    
1061
        public RasterProvider getInternalProvider(int i) {
1062
                return this;
1063
        }
1064

    
1065
        public URI getURIByBand(int band) {
1066
                //No matter which band be selected. In providers with one file is always the first URI
1067
                return getURIOfFirstProvider();
1068
        }
1069

    
1070
        public int getBandPositionByProvider(int band) {
1071
                return band;
1072
        }
1073

    
1074
        public int getSubdatasetCount() {
1075
                return 0;
1076
        }
1077

    
1078
//        public void addFile(File file) throws InvalidSourceException {
1079
//                //Do nothing
1080
//        }
1081
//
1082
//        public void removeFile(File file) {
1083
//                //Do nothing
1084
//        }
1085

    
1086
        public boolean needEnhanced() {
1087
                return false;
1088
        }
1089

    
1090
        /**
1091
         * Gets the {@link Interval} of the store, that means the temporal
1092
         * interval where the store has valid data.
1093
         * In raster this method has sense in a mosaic. Therefore this has to be implemented
1094
         * by the provider.
1095
         * @return
1096
         *         a time interval or null if there is not time support
1097
         */
1098
        public Interval getInterval() {
1099
                return null;
1100
        }
1101

    
1102
        /**
1103
         * Gets all the possible values of time for which the store has data.
1104
         * In raster this method has sense in a mosaic. Therefore this has to be implemented
1105
         * by the provider.
1106
         * @return
1107
         *         a collection of {@link Time} objects.
1108
         */
1109
        public Collection<?> getTimes() {
1110
                return null;
1111
        }
1112

    
1113
        /**
1114
         * Gets all the possible values of time for which the store has data
1115
         * and intersects with an interval.
1116
         * In raster this method has sense in a mosaic. Therefore this has to be implemented
1117
         * by the provider.
1118
         * @param interval
1119
         *         the interval of time
1120
         * @return
1121
         *         a collection of {@link Time} objects.
1122
         */
1123
        public Collection<?> getTimes(Interval interval) {
1124
                return null;
1125
        }
1126

    
1127
        /**
1128
         * Gets the list of geo points associated to this provider
1129
         * @return
1130
         */
1131
        public GeoPointList getGeoPointList() {
1132
                return geoPointList;
1133
        }
1134

    
1135
        /**
1136
         * Sets the list of geo points associated to this provider
1137
         */
1138
        public void setGeoPointList(GeoPointList geoPointList) {
1139
                this.geoPointList = geoPointList;
1140
        }
1141

    
1142
        /**
1143
         * @deprecated This method should not be used. The store have a getDefaultBandList
1144
         * @return
1145
         */
1146
        public BandList getDefaultBandList() {
1147
                BandList bandList = new BandListImpl();
1148
                URI[] uriByProvider = getURIByProvider();
1149
                int[] nBandsByProvider = getBandCountByProvider();
1150

    
1151
                for (int iProvider = 0; iProvider < uriByProvider.length; iProvider++) {
1152
                        for (int iBand = 0; iBand < nBandsByProvider[iProvider]; iBand++) {
1153
                                try {
1154
                                        bandList.addBand(new DatasetBandImpl(uriByProvider[iProvider].getPath(), iBand, getDataType()[0], nBandsByProvider[iProvider]));
1155
                                } catch (BandNotFoundInListException e1) {
1156
                                }
1157
                        }
1158
                }
1159

    
1160
                int[] drawableBands = new int[bandList.getBandCount()];
1161
                for (int i = 0; i < bandList.getBandCount(); i++) {
1162
                        drawableBands[i] = i;
1163
                }
1164

    
1165
                bandList.setDrawableBands(drawableBands);
1166
                return bandList;
1167
        }
1168

    
1169
        public void close() {
1170
                if(transparency != null)
1171
                        transparency.dispose();
1172
                try {
1173
                        finalize();
1174
                } catch (Throwable e) {
1175
                }
1176
        }
1177

    
1178
        protected void finalize() throws Throwable {
1179
                dataType               = null;
1180
                noData                 = null;
1181
                stats                  = null;
1182
                histogram              = null;
1183
                param                  = null;
1184
                storeServices          = null;
1185
                rmfBlocksManager       = null;
1186
                colorTable             = null;
1187
                colorInterpretation    = null;
1188
                serialInfo             = null;
1189
                transparency           = null;
1190
                tileServer             = null;
1191
                fileUtil               = null;
1192
                rasterUtil             = null;
1193
                proj                   = null;
1194
                uri                    = null;
1195
                selectedSubdatasetID   = null;
1196
                ownTransformation      = null;
1197
                externalTransformation = null;
1198
        }
1199
}