Statistics
| Revision:

gvsig-raster / org.gvsig.raster.gdal / tags / pre-remove-jgdal / org.gvsig.raster.gdal / org.gvsig.raster.gdal.io / src / main / java / org / gvsig / raster / gdal / io / GdalProvider.java @ 3739

History | View | Annotate | Download (17.3 KB)

1
/* gvSIG. Geographic Information System of the Valencian Government
2
 *
3
 * Copyright (C) 2007-2008 Infrastructures and Transports Department
4
 * of the Valencian Government (CIT)
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 2
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 */
22
package org.gvsig.raster.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
                                "txt"/*,
166
                                "jp2"*/};
167
                for (int i = 0; i < formatList.length; i++) 
168
                        RasterLocator.getManager().getProviderServices().addFormat(formatList[i], GdalProvider.class);
169
        }
170
        
171
        public String[] getFormatList() {
172
                return formatList;
173
        }
174
                
175
        /**
176
         * Returns true if the extension is supported and false if doesn't
177
         * @param ext
178
         * @return
179
         */
180
        public boolean isExtensionSupported(String ext) {
181
                if(ext.indexOf(".") != -1)
182
                        ext = ext.substring(ext.lastIndexOf(".") + 1, ext.length());
183
                for (int i = 0; i < formatList.length; i++) {
184
                        if(formatList[i].compareTo(ext) == 0)
185
                                return true;
186
                }
187
                return false;
188
        }
189
        
190
        /**
191
         * Mandatory constructor to instantiate an empty provider
192
         */
193
        public GdalProvider() {
194
        }
195
        
196
        /**
197
         * Constructor. Abre el dataset.
198
         * @param proj Proyecci?n
199
         * @param fName Nombre del fichero
200
         * @throws NotSupportedExtensionException
201
         */
202
        public GdalProvider(String params) throws NotSupportedExtensionException {
203
                super(params);
204
                if(params instanceof String) {
205
                        GdalDataParameters p = new GdalDataParameters();
206
                        p.setURI((String)params);
207
                        super.init(p, null, ToolsLocator.getDynObjectManager()
208
                                        .createDynObject(
209
                                                        MetadataLocator.getMetadataManager().getDefinition(
210
                                                                        DataStore.METADATA_DEFINITION_NAME)));
211
                        init(p, null);
212
                }
213
        }
214
        
215
        public GdalProvider (GdalDataParameters params,
216
                        DataStoreProviderServices storeServices) throws NotSupportedExtensionException {
217
                super(params, storeServices, ToolsLocator.getDynObjectManager()
218
                                .createDynObject(
219
                                                MetadataLocator.getMetadataManager().getDefinition(
220
                                                                DataStore.METADATA_DEFINITION_NAME)));
221
                init(params, storeServices);
222
        }
223
        
224
        public GdalProvider(AbstractRasterDataParameters params,
225
                        DataStoreProviderServices storeServices, DynObject metadata) {
226
                super(params, storeServices, metadata);
227
        }
228
        
229
        /**
230
         * Creates file references and loads structures with the information and metadata
231
         * @param params load parameters
232
         * @throws NotSupportedExtensionException
233
         */
234
        public void init (AbstractRasterDataParameters params,
235
                        DataStoreProviderServices storeServices) throws NotSupportedExtensionException {
236
                try {
237
                        setParam(storeServices, params);
238
                        validRmf(params.getURI());
239
                        setFName(translateFileName(params.getURI()));
240
//                        GdalNative aux = new GdalNative(translateFileName(params.getURI()));
241
//                        long ptro = aux.getPtro();
242
//                        aux.delete();
243
                        file = new GdalNative(translateFileName(params.getURI()));
244
                        setColorInterpretation(file.colorInterpr);
245
                        setColorTable(file.palette);
246
                        noData = file.getNoDataValue();
247
                        String wktProjection = file.getProjectionRef();
248
                        if(wktProjection != null && wktProjection != "") {
249
                                try {
250
                                        if(RasterLocator.getManager().isCRSUtilSupported())
251
                                                proj = RasterLocator.getManager().getCRSUtils().convertWktToIProjection(wktProjection);
252
                                } catch (Exception e) {
253
                                        logger.info("Error reading WKT from the raster provider", e);
254
                                }
255
                        }
256
                        //CrsWkt crs = new CrsWkt(wktProjection);
257
                        //IProjection proj = CRSFactory.getCRS("EPSG:23030");
258
                        ownTransformation = file.getOwnTransformation();
259
                        externalTransformation = (AffineTransform)ownTransformation.clone();
260
                        load();
261

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

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

    
278
                super.init();
279

    
280
                try {
281
                        loadFromRmf(getRmfBlocksManager());
282
                } catch (ParsingException e) {
283
                        //No lee desde rmf
284
                        logger.debug("Problems reading from the RMF file", e);
285
                }
286
        }
287

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

    
314
        public RasterProvider load() {
315
                return this;
316
        }
317
        
318
        public boolean isOpen() {
319
                if(file != null && file.isOpen())
320
                        return true;
321
                return false;
322
        }
323

    
324
        public String translateFileName(String fileName) {
325
                if(fileName.endsWith("hdr"))
326
                        return fileName.substring(0, fileName.lastIndexOf("."));
327
                return fileName;
328
        }
329

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

    
339
        public Extent getView() {
340
                return viewRequest;
341
        }
342

    
343
        public double getWidth() {
344
                return file.width;
345
        }
346

    
347
        public double getHeight() {
348
                return file.height;
349
        }
350

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

    
366
                try{
367
                        return file.readCompleteLine(line, band);
368
                }catch(GdalException e){
369
                        throw new RasterDriverException("Error reading data from Gdal library");
370
                }
371
        }
372

    
373
        public Object readBlock(int pos, int blockHeight, double scale)
374
                throws InvalidSetViewException, FileNotOpenException, RasterDriverException, ProcessInterruptedException {
375
                if(pos < 0)
376
                        throw new InvalidSetViewException("Request out of grid");
377

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

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

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

    
421
        public DataStoreMetadata getMetadata() {
422
                if(file != null)
423
                        return file.metadata;
424
                else
425
                        return null;
426
        }
427

    
428
        public Transparency getTransparency() {
429
                return file.fileTransparency;
430
        }
431

    
432
        public boolean isGeoreferenced() {
433
                if(file != null)
434
                        return file.georeferenced;
435
                else
436
                        return false;
437
        }
438

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

    
451
        public GdalNative getNative(){
452
                return file;
453
        }
454

    
455
        public void setAffineTransform(AffineTransform t){
456
                super.setAffineTransform(t);
457
                file.setExternalTransform(t);
458
        }
459

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

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

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

    
494
        public boolean isOverviewsSupported() {
495
                return true;
496
        }
497

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

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