Statistics
| Revision:

gvsig-raster / org.gvsig.raster.mosaic / trunk / org.gvsig.raster.mosaic / org.gvsig.raster.mosaic.io / src / main / java / org / gvsig / raster / mosaic / io / MosaicProvider.java @ 2302

History | View | Annotate | Download (28.9 KB)

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

    
24
import java.awt.geom.AffineTransform;
25
import java.io.File;
26
import java.io.IOException;
27
import java.security.MessageDigest;
28
import java.security.NoSuchAlgorithmException;
29
import java.util.ArrayList;
30
import java.util.Date;
31
import java.util.List;
32

    
33
import org.cresques.cts.IProjection;
34
import org.gvsig.compat.net.ICancellable;
35
import org.gvsig.fmap.dal.DALFileLocator;
36
import org.gvsig.fmap.dal.DALLocator;
37
import org.gvsig.fmap.dal.DataStore;
38
import org.gvsig.fmap.dal.DataStoreParameters;
39
import org.gvsig.fmap.dal.coverage.RasterLocator;
40
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
41
import org.gvsig.fmap.dal.coverage.dataset.BufferParam;
42
import org.gvsig.fmap.dal.coverage.datastruct.BandList;
43
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
44
import org.gvsig.fmap.dal.coverage.datastruct.NoData;
45
import org.gvsig.fmap.dal.coverage.exception.BandAccessException;
46
import org.gvsig.fmap.dal.coverage.exception.BandNotFoundInListException;
47
import org.gvsig.fmap.dal.coverage.exception.BufferCreationException;
48
import org.gvsig.fmap.dal.coverage.exception.FileNotOpenException;
49
import org.gvsig.fmap.dal.coverage.exception.FileNotSupportedException;
50
import org.gvsig.fmap.dal.coverage.exception.HistogramException;
51
import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
52
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
53
import org.gvsig.fmap.dal.coverage.exception.ParsingException;
54
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
55
import org.gvsig.fmap.dal.coverage.exception.QueryException;
56
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
57
import org.gvsig.fmap.dal.coverage.exception.RmfSerializerException;
58
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
59
import org.gvsig.fmap.dal.coverage.store.RasterQuery;
60
import org.gvsig.fmap.dal.coverage.store.parameter.RasterDataParameters;
61
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
62
import org.gvsig.fmap.dal.coverage.store.props.HistogramComputer;
63
import org.gvsig.fmap.dal.coverage.store.props.Statistics;
64
import org.gvsig.fmap.dal.coverage.store.props.TimeSeries;
65
import org.gvsig.fmap.dal.coverage.util.MathUtils;
66
import org.gvsig.fmap.dal.exception.InitializeException;
67
import org.gvsig.fmap.dal.exception.OpenException;
68
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
69
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
70
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemServerExplorer;
71
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemServerExplorerParameters;
72
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemStoreParameters;
73
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
74
import org.gvsig.fmap.dal.spi.DataStoreProvider;
75
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
76
import org.gvsig.metadata.MetadataLocator;
77
import org.gvsig.raster.cache.tile.provider.TileServer;
78
import org.gvsig.raster.impl.buffer.SpiRasterQuery;
79
import org.gvsig.raster.impl.datastruct.BandListImpl;
80
import org.gvsig.raster.impl.datastruct.DatasetBandImpl;
81
import org.gvsig.raster.impl.datastruct.ExtentImpl;
82
import org.gvsig.raster.impl.provider.AbstractRasterProvider;
83
import org.gvsig.raster.impl.provider.RasterProvider;
84
import org.gvsig.raster.impl.provider.fusion.BufferListFusion;
85
import org.gvsig.raster.impl.provider.fusion.BufferListFusion.PixelSquareStructure;
86
import org.gvsig.raster.impl.store.AbstractRasterDataParameters;
87
import org.gvsig.raster.impl.store.DefaultRasterStore;
88
import org.gvsig.raster.impl.store.DefaultStoreFactory;
89
import org.gvsig.raster.impl.store.properties.DataStoreColorInterpretation;
90
import org.gvsig.raster.impl.store.properties.DataStoreTransparency;
91
import org.gvsig.raster.impl.store.properties.SimpleProviderHistogramComputer;
92
import org.gvsig.raster.impl.store.properties.SimpleProviderStatistics;
93
import org.gvsig.raster.mosaic.io.downloader.MosaicTileServer;
94
import org.gvsig.timesupport.RelativeInstant;
95
import org.gvsig.timesupport.Time;
96
import org.gvsig.timesupport.TimeSupportLocator;
97
import org.gvsig.tools.ToolsLocator;
98
import org.gvsig.tools.locator.LocatorException;
99
import org.slf4j.Logger;
100
import org.slf4j.LoggerFactory;
101
/**
102
 * Data provider for raster mosaics
103
 *
104
 * @author Nacho Brodin (nachobrodin@gmail.com)
105
 */
106
public class MosaicProvider extends AbstractRasterProvider {
107
        public static String                     NAME                     = "Mosaic Raster";
108
        public static String                     DESCRIPTION              = "Mosaic Raster Support";
109
        public final String                      METADATA_DEFINITION_NAME = NAME;
110
        private static final Logger              logger                   = LoggerFactory.getLogger(MosaicProvider.class);
111
        private boolean                          open                     = false;
112
        private MathUtils                        math                     = RasterLocator.getManager().getMathUtils();
113
    protected static String[]                formatList               = null;
114
    //private MosaicRasterFormat               mosaicRasterFormat       = null;
115
    private List<RasterProvider>             providerList             = null;
116
    private double                           pixelSize                = 0D;
117
    private Extent                           extent                   = null;
118
        private double                           width                    = 0;
119
        private double                           height                   = 0;
120
        private Extent                           viewRequest              = null;
121
        private ArrayList<RasterProvider>        selectedProviders        = new ArrayList<RasterProvider>();
122
        private boolean                          bandCountCalculated      = false;
123
    
124
        public static void register() {
125
                DataManagerProviderServices dataman = (DataManagerProviderServices) DALLocator.getDataManager();
126
                registerFormats();
127
                
128
                if (dataman != null && !dataman.getStoreProviders().contains(NAME)) {
129
                        dataman.registerStoreProvider(NAME,
130
                                        MosaicProvider.class, MosaicDataParametersImpl.class);
131
                }
132
                
133
                if(DALFileLocator.getFilesystemServerExplorerManager() != null)
134
                        DALFileLocator.getFilesystemServerExplorerManager().registerProvider(
135
                                        NAME, DESCRIPTION,
136
                                        MosaicServerExplorer.class);
137
                
138
                if (!dataman.getExplorerProviders().contains(NAME)) {
139
                        dataman.registerExplorerProvider(NAME, MosaicServerExplorer.class, MosaicServerExplorerParameters.class);
140
                }
141
                
142
                dataman.registerStoreFactory(NAME, DefaultStoreFactory.class);
143
        }
144
        
145
        @SuppressWarnings("deprecation")
146
        private static void registerFormats() {
147
                formatList      = new String[] {"mrf"};
148
                for (int i = 0; i < formatList.length; i++) 
149
                        RasterLocator.getManager().addFormat(formatList[i], MosaicProvider.class);
150
        }
151
        
152
        public String[] getFormatList() {
153
                return formatList;
154
        }
155
        
156
        /**
157
         * Returns true if the extension is supported and false if doesn't
158
         * @param ext
159
         * @return
160
         */
161
        public boolean isExtensionSupported(String ext) {
162
                if(ext.indexOf(".") != -1)
163
                        ext = ext.substring(ext.lastIndexOf(".") + 1, ext.length());
164
                for (int i = 0; i < formatList.length; i++) {
165
                        if(formatList[i].compareTo(ext) == 0)
166
                                return true;
167
                }
168
                return false;
169
        }
170
        
171
        public MosaicProvider() {
172
        }
173
        
174
        /**
175
         * Opens the dataset.
176
         * @param proj Projection
177
         * @param fName File name
178
         * @throws NotSupportedExtensionException
179
         */
180
        public MosaicProvider(String params) throws NotSupportedExtensionException, OpenException {
181
                super(params);
182
                if(params instanceof String) {
183
                        MosaicDataParametersImpl p = new MosaicDataParametersImpl();
184
                        p.setURI((String)params);
185
                        super.init(p, null, ToolsLocator.getDynObjectManager()
186
                                        .createDynObject(
187
                                                        MetadataLocator.getMetadataManager().getDefinition(
188
                                                                        DataStore.METADATA_DEFINITION_NAME)));
189
                        init(p, null);
190
                }
191
        }
192
        
193
        public MosaicProvider (MosaicDataParametersImpl params,
194
                        DataStoreProviderServices storeServices) throws NotSupportedExtensionException, OpenException {
195
                super(params, storeServices, ToolsLocator.getDynObjectManager()
196
                                .createDynObject(
197
                                                MetadataLocator.getMetadataManager().getDefinition(
198
                                                                DataStore.METADATA_DEFINITION_NAME)));
199
                init(params, storeServices);
200
        }
201

    
202
        /**
203
         * Build file references
204
         * @param proj Projection
205
         * @param param Load parameters
206
         * @throws NotSupportedExtensionException
207
         */
208
        public void init (AbstractRasterDataParameters params,
209
                        DataStoreProviderServices storeServices) throws NotSupportedExtensionException, OpenException {
210
                setParam(storeServices, params);
211
                
212
                openFromMrf();
213
                
214
                calcMetadataFromParams();
215
                
216
                super.init();
217
                
218
                try {
219
                        loadFromRmf(getRmfBlocksManager());
220
                } catch (ParsingException e) {
221
                        //No lee desde rmf
222
                }
223
                
224
                open = true;
225
        }
226
        
227
        /**
228
         * Calculates metadata using the parameters
229
         */
230
        private void calcMetadataFromParams() {
231
                uri = getParameters().getURI();
232
                providerList = getParameters().getProviders();
233
                pixelSize = getParameters().getPixelSize();
234
                
235
                //Se le pone banda de transparencia siempre
236
                if(providerList.get(0).getDataType()[0] == Buffer.TYPE_BYTE) {
237
                        transparency = new DataStoreTransparency();
238
                        transparency.setTransparencyBand(getBandCount() - 1);
239
                } else 
240
                        transparency = providerList.get(0).getTransparency();
241
                
242
                extent = null;
243
                for (int i = 0; i < providerList.size(); i++) {
244
                        if(extent == null)
245
                                extent = providerList.get(i).getExtent();
246
                        else
247
                                extent = extent.encloseBoundinBoxes(providerList.get(i).getExtent());
248
                        
249
                        //Usa el primer NoData de la primera imagen que tenga un valor asignado
250
                        if(noData == null && providerList.get(i).getNoDataValue().isDefined()) {
251
                                noData = providerList.get(i).getNoDataValue();
252
                                noData.setFileName(getParameters().getURI());
253
                        }
254
                }
255
                width = extent.width() / pixelSize;
256
                height = extent.height() / pixelSize;
257
                
258
                ownTransformation = new AffineTransform(pixelSize, 0, 
259
                                                        0, -pixelSize, 
260
                                                        extent.getULX(), extent.getULY());
261
                externalTransformation = (AffineTransform) ownTransformation.clone();
262
                
263
                ((MosaicDataParametersImpl)getParameters()).resetParamsChanged();
264
        }
265

    
266
        public ColorInterpretation getColorInterpretation() {
267
                if(super.getColorInterpretation() == null) {
268
                        ColorInterpretation ci = null;
269
                        for (int i = 0; i < providerList.size(); i++) {
270
                                RasterProvider prv = providerList.get(i);
271
                                if(prv.getBandCount() == getBandCount() && prv.getColorInterpretation() != null) {
272
                                        ci = prv.getColorInterpretation().cloneColorInterpretation();
273
                                }
274
                        }
275

    
276
                        if(ci == null) {
277
                                if(getDataType()[0] == Buffer.TYPE_BYTE) {
278
                                        if(getBandCount() == 4)
279
                                                ci = DataStoreColorInterpretation.createARGBInterpretation();
280
                                        if(getBandCount() == 3)
281
                                                ci = DataStoreColorInterpretation.createRGBInterpretation();
282
                                        if(getBandCount() == 1)
283
                                                ci = DataStoreColorInterpretation.createPaletteInterpretation();
284
                                } else {
285
                                        if(getBandCount() == 1)
286
                                                ci = DataStoreColorInterpretation.createGrayInterpretation();
287
                                        else 
288
                                                ci = DataStoreColorInterpretation.createDefaultInterpretation(getBandCount());
289
                                }
290
                        }
291

    
292
                        setColorInterpretation(ci);
293
                }
294
                return super.getColorInterpretation();
295
        }
296
        
297
        /**
298
         * Loads the specific provider
299
         * @param file
300
         * @return
301
         * @throws NotSupportedExtensionException
302
         * @throws FileNotSupportedException 
303
         */
304
        @SuppressWarnings("unchecked")
305
        private RasterProvider loadProvider(String file, DataStoreProviderServices storeServices) throws ProviderNotRegisteredException, InitializeException {
306
                DataManagerProviderServices dataManager = (DataManagerProviderServices)DALLocator.getDataManager();
307
                DataStoreProvider prov = null;
308

    
309
                if(file != null) {
310
                        //We have to locate a provider's name which manages the selected file
311
                        //A FilesystemServerExplorer will give a getProviderNames service
312
                        FilesystemServerExplorerParameters paramsExplorer = (FilesystemServerExplorerParameters)dataManager.createServerExplorerParameters(FilesystemServerExplorer.NAME);
313
                        FilesystemServerExplorer serverExplorer = null;
314
                        try {
315
                                paramsExplorer.setRoot(File.separator);
316
                                serverExplorer = (FilesystemServerExplorer)dataManager.openServerExplorer(FilesystemServerExplorer.NAME, paramsExplorer);
317
                        } catch (ValidateDataParametersException e) {
318
                                throw new InitializeException(e);
319
                        }
320
                        File f = new File(file);
321
                        //Gets the list of provider's name to manage the file
322
                        List<String> provName = serverExplorer.getProviderNameList(f);
323
                        if(provName.size() > 0) {
324
                                for (int i = 0; i < provName.size(); i++) {
325
                                        //Gets the first provider what is not a TileProvider
326
                                        if(provName.get(i).compareTo("Tile Store") != 0) {
327
                                                DataStoreParameters newparams = dataManager.createStoreParameters(provName.get(i));
328
                                                ((FilesystemStoreParameters)newparams).setFile(f); 
329
                                                prov = dataManager.createProvider(storeServices, newparams);
330
                                        }
331
                                }
332
                        }
333
                }
334

    
335
                if(prov != null && prov instanceof RasterProvider) {
336
                        if(((RasterProvider)prov).isRotated())
337
                                throw new InitializeException("Rotation not supported tiling files", new Throwable());
338

    
339
                        return (RasterProvider)prov;
340
                }
341
                
342
                return null;
343
        }
344
        
345
        /**
346
         * Open from a .mrf file. 
347
         * This method loads all providers and adds these to the parameters
348
         * @throws OpenException
349
         */
350
        private void openFromMrf() throws OpenException {
351
                if(getParameters().getURI() != null && new File(getParameters().getURI()).exists()) {
352
                        try {
353
                                if(getParameters().getProviders() != null)
354
                                        getParameters().getProviders().clear();
355
                                MosaicRasterFormat multiFileFormat = new MosaicRasterFormat();
356
                                multiFileFormat = MosaicRasterFormatSerializer.read(multiFileFormat, getParameters().getURI());
357
                                for (int i = 0; i < multiFileFormat.getNumberOfFiles(); i++) {
358
                                        try {
359
                                                File file = new File(multiFileFormat.getPathToFile(i));
360
                                                if(file.exists()) {
361
                                                        RasterProvider prov = loadProvider(multiFileFormat.getPathToFile(i), storeServices);
362
                                                        if(i == 0)
363
                                                                getParameters().setPixelSize(prov.getCellSize());
364
                                                        getParameters().addProvider(prov);
365
                                                }
366
                                        } catch (ProviderNotRegisteredException e) {
367
                                                throw new OpenException("A provider can't be loaded", e);
368
                                        } catch (InitializeException e) {
369
                                                throw new OpenException("A provider can't be initialized", e);
370
                                        }
371
                                }
372
                        } catch (IOException e1) {
373
                                throw new OpenException("File .mrf can't be read", e1);
374
                        } catch (ParsingException e1) {
375
                                throw new OpenException("File .mrf can't be parsed", e1);
376
                        }
377
                } 
378
        }
379
        
380
        public RasterProvider load() {
381
                return this;
382
        }
383
        
384
        /**
385
         * Gets the MosaicDataParameters
386
         * @return
387
         */
388
        public MosaicDataParameters getParameters() {
389
                try {
390
                        return (MosaicDataParameters)parameters;
391
                } catch (ClassCastException e) {
392
                        return null;
393
                }
394
        }
395
        
396
        public boolean isOpen() {
397
                return open;
398
        }
399

    
400
        public void close() {
401
                for (int i = 0; i < providerList.size(); i++) {
402
                        providerList.get(i).close();
403
                }
404
        }
405
        
406
        /**
407
         * @return Returns the dataType.
408
         */
409
        public int[] getDataType() {
410
                if(providerList.get(0).getDataType()[0] == Buffer.TYPE_BYTE) {
411
                        int[] dt = new int[getBandCount()];
412
                        for (int i = 0; i < providerList.get(0).getDataType().length; i++) {
413
                                dt[i] = providerList.get(0).getDataType()[i];
414
                        }
415
                        dt[getBandCount() - 1] = Buffer.TYPE_BYTE;
416
                        return dt;
417
                }
418
                return providerList.get(0).getDataType();
419
        }
420
        
421
        /**
422
         * Gets the number of bands
423
         * @return 
424
         */
425
        public int getBandCount() {
426
                if(!bandCountCalculated) {
427
                        bandCount = providerList.get(0).getBandCount();
428
                        for (int i = 1; i < providerList.size(); i++) {
429
                                if(providerList.get(i).getBandCount() > bandCount)
430
                                        bandCount = providerList.get(i).getBandCount();
431
                        }
432
                }
433
                return bandCount;
434
        }
435
        
436
        public String[] getURIByProvider() {
437
                providerList = getParameters().getProviders();
438
                String[] uris = new String[providerList.size()];
439
                for (int i = 0; i < uris.length; i++) {
440
                        uris[i] = providerList.get(i).getURI();
441
                }
442
                return uris;
443
        }
444
        
445
        public int[] getBandCountByProvider() {
446
                int[] n = new int[providerList.size()];
447
                for (int i = 0; i < providerList.size(); i++) {
448
                        n[i] = providerList.get(i).getBandCount();
449
                }
450
                return n;
451
        }
452
        
453
        public BandList getDefaultBandList() {
454
                BandList bandList = new BandListImpl();
455
                int[] nBandsByProvider = getBandCountByProvider();
456
                int nBands = 0;
457
                for (int i = 0; i < nBandsByProvider.length; i++) {
458
                        nBands = Math.max(nBandsByProvider[i], nBands);
459
                }
460
                
461
                for (int iBand = 0; iBand < nBands; iBand++) {
462
                        try {
463
                                bandList.addBand(new DatasetBandImpl(getURI(), iBand, getDataType()[0], nBands));
464
                        } catch (BandNotFoundInListException e1) {
465
                        }        
466
                }
467

    
468
                int[] drawableBands = new int[bandList.getBandCount()];
469
                for (int i = 0; i < bandList.getBandCount(); i++) {
470
                        drawableBands[i] = i;
471
                }
472
                
473
                bandList.setDrawableBands(drawableBands);
474
                return bandList;
475
        }
476
        
477
        public String getURIByBand(int band) {
478
                return getURI();
479
        }
480
        
481
        public double getPixelSizeX() {
482
                if(getParameters().hasParamsChanged())
483
                        calcMetadataFromParams();
484
                return pixelSize;
485
        }
486

    
487
        public double getPixelSizeY() {
488
                if(getParameters().hasParamsChanged())
489
                        calcMetadataFromParams();
490
                return pixelSize;
491
        }
492

    
493
        public NoData getNoDataValue() {
494
                if(getParameters().hasParamsChanged())
495
                        calcMetadataFromParams();
496
                return noData;
497
        }
498
        
499
        public Extent getExtent() {
500
                if(getParameters().hasParamsChanged())
501
                        calcMetadataFromParams();
502
                return extent;
503
        }
504
        
505
        public double getCellSize() {
506
                return pixelSize;
507
        }
508
        
509
        public Statistics getStatistics() {
510
                if(stats == null || getParameters().hasParamsChanged()) {
511
                        //First of all read the statistics in the rmf. If these have not been calculated then
512
                        //we'll read the statistics from simple files
513
                        stats = super.getStatistics();
514
                        try {
515
                                loadObjectFromRmf(SimpleProviderStatistics.class, stats);
516
                        } catch (RmfSerializerException e) {
517
                                // Si no se puede cargar del RMF, recalcularemos las estadisticas.
518
                        }
519
                        if(!stats.isCalculated()) {
520
                                calcMetadataFromParams();
521
                                providerList = getParameters().getProviders();
522
                                stats = SimpleProviderStatistics.union(this, providerList);
523
                        }
524
                }
525
                return stats;
526
        }
527

    
528
        public HistogramComputer getHistogramComputer() {
529
                if(histogram == null || getParameters().hasParamsChanged()) {
530
                        calcMetadataFromParams();
531
                        providerList = getParameters().getProviders();
532
                        try {
533
                                histogram = SimpleProviderHistogramComputer.union(this, providerList);
534
                        } catch (HistogramException e) {
535
                                return null;
536
                        } catch (InterruptedException e) {
537
                                return null;
538
                        }
539
                }
540
                return histogram;
541
        }
542

    
543
        public String getURIOfFirstProvider() {
544
                return providerList.get(0).getURIOfFirstProvider();
545
        }
546

    
547
        public long getFileSize() {
548
                if(getParameters().hasParamsChanged())
549
                        calcMetadataFromParams();
550
                long sizeMosaic = 0;
551
                for (int i = 0; i < providerList.size(); i++) {
552
                        long[] fs = providerList.get(i).getFileSizeByProvider();
553
                        for (int j = 0; j < fs.length; j++) {
554
                                sizeMosaic += fs[j];
555
                        }
556
                }
557
                return sizeMosaic;
558
        }
559

    
560
        public IProjection getProjection() {
561
                return proj;
562
        }
563

    
564
        public void setProjection(IProjection p) {
565
        }
566

    
567
        public String getInfoByPoint(double x, double y, ICancellable cancellable) {
568
                return null;
569
        }
570
        
571
        public int[] getTileSize(int level) {
572
                return null;
573
        }
574
        
575
        public int getSourceType() {
576
                return RasterDataStore.MOSAIC;
577
        }
578
        
579
        public String translateFileName(String fileName) {
580
                return fileName;
581
        }
582

    
583
        public void setView(Extent e) {
584
                viewRequest = new ExtentImpl(e);
585
        }
586

    
587
        public Extent getView() {
588
                return viewRequest;
589
        }
590

    
591
        public double getWidth() {
592
                if(getParameters().hasParamsChanged())
593
                        calcMetadataFromParams();
594
                return width;
595
        }
596

    
597
        public double getHeight() {
598
                if(getParameters().hasParamsChanged())
599
                        calcMetadataFromParams();
600
                return height;
601
        }
602

    
603
        public Object readBlock(int pos, int blockHeight, double scale)
604
                throws InvalidSetViewException, FileNotOpenException, RasterDriverException, ProcessInterruptedException {
605
                /*if(getParameters().hasParamsChanged())
606
                        calcMetadataFromParams();
607
                blockHeight = pos + blockHeight > getHeight() ? (int)(getHeight() - pos) : blockHeight;
608
                Buffer buf = RasterLocator.getManager().createBuffer(getDataType()[0], (int)getWidth(), blockHeight, getBandCount(), true);
609
                BandList bandList = new BandListImpl();
610
                bandList.clear();
611
                int[] drawableBands = new int[getBandCount()];
612
                for(int i = 0; i < getBandCount(); i++) {
613
                        try {
614
                                int dataType = getDataType()[i];
615
                                DatasetBand band = new DatasetBandImpl(getURIByBand(i), 
616
                                                                                                        getBandPositionByProvider(i), 
617
                                                                                                        dataType, 
618
                                                                                                        getBandCount());
619
                                bandList.addBand(band, i);
620
                                drawableBands[i] = i;
621
                        } catch(BandNotFoundInListException ex) {
622
                                //No a?adimos la banda
623
                        }
624
                }
625
                bandList.setDrawableBands(drawableBands);
626
                return getWindow(0, pos, bandList, buf);*/
627
                return null;
628
        }
629

    
630
        public Object getData(int x, int y, int band) throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
631
                if(getParameters().hasParamsChanged())
632
                        calcMetadataFromParams();
633
                return null;
634
        }
635
        
636
        /**
637
         * Creates a <code>BandList</code> for each provider of this <code>MultiFileProvider</code>.
638
         * When a request is made, the <code>BandList</code> is global for all files. A specific 
639
         * <code>BandList</code> has to be built for each provider. 
640
         * @param globalBandList
641
         * @param provider
642
         * @return
643
         */
644
        private BandList createBandListByProvider(BandList globalBandList, RasterProvider provider) {
645
                if(provider.isTiled()) { 
646
                        //Si los proveedores que hay por debajo son tileados estos crearan su propio buffer para escribir
647
                        //cada tile. Por ello no usara? el buffer que viene del store. Esto quiere decir que el BandList ha
648
                        //de ser distinto para que escriba bien en su buffer
649
                        
650
                        //TODO: De momento no se permiten MultiFiles con proveedores tileados. Esto es porque
651
                        //los tiles crean su propio buffer y no escriben en el buffer creado en el Store
652

    
653
                } else {
654
                        BandList bandListByFile = new BandListImpl();
655
                        for (int i = 0; i < provider.getBandCount(); i++) {
656
                                try {
657
                                        bandListByFile.addBand(new DatasetBandImpl(provider.getURI(), i, provider.getDataType()[0], provider.getBandCount()));
658
                                } catch (BandNotFoundInListException e1) {
659
                                }
660
                        }
661

    
662
                        boolean areThereBandsToDraw = false;
663
                        for (int i = 0; i < provider.getBandCount(); i++) {
664
                                int[] bandsToDrawByProviderBand = globalBandList.getBufferBandToDraw(getURI(), i);
665
                                if(bandsToDrawByProviderBand != null) {
666
                                        areThereBandsToDraw = true;
667
                                        for (int j = 0; j < bandsToDrawByProviderBand.length; j++) {
668
                                                bandListByFile.getBand(i).addPositionToDrawInBuffer(bandsToDrawByProviderBand[j]);                                
669
                                        }
670
                                }
671
                        }
672

    
673
                        if(areThereBandsToDraw)
674
                                return bandListByFile;
675
                }
676
                return null;
677
        }
678
        
679
        private double adjustCoordinate(double c) {
680
                return (c > 0.95 || c < 0.05) ? Math.round(c) : c;
681
        }
682
        
683
        private Buffer getBuffersFusion(SpiRasterQuery query, Buffer rasterBuf, int alphaBandNumber) throws RasterDriverException, ProcessInterruptedException {
684
                
685
                List<Buffer> bufferList = new ArrayList<Buffer>();
686
                
687
                for (int i = 0; i < providerList.size(); i++) {
688
                        RasterProvider provider = providerList.get(i);
689
                        Extent extIntersection = getView().intersection(provider.getExtent());
690
                        
691
                        if(extIntersection == null)
692
                                continue;
693
                        
694
                        double relWidth = getView().width() / rasterBuf.getWidth();
695
                        double relHeight = getView().height() / rasterBuf.getHeight();
696
                        int w = (int)Math.ceil(adjustCoordinate(extIntersection.width() / relWidth));
697
                        int h = (int)Math.ceil(adjustCoordinate(extIntersection.height() / relHeight));
698

    
699
                        RasterQuery q = RasterLocator.getManager().createQuery();
700
                        q.setAreaOfInterest(extIntersection, w, h);
701
                        q.setDrawableBands(query.getBandList().getDrawableBands());
702
                        DefaultRasterStore store = new DefaultRasterStore();
703
                        store.setProvider(provider);
704
                        Buffer buf = null;
705
                        try {
706
                                buf = store.query(q);
707
                                buf.setDataExtent(extIntersection.toRectangle2D());
708
                        } catch (QueryException e) {
709
                                throw new RasterDriverException("Error reading data", e);
710
                        }
711
                        bufferList.add(buf);
712
                }
713
                
714
                if(bufferList.size() == 0)
715
                        return rasterBuf;
716
                
717
                PixelSquareStructure pxSquare = BufferListFusion.buildPixelSquareStructure(
718
                                rasterBuf, 
719
                                getView(), 
720
                                getCellSize(), 
721
                                getBandCount());
722
                BufferListFusion bufferFusion = new BufferListFusion(bufferList, pxSquare, BufferListFusion.FIRST);
723
                bufferFusion.setAlphaBand(alphaBandNumber);
724
                rasterBuf = bufferFusion.getWindow();
725
                bufferFusion.dispose();
726
                return rasterBuf;
727
        }
728
        
729
        public void loadBuffer(SpiRasterQuery q) throws ProcessInterruptedException, RasterDriverException {
730
                if(getParameters().hasParamsChanged())
731
                        calcMetadataFromParams();
732
                setView(q.getAdjustedRequestBoundingBox());
733

    
734
                int alphaBandNumber = q.getAlphaBandNumber(); 
735
                if(q.getAlphaBandNumber() != -1) {
736
                        alphaBandNumber ++;
737
                }
738
                
739
                //La query no ha creado el buffer porque no sabe el n?mero de bandas. Lo calculamos aqu?
740
                BufferParam bufParam = RasterLocator.getManager().getBufferFactory().createBufferParams(
741
                                q.getBufWidth(), 
742
                                q.getBufHeight(), 
743
                                q.getAlphaBandNumber() == -1 ? getBandCount() : getBandCount() + 1, 
744
                                getDataType()[0], 
745
                                true);
746
                
747
                try {
748
                        Buffer buf = RasterLocator.getManager().getBufferFactory().createBuffer(bufParam);
749
                        buf.setDataExtent(q.getAdjustedRequestBoundingBox().toRectangle2D());
750
                        getBuffersFusion(q, buf, alphaBandNumber) ;
751
                        q.setBufferResult(buf);
752
                } catch (LocatorException e) {
753
                        new RasterDriverException("Error locating the manager", e);
754
                } catch (BufferCreationException e) {
755
                        new RasterDriverException("Error creating the buffer", e);
756
                }
757
        }
758
        
759

    
760
        public int getBlockSize() {
761
                return 0;
762
        }
763
        
764
        public boolean isTiled() {
765
                return false;
766
        }
767

    
768
        public int getOverviewCount(int band) throws BandAccessException, RasterDriverException {
769
                return 0;
770
        }
771

    
772
        public int getOverviewWidth(int band, int overview) throws BandAccessException, RasterDriverException {
773
                return 0;
774
        }
775

    
776
        public int getOverviewHeight(int band, int overview) throws BandAccessException, RasterDriverException {
777
                return 0;
778
        }
779

    
780
        public boolean isOverviewsSupported() {
781
                return false;
782
        }
783

    
784
        public boolean isReproyectable() {
785
                return false;
786
        }
787

    
788
        public String getName() {
789
                return NAME;
790
        }
791
        
792
        public void setStatus(RasterProvider provider) {
793
                if(provider instanceof MosaicProvider) {
794
                }
795
        }
796
        
797
        public boolean isTimeSupported() {
798
                return true;
799
        }
800
        
801
        public boolean isMosaic() {
802
                return true;
803
        }
804
        
805
        /**
806
         * Gets the layer name using the time selection and visibility
807
         * @param t
808
         * @return
809
         */
810
        private String getLayerNameFromSelection(Time t) {
811
                String name = "";
812
                
813
                MessageDigest md = null;
814
                try {
815
                        md = java.security.MessageDigest.getInstance("MD5");
816
                } catch (NoSuchAlgorithmException e) {
817
                }
818

    
819
                //Without time selected
820
                if(t == null || selectedProviders.size() != providerList.size()) {
821
                        selectedProviders.clear();
822
                        for (int i = 0; i < providerList.size(); i++) {
823
                                RasterProvider prov = providerList.get(i);
824
                                selectedProviders.add(prov);
825
                                if(!((RasterDataParameters)prov.getDataParameters()).isVisible())
826
                                        name += prov.getURI().substring(prov.getURI().lastIndexOf(File.separator) + 1, prov.getURI().length());
827
                        }
828
                } else {
829
                        selectedProviders.clear();
830
                        for (int i = 0; i < providerList.size(); i++) {
831
                                try {
832
                                        TimeSeries tSeries = providerList.get(i).getTimeSerials();
833
                                        ArrayList<?> tList = tSeries.getTimeList();
834
                                        for (int j = 0; j < tList.size(); j++) {
835
                                                Object obj = tList.get(i);
836
                                                RelativeInstant instant = null;
837
                                                if(obj instanceof Date) {
838
                                                        Date s = (Date)obj;
839
                                                        instant = TimeSupportLocator.getManager().createRelativeInstant(s);
840
                                                }
841
                                                if(obj instanceof Double) {
842
                                                        long s = ((Double)obj).longValue();
843
                                                        instant = TimeSupportLocator.getManager().createRelativeInstant(s);
844
                                                }
845
                                                if( instant != null && 
846
                                                        t.intersects(instant) &&
847
                                                        !selectedProviders.contains(providerList.get(i))) {
848
                                                        RasterProvider prov = providerList.get(i);
849
                                                        selectedProviders.add(prov);
850
                                                        if(!((RasterDataParameters)prov.getDataParameters()).isVisible())
851
                                                                name += prov.getURI().substring(prov.getURI().lastIndexOf(File.separator) + 1, prov.getURI().length());
852
                                                }
853
                                        }
854
                                } catch (RmfSerializerException e) {
855
                                        logger.debug("Error reading rmf time serials", e);
856
                                }
857
                        }
858
                }
859
                
860
                if(md != null) {
861
                        md.update(name.getBytes());
862
                        return math.convertToHex(md.digest());
863
                } else {
864
                        return name;
865
                }
866
        }
867
        
868
        public TileServer getTileServer() {
869
                if(tileServer == null) {
870
                        DefaultRasterStore store = new DefaultRasterStore();
871
                        store.setProvider(this);
872
                        tileServer = new MosaicTileServer(store);
873
                }
874
                return tileServer;
875
        }
876
        
877
}