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 @ 2301

History | View | Annotate | Download (31.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.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.HashMap;
32
import java.util.List;
33

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

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

    
274
        public ColorInterpretation getColorInterpretation() {
275
                if(super.getColorInterpretation() == null) {
276
                        ColorInterpretation ci = null;
277
                        for (int i = 0; i < providerList.size(); i++) {
278
                                RasterProvider prv = providerList.get(i);
279
                                if(prv.getBandCount() == getBandCount() && prv.getColorInterpretation() != null) {
280
                                        ci = prv.getColorInterpretation().cloneColorInterpretation();
281
                                }
282
                        }
283

    
284
                        if(ci == null) {
285
                                if(getDataType()[0] == Buffer.TYPE_BYTE) {
286
                                        if(getBandCount() == 4)
287
                                                ci = DataStoreColorInterpretation.createARGBInterpretation();
288
                                        if(getBandCount() == 3)
289
                                                ci = DataStoreColorInterpretation.createRGBInterpretation();
290
                                        if(getBandCount() == 1)
291
                                                ci = DataStoreColorInterpretation.createPaletteInterpretation();
292
                                } else {
293
                                        if(getBandCount() == 1)
294
                                                ci = DataStoreColorInterpretation.createGrayInterpretation();
295
                                        else 
296
                                                ci = DataStoreColorInterpretation.createDefaultInterpretation();
297
                                }
298
                        }
299

    
300
                        setColorInterpretation(ci);
301
                }
302
                return super.getColorInterpretation();
303
        }
304
        
305
        /**
306
         * Loads the specific provider
307
         * @param file
308
         * @return
309
         * @throws NotSupportedExtensionException
310
         * @throws FileNotSupportedException 
311
         */
312
        @SuppressWarnings("unchecked")
313
        private RasterProvider loadProvider(String file, DataStoreProviderServices storeServices) throws ProviderNotRegisteredException, InitializeException {
314
                DataManagerProviderServices dataManager = (DataManagerProviderServices)DALLocator.getDataManager();
315
                DataStoreProvider prov = null;
316

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

    
343
                if(prov != null && prov instanceof RasterProvider) {
344
                        if(((RasterProvider)prov).isRotated())
345
                                throw new InitializeException("Rotation not supported tiling files", new Throwable());
346

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

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

    
476
                int[] drawableBands = new int[bandList.getBandCount()];
477
                for (int i = 0; i < bandList.getBandCount(); i++) {
478
                        drawableBands[i] = i;
479
                }
480
                
481
                bandList.setDrawableBands(drawableBands);
482
                return bandList;
483
        }
484
        
485
        public String getURIByBand(int band) {
486
                return getURI();
487
        }
488
        
489
        public double getPixelSizeX() {
490
                if(getParameters().hasParamsChanged())
491
                        calcMetadataFromParams();
492
                return pixelSize;
493
        }
494

    
495
        public double getPixelSizeY() {
496
                if(getParameters().hasParamsChanged())
497
                        calcMetadataFromParams();
498
                return pixelSize;
499
        }
500

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

    
536
        public HistogramComputer getHistogramComputer() {
537
                if(histogram == null || getParameters().hasParamsChanged()) {
538
                        calcMetadataFromParams();
539
                        providerList = getParameters().getProviders();
540
                        try {
541
                                histogram = SimpleProviderHistogramComputer.union(this, providerList);
542
                        } catch (HistogramException e) {
543
                                return null;
544
                        } catch (InterruptedException e) {
545
                                return null;
546
                        }
547
                }
548
                return histogram;
549
        }
550

    
551
        public String getURIOfFirstProvider() {
552
                return providerList.get(0).getURIOfFirstProvider();
553
        }
554

    
555
        public long getFileSize() {
556
                if(getParameters().hasParamsChanged())
557
                        calcMetadataFromParams();
558
                long sizeMosaic = 0;
559
                for (int i = 0; i < providerList.size(); i++) {
560
                        long[] fs = providerList.get(i).getFileSizeByProvider();
561
                        for (int j = 0; j < fs.length; j++) {
562
                                sizeMosaic += fs[j];
563
                        }
564
                }
565
                return sizeMosaic;
566
        }
567

    
568
        public IProjection getProjection() {
569
                return proj;
570
        }
571

    
572
        public void setProjection(IProjection p) {
573
        }
574

    
575
        public String getInfoByPoint(double x, double y, ICancellable cancellable) {
576
                return null;
577
        }
578
        
579
        public int[] getTileSize(int level) {
580
                return null;
581
        }
582
        
583
        public int getSourceType() {
584
                return RasterDataStore.MOSAIC;
585
        }
586
        
587
        public String translateFileName(String fileName) {
588
                return fileName;
589
        }
590

    
591
        public void setView(Extent e) {
592
                viewRequest = new ExtentImpl(e);
593
        }
594

    
595
        public Extent getView() {
596
                return viewRequest;
597
        }
598

    
599
        public double getWidth() {
600
                if(getParameters().hasParamsChanged())
601
                        calcMetadataFromParams();
602
                return width;
603
        }
604

    
605
        public double getHeight() {
606
                if(getParameters().hasParamsChanged())
607
                        calcMetadataFromParams();
608
                return height;
609
        }
610

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

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

    
662
                } else {
663
                        BandList bandListByFile = new BandListImpl();
664
                        for (int i = 0; i < provider.getBandCount(); i++) {
665
                                try {
666
                                        bandListByFile.addBand(new DatasetBandImpl(provider.getURI(), i, provider.getDataType()[0], provider.getBandCount()));
667
                                } catch (BandNotFoundInListException e1) {
668
                                }
669
                        }
670

    
671
                        boolean areThereBandsToDraw = false;
672
                        for (int i = 0; i < provider.getBandCount(); i++) {
673
                                int[] bandsToDrawByProviderBand = globalBandList.getBufferBandToDraw(getURI(), i);
674
                                if(bandsToDrawByProviderBand != null) {
675
                                        areThereBandsToDraw = true;
676
                                        for (int j = 0; j < bandsToDrawByProviderBand.length; j++) {
677
                                                bandListByFile.getBand(i).addPositionToDrawInBuffer(bandsToDrawByProviderBand[j]);                                
678
                                        }
679
                                }
680
                        }
681

    
682
                        if(areThereBandsToDraw)
683
                                return bandListByFile;
684
                }
685
                return null;
686
        }
687
        
688
        private double adjustCoordinate(double c) {
689
                return (c > 0.95 || c < 0.05) ? Math.round(c) : c;
690
        }
691
        
692
        private Buffer getBuffersFusion(BandList bandList, TaskStatus status, Buffer rasterBuf) throws RasterDriverException, ProcessInterruptedException {
693
                List<Buffer> bufferList = new ArrayList<Buffer>();
694
                
695
                for (int i = 0; i < providerList.size(); i++) {
696
                        RasterProvider provider = providerList.get(i);
697
                        Extent extIntersection = getView().intersection(provider.getExtent());
698
                        
699
                        if(extIntersection == null)
700
                                continue;
701
                        
702
                        double relWidth = getView().width() / rasterBuf.getWidth();
703
                        double relHeight = getView().height() / rasterBuf.getHeight();
704
                        int w = (int)Math.ceil(adjustCoordinate(extIntersection.width() / relWidth));
705
                        int h = (int)Math.ceil(adjustCoordinate(extIntersection.height() / relHeight));
706

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

    
741
        public int getBlockSize() {
742
                return 0;
743
        }
744
        
745
        public boolean isTiled() {
746
                return false;
747
        }
748

    
749
        public int getOverviewCount(int band) throws BandAccessException, RasterDriverException {
750
                return 0;
751
        }
752

    
753
        public int getOverviewWidth(int band, int overview) throws BandAccessException, RasterDriverException {
754
                return 0;
755
        }
756

    
757
        public int getOverviewHeight(int band, int overview) throws BandAccessException, RasterDriverException {
758
                return 0;
759
        }
760

    
761
        public boolean isOverviewsSupported() {
762
                return false;
763
        }
764

    
765
        public boolean isReproyectable() {
766
                return false;
767
        }
768

    
769
        public String getName() {
770
                return NAME;
771
        }
772
        
773
        public void setStatus(RasterProvider provider) {
774
                if(provider instanceof MosaicProvider) {
775
                }
776
        }
777
        
778
        public boolean isTimeSupported() {
779
                return true;
780
        }
781
        
782
        public boolean isMosaic() {
783
                return true;
784
        }
785
        
786
//        public void deleteLayerFromCache() {
787
//                String layerName = getLayerNameFromSelection(null);
788
//                TileCacheManager  manager = TileCacheLocator.getManager();
789
//                TileCache tileCache = manager.getTileCache(RasterLibrary.pathTileCache);
790
//                TiledLayer newLayer = tileCache.createLayer(getTileServer(layerName), TileCacheLibrary.DEFAULT_STRUCTURE);
791
//                tileCache.removeLayer(newLayer);
792
//        }
793
        
794
        /**
795
         * Gets the layer name using the time selection and visibility
796
         * @param t
797
         * @return
798
         */
799
        private String getLayerNameFromSelection(Time t) {
800
                String name = "";
801
                
802
                MessageDigest md = null;
803
                try {
804
                        md = java.security.MessageDigest.getInstance("MD5");
805
                } catch (NoSuchAlgorithmException e) {
806
                }
807

    
808
                //Without time selected
809
                if(t == null || selectedProviders.size() != providerList.size()) {
810
                        selectedProviders.clear();
811
                        for (int i = 0; i < providerList.size(); i++) {
812
                                RasterProvider prov = providerList.get(i);
813
                                selectedProviders.add(prov);
814
                                if(!((RasterDataParameters)prov.getDataParameters()).isVisible())
815
                                        name += prov.getURI().substring(prov.getURI().lastIndexOf(File.separator) + 1, prov.getURI().length());
816
                        }
817
                } else {
818
                        selectedProviders.clear();
819
                        for (int i = 0; i < providerList.size(); i++) {
820
                                try {
821
                                        TimeSeries tSeries = providerList.get(i).getTimeSerials();
822
                                        ArrayList<?> tList = tSeries.getTimeList();
823
                                        for (int j = 0; j < tList.size(); j++) {
824
                                                Object obj = tList.get(i);
825
                                                RelativeInstant instant = null;
826
                                                if(obj instanceof Date) {
827
                                                        Date s = (Date)obj;
828
                                                        instant = TimeSupportLocator.getManager().createRelativeInstant(s);
829
                                                }
830
                                                if(obj instanceof Double) {
831
                                                        long s = ((Double)obj).longValue();
832
                                                        instant = TimeSupportLocator.getManager().createRelativeInstant(s);
833
                                                }
834
                                                if( instant != null && 
835
                                                        t.intersects(instant) &&
836
                                                        !selectedProviders.contains(providerList.get(i))) {
837
                                                        RasterProvider prov = providerList.get(i);
838
                                                        selectedProviders.add(prov);
839
                                                        if(!((RasterDataParameters)prov.getDataParameters()).isVisible())
840
                                                                name += prov.getURI().substring(prov.getURI().lastIndexOf(File.separator) + 1, prov.getURI().length());
841
                                                }
842
                                        }
843
                                } catch (RmfSerializerException e) {
844
                                        logger.debug("Error reading rmf time serials", e);
845
                                }
846
                        }
847
                }
848
                
849
                if(md != null) {
850
                        md.update(name.getBytes());
851
                        return math.convertToHex(md.digest());
852
                } else {
853
                        return name;
854
                }
855
        }
856
        
857
        /**
858
         * Creates a new tiled layer if this hasn't been created yet or the ID has changed. 
859
         * An ID could changed because the file type has changed when the user uses WMTS properties.
860
         */
861
//        private TileCache createTiledLayer(String layerName) {
862
//                TileCacheManager  manager = TileCacheLocator.getManager();
863
//                TileCache tileCache = manager.getTileCache(RasterLibrary.pathTileCache);
864
//                TiledLayer newLayer = tileCache.createLayer(getTileServer(layerName), TileCacheLibrary.DEFAULT_STRUCTURE);
865
//                if(tiledLayer == null || newLayer.getID().compareTo(tiledLayer.getID()) != 0)
866
//                        tiledLayer = newLayer;
867
//                return tileCache;
868
//        }
869
        
870
        /**
871
         * Gets the tile list in a selected extent
872
         * @param ex
873
         * @param bandList
874
         * @param bufWidth
875
         * @param bufHeight
876
         * @return
877
         * @throws TileBuildException 
878
         */
879
        /*private List<Tile> getTileList(Extent ex, BandList bandList, int bufWidth, int bufHeight, String layerName) throws TileBuildException {
880
                CacheStruct struct = getTileServer(layerName).getStruct();
881
                
882
                createTiledLayer(layerName); //Creates a new layer when the file type changes
883
                
884
                Extent adjustedExtent = util.intersection(getExtent(), ex);
885
                double newBufWidth = (adjustedExtent.width() * bufWidth) / ex.width();
886
                double pixelSizeRequest = adjustedExtent.width() / newBufWidth; 
887
                
888
                List<Tile> tileList = struct.getTileList(new Point2D.Double(adjustedExtent.getULX(), adjustedExtent.getULY()), 
889
                                new Point2D.Double(adjustedExtent.getLRX(), adjustedExtent.getLRY()), 
890
                                pixelSizeRequest);
891
                
892
                for (int i = 0; i < tileList.size(); i++) {
893
                        tileList.get(i).setDownloaderParams("BandList", bandList.clone());
894
                }
895
                return tileList;
896
        }*/
897
        
898
        public TileServer getTileServer() {
899
                if(tileServer == null) {
900
                        DefaultRasterStore store = new DefaultRasterStore();
901
                        store.setProvider(this);
902
                        tileServer = new FileTileServer(store);
903
                }
904
                return tileServer;
905
        }
906
        
907
        /**
908
         * Gets the tile server from the Hashmap
909
         * @param layerName
910
         * @return
911
         */
912
        /*public TileServer getTileServer(String layerName) {
913
                MosaicTileServer tileServer = tileServerMap.get(layerName);
914
                if(tileServer == null) {
915
                        DefaultRasterStore store = new DefaultRasterStore();
916
                        store.setProvider(this);
917
                        tileServer = new MosaicTileServer(store, 
918
                                        providerList,
919
                                        layerName,
920
                                        getParameters().getOverlapMethod(),
921
                                        getParameters().getColorCorrectionMethod(),
922
                                        getNoDataValue());
923
                        tileServerMap.put(layerName, tileServer);
924
                }
925
                return tileServer;
926
        }*/
927
}