Statistics
| Revision:

gvsig-raster / org.gvsig.raster.gdal / trunk / org.gvsig.raster.gdal / org.gvsig.raster.gdal.io / src / main / java / org / gvsig / raster / gdal / io / GdalProvider.java @ 2453

History | View | Annotate | Download (17.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.gdal.io;
23

    
24
import java.awt.geom.AffineTransform;
25
import java.io.BufferedReader;
26
import java.io.File;
27
import java.io.FileNotFoundException;
28
import java.io.FileReader;
29
import java.io.IOException;
30

    
31
import org.gvsig.fmap.dal.DALFileLocator;
32
import org.gvsig.fmap.dal.DALLocator;
33
import org.gvsig.fmap.dal.DataStore;
34
import org.gvsig.fmap.dal.coverage.RasterLocator;
35
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
36
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
37
import org.gvsig.fmap.dal.coverage.exception.BandAccessException;
38
import org.gvsig.fmap.dal.coverage.exception.FileNotOpenException;
39
import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
40
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
41
import org.gvsig.fmap.dal.coverage.exception.ParsingException;
42
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
43
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
44
import org.gvsig.fmap.dal.coverage.store.props.Transparency;
45
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
46
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
47
import org.gvsig.jgdal.GdalException;
48
import org.gvsig.metadata.MetadataLocator;
49
import org.gvsig.raster.cache.tile.provider.TileServer;
50
import org.gvsig.raster.impl.buffer.SpiRasterQuery;
51
import org.gvsig.raster.impl.datastruct.ExtentImpl;
52
import org.gvsig.raster.impl.provider.AbstractRasterProvider;
53
import org.gvsig.raster.impl.provider.RasterProvider;
54
import org.gvsig.raster.impl.provider.tile.FileTileServer;
55
import org.gvsig.raster.impl.store.AbstractRasterDataParameters;
56
import org.gvsig.raster.impl.store.DefaultRasterStore;
57
import org.gvsig.raster.impl.store.DefaultStoreFactory;
58
import org.gvsig.raster.impl.store.properties.DataStoreMetadata;
59
import org.gvsig.tools.ToolsLocator;
60
import org.gvsig.tools.dynobject.DynObject;
61
import org.gvsig.tools.extensionpoint.ExtensionPoint;
62
import org.gvsig.tools.extensionpoint.ExtensionPointManager;
63
import org.slf4j.Logger;
64
import org.slf4j.LoggerFactory;
65
/**
66
 * This class represents the data access for gdal formats.
67
 *
68
 * @author Nacho Brodin (nachobrodin@gmail.com)
69
 */
70
public class GdalProvider extends AbstractRasterProvider {
71
        public static String        NAME                     = "Gdal Store";
72
        public static String        DESCRIPTION              = "Gdal Raster file";
73
        public static final String  METADATA_DEFINITION_NAME = "GdalStore";
74
        private static final Logger logger                   = LoggerFactory.getLogger(GdalProvider.class);
75
        
76
        public static final String  FORMAT_GTiff    = "GTiff";
77
        public static final String  FORMAT_VRT      = "VRT";
78
        public static final String  FORMAT_NITF     = "NITF";
79
        public static final String  FORMAT_HFA      = "HFA";
80
        public static final String  FORMAT_ELAS     = "ELAS";
81
        public static final String  FORMAT_MEM      = "MEM";
82
        public static final String  FORMAT_BMP      = "BMP";
83
        public static final String  FORMAT_PCIDSK   = "PCIDSK";
84
        public static final String  FORMAT_ILWIS    = "ILWIS";
85
        public static final String  FORMAT_HDF4     = "HDF4Image";
86
        public static final String  FORMAT_PNM      = "PNM";
87
        public static final String  FORMAT_ENVI     = "ENVI";
88
        public static final String  FORMAT_EHDR     = "EHdr";
89
        public static final String  FORMAT_PAUX     = "PAux";
90
        public static final String  FORMAT_MFF      = "MFF";
91
        public static final String  FORMAT_MFF2     = "MFF2";
92
        public static final String  FORMAT_BT       = "BT";
93
        public static final String  FORMAT_IDA      = "IDA";
94
        public static final String  FORMAT_RMF      = "RMF";
95
        public static final String  FORMAT_RST      = "RST";
96
        public static final String  FORMAT_LEVELLER = "Leveller";
97
        public static final String  FORMAT_TERRAGEN = "Terragen";
98
        public static final String  FORMAT_ERS      = "ERS";
99
        public static final String  FORMAT_INGR     = "INGR";
100
        public static final String  FORMAT_GSAG     = "GSAG";
101
        public static final String  FORMAT_GSBG     = "GSBG";
102
        public static final String  FORMAT_ADRG     = "ADRG";
103
        public static final String  FORMAT_JP2      = "JPEG2000";
104
        public static final String  FORMAT_GRD      = "GRD";
105
        public static final int     BAND_HEIGHT     = 64;
106
        protected GdalNative        file            = null;
107
        private Extent              viewRequest     = null;
108
        protected static String[]   formatList      = null;
109
        
110
        public static void register() {
111
                ExtensionPointManager extensionPoints = ToolsLocator.getExtensionPointManager();
112
                registerFormats();
113
                
114
                ExtensionPoint point = extensionPoints.get("DefaultRasterProvider");
115
                point.append("reader", GdalProvider.NAME, GdalProvider.class);
116
                
117
                RasterLocator.getManager().getProviderServices().registerFileProvidersTiled(GdalProvider.class);
118
                
119
                DataManagerProviderServices dataman = (DataManagerProviderServices) DALLocator.getDataManager();
120
                if (dataman != null && !dataman.getStoreProviders().contains(NAME)) {
121
                        dataman.registerStoreProvider(NAME,
122
                                        GdalProvider.class, GdalDataParameters.class);
123
                }
124
                
125
                if(DALFileLocator.getFilesystemServerExplorerManager() != null)
126
                        DALFileLocator.getFilesystemServerExplorerManager().registerProvider(
127
                                        NAME, DESCRIPTION,
128
                                        GdalFilesystemServerExplorer.class);
129
                
130
                dataman.registerStoreFactory(NAME, DefaultStoreFactory.class);
131
        }
132
        
133
        private static void registerFormats() {
134
                formatList      = new String[] {
135
                                "bmp", 
136
                                "gif",
137
                                "tif",
138
                                "tiff",
139
                                "jpg",
140
                                "jpeg",
141
                                "png",
142
                                "vrt",
143
                                "dat", // Envi
144
                                "lan", // Erdas
145
                                "gis", // Erdas
146
                                "img", // Erdas
147
                                "pix", // PCI Geomatics
148
                                "aux", // PCI Geomatics
149
                                "adf", // ESRI Grids
150
                                "mpr", // Ilwis
151
                                "mpl", // Ilwis
152
                                "map", // PC Raster
153
                                "asc",
154
                                "pgm", //Ficheros PNM en escala de grises
155
                                "ppm", //Ficheros PNM en RGB
156
                                "rst", //IDRISIS
157
                                "rmf", //Raster Matrix Format
158
                                "nos",
159
                                "kap",
160
                                "hdr",
161
                                "raw",
162
                                "ers",
163
                                "xml",
164
                                "grd"/*,
165
                                "jp2"*/};
166
                for (int i = 0; i < formatList.length; i++) 
167
                        RasterLocator.getManager().getProviderServices().addFormat(formatList[i], GdalProvider.class);
168
        }
169
        
170
        public String[] getFormatList() {
171
                return formatList;
172
        }
173
        
174
        /**
175
         * Returns true if the extension is supported and false if doesn't
176
         * @param ext
177
         * @return
178
         */
179
        public boolean isExtensionSupported(String ext) {
180
                if(ext.indexOf(".") != -1)
181
                        ext = ext.substring(ext.lastIndexOf(".") + 1, ext.length());
182
                for (int i = 0; i < formatList.length; i++) {
183
                        if(formatList[i].compareTo(ext) == 0)
184
                                return true;
185
                }
186
                return false;
187
        }
188
        
189
        /**
190
         * Mandatory constructor to instantiate an empty provider
191
         */
192
        public GdalProvider() {
193
        }
194
        
195
        /**
196
         * Constructor. Abre el dataset.
197
         * @param proj Proyecci?n
198
         * @param fName Nombre del fichero
199
         * @throws NotSupportedExtensionException
200
         */
201
        public GdalProvider(String params) throws NotSupportedExtensionException {
202
                super(params);
203
                if(params instanceof String) {
204
                        GdalDataParameters p = new GdalDataParameters();
205
                        p.setURI((String)params);
206
                        super.init(p, null, ToolsLocator.getDynObjectManager()
207
                                        .createDynObject(
208
                                                        MetadataLocator.getMetadataManager().getDefinition(
209
                                                                        DataStore.METADATA_DEFINITION_NAME)));
210
                        init(p, null);
211
                }
212
        }
213
        
214
        public GdalProvider (GdalDataParameters params,
215
                        DataStoreProviderServices storeServices) throws NotSupportedExtensionException {
216
                super(params, storeServices, ToolsLocator.getDynObjectManager()
217
                                .createDynObject(
218
                                                MetadataLocator.getMetadataManager().getDefinition(
219
                                                                DataStore.METADATA_DEFINITION_NAME)));
220
                init(params, storeServices);
221
        }
222
        
223
        public GdalProvider(AbstractRasterDataParameters params,
224
                        DataStoreProviderServices storeServices, DynObject metadata) {
225
                super(params, storeServices, metadata);
226
        }
227
        
228
        /**
229
         * Creates file references and loads structures with the information and metadata
230
         * @param params load parameters
231
         * @throws NotSupportedExtensionException
232
         */
233
        public void init (AbstractRasterDataParameters params,
234
                        DataStoreProviderServices storeServices) throws NotSupportedExtensionException {
235
                try {
236
                        setParam(storeServices, params);
237
                        validRmf(params.getURI());
238
                        setFName(translateFileName(params.getURI()));
239
                        file = new GdalNative(translateFileName(params.getURI()));
240
                        setColorInterpretation(file.colorInterpr);
241
                        setColorTable(file.palette);
242
                        noData = file.getNoDataValue();
243
                        String wktProjection = file.getProjectionRef();
244
                        if(wktProjection != null && wktProjection != "") {
245
                                try {
246
                                        if(RasterLocator.getManager().isCRSUtilSupported())
247
                                                proj = RasterLocator.getManager().getCRSUtils().convertWktToIProjection(wktProjection);
248
                                } catch (Exception e) {
249
                                        logger.info("Error reading WKT from the raster provider", e);
250
                                }
251
                        }
252
                        //CrsWkt crs = new CrsWkt(wktProjection);
253
                        //IProjection proj = CRSFactory.getCRS("EPSG:23030");
254
                        ownTransformation = file.getOwnTransformation();
255
                        externalTransformation = (AffineTransform)ownTransformation.clone();
256
                        load();
257

    
258
                        if(file != null)
259
                                bandCount = file.getRasterCount();
260
                } catch (GdalException e) {
261
                        throw new NotSupportedExtensionException("Extension not supported", e);
262
                } catch(Exception e) {
263
                        System.out.println("Error en GdalOpen");
264
                        e.printStackTrace();
265
                        file = null;
266
                }
267

    
268
                //Obtenemos el tipo de dato de gdal y lo convertimos el de RasterBuf
269
                int[] dt = new int[file.getDataType().length];
270
                for (int i = 0; i < dt.length; i++)
271
                        dt[i] = GdalNative.getRasterBufTypeFromGdalType(file.getDataType()[i]);
272
                setDataType(dt);
273

    
274
                super.init();
275

    
276
                try {
277
                        loadFromRmf(getRmfBlocksManager());
278
                } catch (ParsingException e) {
279
                        //No lee desde rmf
280
                        logger.debug("Problems reading from the RMF file", e);
281
                }
282
        }
283

    
284
        /**
285
         * Comprueba si el fichero abierto es un RasterMetaFile o una imagen
286
         * raster.
287
         * @throws GdalException
288
         */
289
        private void validRmf(String file) throws GdalException {
290
                if(file.endsWith(".rmf")) {
291
                        File f = new File(file);
292
                        try {
293
                                FileReader fr = new FileReader(f);
294
                                BufferedReader br = new BufferedReader(fr);
295
                                char[] buffer = new char[5];
296
                                br.read(buffer);
297
                                StringBuffer st = new StringBuffer(new String(buffer));
298
                                br.close();
299
                                fr.close();
300
                                if(st.toString().equals("<?xml"))
301
                                        throw new GdalException("RasterMetaFile");
302
                        } catch (FileNotFoundException e) {
303
                                throw new GdalException("File Not Found");
304
                        } catch (IOException e) {
305
                                throw new GdalException("");
306
                        }
307
                }
308
        }
309

    
310
        public RasterProvider load() {
311
                return this;
312
        }
313
        
314
        public boolean isOpen() {
315
                if(file != null && file.isOpen())
316
                        return true;
317
                return false;
318
        }
319

    
320
        public String translateFileName(String fileName) {
321
                if(fileName.endsWith("hdr"))
322
                        return fileName.substring(0, fileName.lastIndexOf("."));
323
                return fileName;
324
        }
325

    
326
        /**
327
         * Asigna el extent de la vista actual. existe un fichero .rmf debemos hacer una transformaci?n
328
         * de la vista asignada ya que la petici?n viene en coordenadas del fichero .rmf y la vista (v)
329
         * ha de estar en coordenadas del fichero.
330
         */
331
        public void setView(Extent e) {
332
                viewRequest = new ExtentImpl(e);
333
        }
334

    
335
        public Extent getView() {
336
                return viewRequest;
337
        }
338

    
339
        public double getWidth() {
340
                return file.width;
341
        }
342

    
343
        public double getHeight() {
344
                return file.height;
345
        }
346

    
347
        /**
348
         * Read a line from the file
349
         * @param line
350
         * @param band
351
         * @return
352
         * @throws InvalidSetViewException
353
         * @throws FileNotOpenException
354
         * @throws RasterDriverException
355
         * @Deprecated This operation is deprecated because is not useful and in the future
356
         * it will not be maintained. The abstract operation has dissapear
357
         */
358
        public Object readCompleteLine(int line, int band)throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
359
                if(line > this.getHeight() || band > this.getBandCount())
360
                        throw new InvalidSetViewException("Request out of grid");
361

    
362
                try{
363
                        return file.readCompleteLine(line, band);
364
                }catch(GdalException e){
365
                        throw new RasterDriverException("Error reading data from Gdal library");
366
                }
367
        }
368

    
369
        public Object readBlock(int pos, int blockHeight, double scale)
370
                throws InvalidSetViewException, FileNotOpenException, RasterDriverException, ProcessInterruptedException {
371
                if(pos < 0)
372
                        throw new InvalidSetViewException("Request out of grid");
373

    
374
                if((pos + blockHeight) > getHeight())
375
                        blockHeight = Math.abs(((int)getHeight()) - pos);
376
                try{
377
                        return file.readBlock(pos, blockHeight, scale);
378
                }catch(GdalException e){
379
                        throw new RasterDriverException("Error reading data from Gdal library");
380
                }
381
        }
382

    
383
        public Object getData(int x, int y, int band)throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
384
                if(file != null){
385
                        if(x < 0 || y < 0 || x >= file.width || y >= file.height)
386
                                throw new InvalidSetViewException("Request out of grid");
387
                        Object[] data = file.getData(x, y);
388
                        return data[band];
389
                }
390
                throw new FileNotOpenException("GdalNative not exist");
391
        }
392

    
393
        @Override
394
        public void loadBuffer(SpiRasterQuery q) 
395
                        throws ProcessInterruptedException, RasterDriverException {
396
                setView(q.getAdjustedRequestBoundingBox());
397
                
398
                try {
399
                        file.readWindow(q.getBufferForProviders(), 
400
                                        q.getBandList(), 
401
                                        q.getAdjustedRequestBoundingBox(), 
402
                                        q.getAdjustedRequestPxWindow(),
403
                                        q.getTaskStatus());
404
                } catch (GdalException e) {
405
                        throw new RasterDriverException("Error reading data", e);
406
                }
407
                
408
        }
409
        
410
        public int getBlockSize(){
411
                if(file != null)
412
                        return file.getBlockSize();
413
                else
414
                        return 0;
415
        }
416

    
417
        public DataStoreMetadata getMetadata() {
418
                if(file != null)
419
                        return file.metadata;
420
                else
421
                        return null;
422
        }
423

    
424
        public Transparency getTransparency() {
425
                return file.fileTransparency;
426
        }
427

    
428
        public boolean isGeoreferenced() {
429
                if(file != null)
430
                        return file.georeferenced;
431
                else
432
                        return false;
433
        }
434

    
435
        /**
436
         * Informa de si el driver ha supersampleado en el ?ltimo dibujado. Es el driver el que colocar?
437
         * el valor de esta variable cada vez que dibuja.
438
         * @return true si se ha supersampleado y false si no se ha hecho.
439
         */
440
        public boolean isSupersampling() {
441
                if(file != null)
442
                        return file.isSupersampling;
443
                else
444
                        return false;
445
        }
446

    
447
        public GdalNative getNative(){
448
                return file;
449
        }
450

    
451
        public void setAffineTransform(AffineTransform t){
452
                super.setAffineTransform(t);
453
                file.setExternalTransform(t);
454
        }
455

    
456
        public int getOverviewCount(int band) throws BandAccessException, RasterDriverException {
457
                if(band >= getBandCount())
458
                        throw new BandAccessException("Wrong band");
459
                try {
460
                        return file.getRasterBand(band + 1).getOverviewCount();
461
                } catch (GdalException e) {
462
                        throw new RasterDriverException("");
463
                }
464
        }
465

    
466
        public int getOverviewWidth(int band, int overview) throws BandAccessException, RasterDriverException {
467
                if (band >= getBandCount())
468
                        throw new BandAccessException("Wrong band");
469
                try {
470
                        if (overview >= file.getRasterBand(band + 1).getOverviewCount())
471
                                throw new BandAccessException("Wrong overview count");
472
                        return file.getRasterBand(band + 1).getOverview(overview).getRasterBandXSize();
473
                } catch (GdalException e) {
474
                        throw new RasterDriverException("");
475
                }
476
        }
477

    
478
        public int getOverviewHeight(int band, int overview) throws BandAccessException, RasterDriverException {
479
                if (band >= getBandCount())
480
                        throw new BandAccessException("Wrong band");
481
                try {
482
                        if (overview >= file.getRasterBand(band + 1).getOverviewCount())
483
                                throw new BandAccessException("Wrong overview count");
484
                        return file.getRasterBand(band + 1).getOverview(overview).getRasterBandYSize();
485
                } catch (GdalException e) {
486
                        throw new RasterDriverException("");
487
                }
488
        }
489

    
490
        public boolean isOverviewsSupported() {
491
                return true;
492
        }
493

    
494
        public boolean isReproyectable() {
495
                return true;
496
        }
497
        
498
        public boolean needEnhanced() {
499
                return (getDataType()[0] != Buffer.TYPE_BYTE); 
500
                //Desconozco pq raz?n estaba esta condici?n. Quiz?s haya que volver a a?adirla
501
                //Eliminada 30/5/2013
502
                //|| (getBandCount() == 1 && getDataType()[0] == Buffer.TYPE_BYTE));
503
        }
504

    
505
        public String getName() {
506
                return NAME;
507
        }
508
        
509
        public void setStatus(RasterProvider provider) {
510
                if(provider instanceof GdalProvider) {
511
                        //Not implemented yet
512
                }
513
        }
514
        
515
        public TileServer getTileServer() {
516
                if(tileServer == null) {
517
                        DefaultRasterStore store = new DefaultRasterStore();
518
                        store.setProvider(this);
519
                        tileServer = new FileTileServer(store);
520
                }
521
                return tileServer;
522
        }
523
        
524
        public void close() {
525
                if(file != null){
526
                        file.dispose();
527
                }
528
                try {
529
                        finalize();
530
                } catch (Throwable e) {
531
                }
532
        }
533
        
534
        protected void finalize() throws Throwable {
535
                file           = null;
536
                viewRequest    = null;
537
                if(formatList != null) {
538
                        for (int i = 0; i < formatList.length; i++) {
539
                                formatList[i] = null;
540
                        }
541
                        formatList = null;
542
                }
543
                super.finalize();
544
        }
545
}