Statistics
| Revision:

gvsig-raster / org.gvsig.raster.tilecache / trunk / org.gvsig.raster.tilecache / org.gvsig.raster.tilecache.io / src / main / java / org / gvsig / raster / tilecache / io / TileProvider.java @ 1859

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

    
24
import java.awt.Image;
25
import java.awt.geom.AffineTransform;
26
import java.awt.geom.NoninvertibleTransformException;
27
import java.awt.geom.Point2D;
28
import java.io.File;
29
import java.io.FileNotFoundException;
30
import java.io.IOException;
31
import java.lang.reflect.Constructor;
32
import java.lang.reflect.InvocationTargetException;
33
import java.util.ArrayList;
34
import java.util.List;
35

    
36
import org.gvsig.compat.net.ICancellable;
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.RasterLibrary;
41
import org.gvsig.fmap.dal.coverage.RasterLocator;
42
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
43
import org.gvsig.fmap.dal.coverage.datastruct.BandList;
44
import org.gvsig.fmap.dal.coverage.datastruct.DatasetBand;
45
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
46
import org.gvsig.fmap.dal.coverage.exception.BandAccessException;
47
import org.gvsig.fmap.dal.coverage.exception.BandNotFoundInListException;
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.InfoByPointException;
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.ProcessInterruptedException;
54
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
55
import org.gvsig.fmap.dal.coverage.exception.RmfSerializerException;
56
import org.gvsig.fmap.dal.coverage.store.parameter.MultiDimensionalStoreParameters;
57
import org.gvsig.fmap.dal.coverage.store.parameter.RasterDataParameters;
58
import org.gvsig.fmap.dal.coverage.store.parameter.RemoteStoreParameters;
59
import org.gvsig.fmap.dal.coverage.store.parameter.TileDataParameters;
60
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
61
import org.gvsig.fmap.dal.coverage.store.props.ColorTable;
62
import org.gvsig.fmap.dal.coverage.store.props.Transparency;
63
import org.gvsig.fmap.dal.coverage.util.MathUtils;
64
import org.gvsig.fmap.dal.coverage.util.RasterUtils;
65
import org.gvsig.fmap.dal.exception.InitializeException;
66
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
67
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
68
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemServerExplorer;
69
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemServerExplorerParameters;
70
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemStoreParameters;
71
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
72
import org.gvsig.fmap.dal.spi.DataStoreProvider;
73
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
74
import org.gvsig.metadata.MetadataLocator;
75
import org.gvsig.raster.cache.tile.Tile;
76
import org.gvsig.raster.cache.tile.TileCache;
77
import org.gvsig.raster.cache.tile.TileCacheLibrary;
78
import org.gvsig.raster.cache.tile.TileCacheLocator;
79
import org.gvsig.raster.cache.tile.TileCacheManager;
80
import org.gvsig.raster.cache.tile.exception.TileBuildException;
81
import org.gvsig.raster.cache.tile.exception.TileGettingException;
82
import org.gvsig.raster.cache.tile.layer.TiledLayer;
83
import org.gvsig.raster.cache.tile.provider.CacheStruct;
84
import org.gvsig.raster.cache.tile.provider.TileListener;
85
import org.gvsig.raster.cache.tile.provider.TileServer;
86
import org.gvsig.raster.impl.buffer.DefaultRasterQuery;
87
import org.gvsig.raster.impl.datastruct.BandListImpl;
88
import org.gvsig.raster.impl.datastruct.DatasetBandImpl;
89
import org.gvsig.raster.impl.datastruct.ExtentImpl;
90
import org.gvsig.raster.impl.provider.DefaultRasterProvider;
91
import org.gvsig.raster.impl.provider.MemoryMatrixBuffer;
92
import org.gvsig.raster.impl.provider.RasterProvider;
93
import org.gvsig.raster.impl.provider.RemoteRasterProvider;
94
import org.gvsig.raster.impl.provider.TiledRasterProvider;
95
import org.gvsig.raster.impl.store.DefaultStoreFactory;
96
import org.gvsig.raster.impl.store.properties.RemoteDataStoreStatistics;
97
import org.gvsig.tools.ToolsLocator;
98
import org.gvsig.tools.locator.LocatorException;
99
import org.gvsig.tools.task.TaskStatus;
100
import org.slf4j.Logger;
101
import org.slf4j.LoggerFactory;
102

    
103
/**
104
 * Provider for WMTS service
105
 *
106
 * @author Nacho Brodin (nachobrodin@gmail.com)
107
 */
108
public class TileProvider extends DefaultRasterProvider implements TiledRasterProvider {
109
        public static String                NAME                     = "Tile Store";
110
        public static String                DESCRIPTION              = "Raster Tiled Source";
111
        public static final String          METADATA_DEFINITION_NAME = "TileStore";
112
        private static final Logger         logger                   = LoggerFactory.getLogger(TileProvider.class);
113
        private RasterProvider              provider                 = null;
114
        private boolean                     open                     = false;
115
        private Extent                      viewRequest              = null;
116
        private TiledLayer                  tiledLayer               = null;
117
        private RasterUtils                 util                     = RasterLocator.getManager().getRasterUtils();
118
        private MathUtils                   math                     = RasterLocator.getManager().getMathUtils();
119
        private TileServer                  secondLevelTileServer    = null;
120
         
121
        public static void register() {                
122
                DataManagerProviderServices dataman = (DataManagerProviderServices) DALLocator.getDataManager();
123
                if (dataman != null && !dataman.getStoreProviders().contains(NAME)) {
124
                        dataman.registerStoreProvider(NAME,
125
                                        TileProvider.class, TileDataParametersImpl.class);
126
                }
127

    
128
                /*if(DALFileLocator.getFilesystemServerExplorerManager() != null)
129
                        DALFileLocator.getFilesystemServerExplorerManager().registerProvider(
130
                                        NAME, DESCRIPTION,
131
                                        TileServerExplorer.class);*/
132
                
133
                if (!dataman.getExplorerProviders().contains(TileServerExplorer.NAME)) {
134
                        dataman.registerExplorerProvider(TileServerExplorer.NAME, TileServerExplorer.class, TileServerExplorerParameters.class);
135
                }
136
                dataman.registerStoreFactory(NAME, DefaultStoreFactory.class);
137
        }
138
        
139
        /**
140
         * Loads the specific provider to download data
141
         * @param file
142
         * @return
143
         * @throws NotSupportedExtensionException
144
         * @throws FileNotSupportedException 
145
         */
146
        private RasterProvider loadProvider(TileDataParametersImpl params, DataStoreProviderServices storeServices) throws ProviderNotRegisteredException, InitializeException {
147
                Object obj = params.getDataParameters();
148
                DataManagerProviderServices dataManager = (DataManagerProviderServices)DALLocator.getDataManager();
149
                DataStoreProvider prov = null;
150
                
151
                if(obj != null && obj instanceof DataStoreParameters) //Remote 
152
                        prov = dataManager.createProvider(storeServices, (DataStoreParameters)obj);
153
                else { //File
154
                        if(params.getFile() != null) {
155
                                //We have to locate a provider's name which manages the selected file
156
                                //A FilesystemServerExplorer will give a getProviderNames service
157
                                FilesystemServerExplorerParameters paramsExplorer = (FilesystemServerExplorerParameters)dataManager.createServerExplorerParameters(FilesystemServerExplorer.NAME);
158
                                FilesystemServerExplorer serverExplorer = null;
159
                                try {
160
                                        paramsExplorer.setRoot(File.separator);
161
                                        serverExplorer = (FilesystemServerExplorer)dataManager.openServerExplorer(FilesystemServerExplorer.NAME, paramsExplorer);
162
                                } catch (ValidateDataParametersException e) {
163
                                        throw new InitializeException(e);
164
                                }
165
                                
166
                                //Gets the list of provider's name to manage the file
167
                                ArrayList<String> provName = serverExplorer.getProviderNameList(params.getFile());
168
                                if(provName.size() > 0) {
169
                                        for (int i = 0; i < provName.size(); i++) {
170
                                                //Gets the first provider what is not a TileProvider
171
                                                if(provName.get(i).compareTo(NAME) != 0) {
172
                                                        DataStoreParameters newparams = dataManager.createStoreParameters(provName.get(i));
173
                                                        ((FilesystemStoreParameters)newparams).setFile(params.getFile()); 
174
                                                        prov = dataManager.createProvider(storeServices, newparams);
175
                                                }
176
                                        }
177
                                }
178
                        }
179
                }
180
                
181
                if(prov != null && prov instanceof RasterProvider) {
182
                        if(((RasterProvider)prov).isRotated())
183
                                throw new InitializeException("Rotation not supported tiling files", new Throwable());
184

    
185
                        return (RasterProvider)prov;
186
                }
187
                
188
                return null;
189
        }
190
        
191
        /**
192
         * Gets the internal provider used to feed the TileProvider
193
         * @return
194
         */
195
        public RasterProvider getInternalProvider() {
196
                return provider;
197
        }
198
        
199
        public Image getImageLegend() {
200
                return provider.getImageLegend();
201
        }
202
        
203
        public String getFileSuffix() {
204
                try {
205
                        return provider instanceof RemoteRasterProvider ? provider.getFileSuffix() : "tif";
206
                } catch(Throwable e) {
207
                        //if wmts doesn't exists in the classpath
208
                        return "tif";
209
                }
210
        }
211
        
212
        public String getRMFFile() {
213
                TileCacheManager  manager = TileCacheLocator.getManager();
214
                TileCache tileCache = manager.getTileCache(RasterLibrary.pathTileCache);
215
                
216
                String path = tiledLayer.getBaseLayerDirectory().substring(0, tiledLayer.getBaseLayerDirectory().lastIndexOf(File.separator) + 1) + 
217
                                          tileCache.getConfigurationDirectory() + File.separator + 
218
                                          tiledLayer.getID() + ".rmf";
219
                
220
                try {
221
                        if(!new File(path).exists() && 
222
                                provider != null && 
223
                                provider.getRMFFile() != null &&
224
                                new File(provider.getRMFFile()).exists()) 
225
                                RasterLocator.getManager().getFileUtils().copyFile(provider.getRMFFile(), path);
226
                        
227
                        if(provider != null && provider.getColorTable() != null) {        
228
                                ColorTable colorTable = provider.getColorTable();
229
                                RasterLocator.getManager().getProviderServices().saveObjectToRmfFile(path, ColorTable.class, colorTable);
230
                        }
231
                } catch (LocatorException e) {
232
                        logger.info("No se ha podido copiar el fichero RMF a la capa tileada", e);
233
                } catch (FileNotFoundException e) {
234
                        logger.info("No se ha podido copiar el fichero RMF a la capa tileada", e);
235
                } catch (IOException e) {
236
                        logger.info("No se ha podido copiar el fichero RMF a la capa tileada", e);
237
                } catch (RmfSerializerException e) {
238
                        logger.info("No se ha podido copiar la tabla de color a la capa tileada", e);
239
                }
240
                return path;
241
        }
242
        
243
        public TileProvider() throws NotSupportedExtensionException {
244
                super();
245
        }
246
        
247
        public void registerTileProviderFormats(Class<RasterProvider> c) {
248
                
249
        }
250
        
251
        /**
252
         * Assigns the provider associated to this tile server
253
         * @param prov
254
         * @throws NotSupportedExtensionException 
255
         */
256
        public void setProvider(RasterProvider prov) throws InitializeException  {
257
                this.provider = prov;
258
                init(getDataStoreParameters(), getStoreServices());
259
        }
260
        
261
        public TileProvider(TileDataParametersImpl params,
262
                        DataStoreProviderServices storeServices) throws InitializeException {
263
                super(params, storeServices, ToolsLocator.getDynObjectManager()
264
                                .createDynObject(
265
                                                MetadataLocator.getMetadataManager().getDefinition(
266
                                                                DataStore.METADATA_DEFINITION_NAME)));
267
                if(!params.isSecondLevelCache()) {
268
                        try {
269
                                provider = loadProvider(params, storeServices);
270
                        } catch (ProviderNotRegisteredException e) {
271
                                throw new InitializeException("Provider not registered", e);
272
                        }
273
                        init(params, storeServices);
274
                        if(provider.getFileSizeByProvider() != null && provider.getFileSizeByProvider().length > 0)
275
                                fileSize = provider.getFileSizeByProvider()[0];
276
                }
277
        }
278
        
279
        /**
280
         * Creates the second level cache if the client has set a <code>TileServer</code> and the
281
         * <code>CacheStruct</code> is different that the old one. 
282
         * <UL>
283
         * <LI>First level cache without TileServer from the client: do nothing</LI>
284
         * <LI>First level cache with TileServer from the client and the structure is 
285
         * different to the old one: Builds a second level TileProvider</LI>
286
         * <LI>First level cache with TileServer from the client and the structure is 
287
         * equal to the old one: do nothing</LI>
288
         * <LI>Second level cache: sets the TileServer</LI>
289
         * </UL>
290
         * @param params
291
         * @param storeServices
292
         * @throws NotSupportedExtensionException
293
         */
294
        /*private void createsSecondLevelCache(TileDataParametersImpl params) throws NotSupportedExtensionException {
295
                //Se obtiene el TileServer que haya pasado el cliente en los par?metros si ha pasado alguno.
296
                TileServer tileServer = params.getTileServer();
297
                //Se obtiene el CacheStruct y se compara con el del provider
298
                CacheStruct cacheStruct = null;
299
                if(tileServer != null)
300
                        cacheStruct = tileServer.getStruct();
301
                
302
                if(params.isSecondLevelCache()) { //Cache de segundo nivel
303
                        this.secondLevelTileServer = tileServer;
304
                } else if(cacheStruct != null && !provider.getTileServer().getStruct().compare(cacheStruct)) { //Cache de primer nivel
305
                        //Si son distintos habr? que crear una cach? de segundo nivel por lo que creamos un nuevo TileProvider
306
                        //que tenga como par?metro el provider viejo
307
                        TileDataParametersImpl par = new TileDataParametersImpl();
308
                        par.setDataParameters(provider.getDataParameters());
309
                        par.setTileServer(tileServer);
310
                        par.setSecondLevelCache(true);
311
                        TileProvider newProvider = new TileProvider(par, null);
312
                        newProvider.setProvider(this.provider);
313
                        //Al TileProvider actual se le asigna como provider el TileProvider creado
314
                        this.provider = newProvider;
315
                }
316
        }*/
317
        
318
        /**
319
         * Crea las referencias al fichero y carga
320
         * las estructuras con la informaci?n y los metadatos.
321
         * @param proj Proyecci?n
322
         * @param param Parametros de carga
323
         * @throws NotSupportedExtensionException
324
         */
325
        public void init (DataStoreParameters params,
326
                        DataStoreProviderServices storeServices) throws InitializeException  {
327
                setParam(storeServices, params);
328
                open = true;
329
                setDataType(provider.getDataType());
330
                bandCount = provider.getBandCount();
331
                //if(getColorInterpretation() == null)
332
                        setColorInterpretation(provider.getColorInterpretation());
333
                /*else
334
                        getColorInterpretation().addColorInterpretation(provider.getColorInterpretation());*/
335
                setColorTable(provider.getColorTable());
336
                noData = provider.getNoDataValue();
337
                setFName(provider.getURIOfFirstProvider());
338
                proj = provider.getProjection();
339
                ownTransformation = provider.getAffineTransform();
340
                externalTransformation = (AffineTransform)ownTransformation.clone();
341
                
342
                createTiledLayer();
343
                
344
                //Force to deletes the layer if the flag is to true
345
                if(tiledLayer != null) {
346
                        if(param instanceof TileDataParameters) {
347
                                if(((TileDataParameters)param).isDeletingCache()) {
348
                                        TileCacheManager  manager = TileCacheLocator.getManager();
349
                                        TileCache tileCache = manager.getTileCache(RasterLibrary.pathTileCache);
350
                                        tileCache.removeLayer(tiledLayer);
351
                                        ((TileDataParameters)param).deleteCache(false);
352
                                }
353
                        }
354
                }
355
                
356
                if(provider instanceof RemoteRasterProvider)
357
                        stats = new RemoteDataStoreStatistics(provider);
358
        }
359
        
360
        /**
361
         * Creates a new tiled layer if this hasn't been created yet or the ID has changed. 
362
         * An ID could changed because the file type has changed when the user uses WMTS properties.
363
         */
364
        private void createTiledLayer() {
365
                TileCacheManager  manager = TileCacheLocator.getManager();
366
                TileCache tileCache = manager.getTileCache(RasterLibrary.pathTileCache);
367
                TiledLayer newLayer = tileCache.createLayer(provider.getTileServer(), TileCacheLibrary.DEFAULT_STRUCTURE);
368
                if(tiledLayer == null || newLayer.getID().compareTo(tiledLayer.getID()) != 0)
369
                        tiledLayer = newLayer;
370
        }
371
        
372
        public int getZoomLevels() {
373
                if(provider.getTileServer() != null)
374
                        return provider.getTileServer().getStruct().getNumberOfLevels();
375
                return 0;
376
        }
377
        
378
        public int getNearestLevel(double pixelSize) {
379
                double[] pixelSizes = getPixelSizeByLevel();
380
                for (int i = 0; i < pixelSizes.length - 1; i++) {
381
                        if(pixelSize <= pixelSizes[i] && pixelSize > pixelSizes[i + 1]) {
382
                                return i;
383
                        }
384
                }
385
                if(pixelSize < pixelSizes[getZoomLevels() - 1])
386
                        return getZoomLevels() - 1;
387
                return 0;
388
        }
389
        
390
        /**
391
         * Returns a list of pixel sizes by level
392
         * @return
393
         */
394
        public double[] getPixelSizeByLevel() {
395
                double[] list = new double[getZoomLevels()];
396
                CacheStruct struct = provider.getTileServer().getStruct();
397
                for (int i = 0; i < struct.getNumberOfLevels(); i++) {
398
                        list[i] = math.adjustDouble(struct.getPixelSizeByLevel(i));
399
                }
400
                return list;
401
        }
402
        
403
        public Extent getCoordsInTheNearestLevel(Extent extent, int w, int h) {
404
                double[] pixelSizes = getPixelSizeByLevel();
405
                double currentPixelSize = extent.width() / (double)w;
406
                
407
                int level = 0;
408
                for (int i = 0; i < (pixelSizes.length - 1); i++) {
409
                        if(currentPixelSize < pixelSizes[i] && currentPixelSize >= pixelSizes[i + 1]) {
410
                                level = i + 1;
411
                                break;
412
                        }
413
                }
414
                
415
                return getZoomLevelCoordinates(level, extent, w, h);
416
        }
417
        
418
        public Extent getCoordsInLevel(Point2D viewCenter, int level, int w, int h) {
419
                level = adjustLevel(level);
420
                double pixelSize = provider.getTileServer().getStruct().getPixelSizeByLevel(level);
421
                
422
                double ulx = viewCenter.getX() - ((w / 2) * pixelSize);
423
                double uly = viewCenter.getY() - ((h / 2) * pixelSize);
424
                double lrx = ulx + (w * pixelSize);
425
                double lry = uly + (h * pixelSize);
426
                return new ExtentImpl(ulx, uly, lrx, lry);
427
        }
428
        
429
        /**
430
         * Adjust de level to the range
431
         * @param level
432
         * @return
433
         */
434
        private int adjustLevel(int level) {
435
                if(level < 0)
436
                        level = 0;
437
                if(level > getZoomLevels())
438
                        level = getZoomLevels();
439
                return level;
440
        }
441
        
442
        public AffineTransform getAffineTransform() {
443
                return provider.getAffineTransform();
444
        }
445
        
446
        /**
447
         * Obtiene el objeto que contiene el estado de la transparencia
448
         */
449
        public Transparency getTransparency() {
450
                return provider.getTransparency();
451
        }
452
        
453
        /**
454
         * Gets the bounding box in world coordinates. If the layer has grid subsets (TileMatrixLimits) then
455
         * this will have a only extent but if the layer doesn't have grid subsets then this will have a different
456
         * extent in each level resolution. In this case we need to know the extent for each level.
457
         * @return Extent
458
         */
459
        public Extent getExtent() {
460
                return provider.getExtent();
461
        }
462

    
463
        public RasterProvider load() {
464
                return this;
465
        }
466
        
467
        public boolean isOpen() {
468
                return open;
469
        }
470

    
471
        public boolean isTiled() {
472
                return true;
473
        }
474
        
475
        public void close() {
476
                open = false;
477
                if(provider != null)
478
                        provider.close();
479
        }
480
        
481
        public String translateFileName(String fileName) {
482
                return fileName;
483
        }
484

    
485
        public void setView(Extent e) {
486
                viewRequest = e;
487
        }
488

    
489
        public Extent getView() {
490
                return viewRequest;
491
        }
492

    
493
        public double getWidth() {
494
                return provider.getWidth();
495
        }
496

    
497
        public double getHeight() {
498
                return provider.getHeight();
499
        }
500

    
501
        public Object readCompleteLine(int line, int band)
502
                throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
503
                return null;
504
        }
505
        
506
        public File getFileLayer() throws RasterDriverException {
507
                return null;
508
        }
509

    
510
        /**
511
         * Reads a complete block of data and returns an tridimensional array of the right type. This function is useful
512
         * to read a file very fast without setting a view. 
513
         * 
514
         * @param pos Posici?n donde se empieza  a leer
515
         * @param blockHeight Altura m?xima del bloque leido
516
         * @return Object que es un array tridimendional del tipo de datos del raster. (Bandas X Filas X Columnas)
517
         * @throws InvalidSetViewException
518
         * @throws FileNotOpenException
519
         * @throws RasterDriverException
520
         */
521
        public Object readBlock(int pos, int blockHeight, double scale) 
522
        throws InvalidSetViewException, FileNotOpenException, RasterDriverException, ProcessInterruptedException {
523
                return provider.readBlock(pos, blockHeight, scale);
524
        }
525

    
526
        public Object getData(int x, int y, int band)
527
                throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
528
                return provider.getData(x, y, band);
529
        }
530
        
531
        /**
532
         * Assigns the list of bands RGB and read a window of data
533
         * @param rasterBuf
534
         * @param bandList
535
         * @param lastFile
536
         * @param ulx
537
         * @param uly
538
         * @param lrx
539
         * @param lry
540
         * @return
541
         * @throws RasterDriverException
542
         * @throws ProcessInterruptedException
543
         */
544
        public Buffer getBuffer(Buffer rasterBuf, BandList bandList, File lastFile, 
545
                        double ulx, double uly, double lrx, double lry) throws RasterDriverException, ProcessInterruptedException {
546
                return null;
547
        }
548
        
549
        /**
550
         * Calculates the extent of a zoom level using other extent as a reference. The new extent is 
551
         * calculated with the same coordinate at the center. 
552
         * @param level
553
         * @param extent
554
         * @param w
555
         * @param h
556
         * @return
557
         */
558
        public Extent getZoomLevelCoordinates(int level, Extent extent, int w, int h) {
559
                double centerX = extent.getCenterX();
560
                double centerY = extent.getCenterY();
561
                return getCoordsInLevel(new Point2D.Double(centerX, centerY), level, w, h);
562
        }
563
        
564
        /**
565
         * Gets the tile list in a selected extent
566
         * @param ex
567
         * @param bandList
568
         * @param bufWidth
569
         * @param bufHeight
570
         * @return
571
         * @throws TileBuildException 
572
         */
573
        private List<Tile> getTileList(Extent ex, BandList bandList, int bufWidth, int bufHeight) throws TileBuildException {
574
                TileServer tileServer = provider.getTileServer();
575
                CacheStruct struct = tileServer.getStruct();
576
                tileServer.setFileSuffix(getFileSuffix());
577
                
578
                createTiledLayer(); //Creates a new layer when the file type changes
579
                
580
                Extent adjustedExtent = util.intersection(provider.getExtent(), ex);
581
                double newBufWidth = (adjustedExtent.width() * bufWidth) / ex.width();
582
                double pixelSizeRequest = adjustedExtent.width() / newBufWidth; 
583
                
584
                List<Tile> tileList = struct.getTileList(new Point2D.Double(adjustedExtent.getULX(), adjustedExtent.getULY()), 
585
                                new Point2D.Double(adjustedExtent.getLRX(), adjustedExtent.getLRY()), 
586
                                pixelSizeRequest);
587
                
588
                for (int i = 0; i < tileList.size(); i++) {
589
                        loadTileTimeParameters(tileList.get(i));
590
                }
591
                
592
                for (int i = 0; i < tileList.size(); i++) {
593
                        tileList.get(i).setDownloaderParams("BandList", bandList.clone());
594
                }
595
                return tileList;
596
        }
597
        
598
        /**
599
         * Loads the multidimensional parameters in a tile 
600
         * @param tile
601
         */
602
        private void loadTileTimeParameters(Tile tile) {
603
                if(provider.getDataParameters() instanceof MultiDimensionalStoreParameters) {
604
                        MultiDimensionalStoreParameters par = (MultiDimensionalStoreParameters)provider.getDataParameters();
605
                        tile.setVariable(par.getStringVariable());
606
                        tile.setZ(par.getStringLevel());
607
                        tile.setTimeInstant(par.getStringTime());
608
                }
609
        }
610
        
611
        public boolean needEnhanced() {
612
                return provider.needEnhanced();
613
        }
614
        
615
        public Tile getTile(DefaultRasterQuery q) throws TileGettingException {
616
                //q.getResolutionLevel(), q.getTileCol(), q.getTileRow(), q.getBBox(), q.getCacheStruct()
617
                if(q.getCacheStruct() == null)
618
                        q.setCacheStruct(provider.getTileServer().getStruct());
619
                else
620
                        provider.getTileServer().setStruct(q.getCacheStruct());
621
                
622
                Tile tile = null;
623
                try {
624
                        tile = q.getCacheStruct().getTileStructure(
625
                                        q.getResolutionLevel(), q.getTileCol(), q.getTileRow(), 
626
                                        new Point2D.Double(q.getBBox().getULX(), q.getBBox().getULY()), 
627
                                        new Point2D.Double(q.getBBox().getLRX(), q.getBBox().getLRY()));
628
                } catch (TileBuildException e1) {
629
                        throw new TileGettingException(e1);
630
                }
631
                
632
                loadTileTimeParameters(tile);
633
                
634
                //Creamos un BandList con todas las bandas del fichero
635
                BandList bandList = new BandListImpl();
636
                for(int i = 0; i < provider.getBandCount(); i++) {
637
                        try {
638
                                DatasetBand band = new DatasetBandImpl(provider.getURIOfFirstProvider(), i, provider.getDataType()[i], provider.getBandCount());
639
                                bandList.addBand(band);
640
                        } catch(BandNotFoundInListException e) {
641
                                //No a?adimos la banda
642
                        }
643
                }
644
                bandList.setDrawableBands(new int[]{0, 1, 2});
645
                
646
                tile.setDownloaderParams("BandList", bandList);
647
                createTiledLayer();
648
                return tiledLayer.getTile(tile);
649
        }
650

    
651
        public void getWindow(Extent ex, int bufWidth, int bufHeight, 
652
                        BandList bandList, TileListener listener, TaskStatus taskStatus) throws ProcessInterruptedException, RasterDriverException {
653
                try {
654
                        List<Tile> tileList = getTileList(ex, bandList, bufWidth, bufHeight);
655
                        tiledLayer.getTiles(tileList, listener, taskStatus);
656
                } catch (TileGettingException e) {
657
                        throw new RasterDriverException("Error getting the tile list", e);
658
                } catch (TileBuildException e) {
659
                        throw new RasterDriverException("Error building the tile list", e);
660
                }
661
        }
662
        
663
        public Buffer getWindow(Extent extent, int bufWidth, int bufHeight, 
664
                        BandList bandList, Buffer rasterBuf, boolean adjustToExtent, TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
665
                //draw method
666
                List<Tile> tileList = null;
667
                try {
668
                        tileList = getTileList(extent, bandList, bufWidth, bufHeight);
669
                        for (int i = 0; i < tileList.size(); i++) {
670
                                tiledLayer.getTile(tileList.get(i));
671
                        }
672
                } catch (TileGettingException e) {
673
                        throw new RasterDriverException("Error getting the tile list", e);
674
                } catch (TileBuildException e) {
675
                        throw new RasterDriverException("Error building the tile list", e);
676
                }
677
                MemoryMatrixBuffer matrixBuffer = new MemoryMatrixBuffer(tileList);
678
                return matrixBuffer.getWindow(extent, rasterBuf);
679
        }
680

    
681
        public Buffer getWindow(Extent ex, BandList bandList, Buffer rasterBuf, TaskStatus status) 
682
                throws ProcessInterruptedException, RasterDriverException {
683
                //return ((DefaultRasterProvider)provider).getWindow(ex, bandList, rasterBuf);
684
                return null;
685
        }
686

    
687
        public Buffer getWindow(double ulx, double uly, double w, double h, 
688
                        BandList bandList, Buffer rasterBuf, boolean adjustToExtent, TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
689
                Extent extent = new ExtentImpl(ulx, uly, ulx + w, uly - h);
690
                List<Tile> tileList = null;
691
                try {
692
                        tileList = getTileList(extent, bandList, rasterBuf.getWidth(), rasterBuf.getHeight());
693
                        for (int i = 0; i < tileList.size(); i++) {
694
                                tiledLayer.getTile(tileList.get(i));
695
                        }
696
                } catch (TileGettingException e) {
697
                        throw new RasterDriverException("Error getting the tile list", e);
698
                } catch (TileBuildException e) {
699
                        throw new RasterDriverException("Error building the tile list", e);
700
                }
701
                MemoryMatrixBuffer matrixBuffer = new MemoryMatrixBuffer(tileList);
702
                return matrixBuffer.getWindow(extent, rasterBuf);
703
        }
704

    
705
        public Buffer getWindow(int x, int y, int w, int h, 
706
                        BandList bandList, Buffer rasterBuf, TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
707
                DefaultRasterQuery q = (DefaultRasterQuery)RasterLocator.getManager().createQuery();
708
                q.setAreaOfInterest(x, y, w, h);
709
                q.setBandList(bandList);
710
                q.setBuffer(rasterBuf);
711
                Buffer b = ((DefaultRasterProvider)provider).getDataSet(q);
712
                if(b != null)
713
                        return b;
714
                else {
715
                        //TODO
716
                }
717
                return null;
718
        }
719

    
720
        public int getBlockSize() {
721
                return 0;
722
        }
723

    
724
        public void setAffineTransform(AffineTransform t){
725
                
726
        }
727

    
728
        public int getOverviewCount(int band) throws BandAccessException, RasterDriverException {
729
                return getZoomLevels();
730
        }
731

    
732
        public int getOverviewWidth(int band, int overview) throws BandAccessException, RasterDriverException {
733
                return provider.getTileServer().getStruct().getLayerWidthOfTileMatrixByLevel(overview) * 
734
                                provider.getTileServer().getStruct().getTileSizeByLevel(overview)[0];
735
        }
736

    
737
        public int getOverviewHeight(int band, int overview) throws BandAccessException, RasterDriverException {
738
                return provider.getTileServer().getStruct().getLayerHeightOfTileMatrixByLevel(overview) * 
739
                                provider.getTileServer().getStruct().getTileSizeByLevel(overview)[0];
740
        }
741

    
742
        public boolean isOverviewsSupported() {
743
                return false;
744
        }
745

    
746
        public String getName() {
747
                return NAME;
748
        }
749
        
750
        /**
751
         * Convierte un punto desde coordenadas pixel a coordenadas del mundo.
752
         * @param pt Punto a transformar
753
         * @return punto transformado en coordenadas del mundo
754
         */
755
        public Point2D rasterToWorld(Point2D pt) {
756
                Point2D p = new Point2D.Double();
757
                getAffineTransform().transform(pt, p);
758
                return p;
759
        }
760

    
761
        /**
762
         * Convierte un punto desde del mundo a coordenadas pixel.
763
         * @param pt Punto a transformar
764
         * @return punto transformado en coordenadas pixel
765
         */
766
        public Point2D worldToRaster(Point2D pt) {
767
                Point2D p = new Point2D.Double();
768
                try {
769
                        getAffineTransform().inverseTransform(pt, p);
770
                } catch (NoninvertibleTransformException e) {
771
                        return pt;
772
                }
773
                return p;
774
        }
775
        
776
        public void setStatus(RasterProvider provider) {
777
                if(provider instanceof TileProvider) {
778
                }
779
        }
780
        
781
        /**
782
         * ASigna el par?metro de inicializaci?n del driver.
783
         */
784
        @Override
785
        public void setParam(DataStoreProviderServices storeServices, DataStoreParameters param) {
786
                if(param instanceof RemoteStoreParameters)
787
                        this.uri = ((RasterDataParameters)param).getURI();
788
                this.param = param;
789
                this.storeServices = storeServices;
790
        }
791
        
792
        public String getInfoByPoint(double x, double y, ICancellable cancellable) throws InfoByPointException {
793
                if(provider != null)
794
                        return provider.getInfoByPoint(x, y, cancellable);
795
                return "Not implemented";
796
        }
797
        
798
        public String getInfoByPoint(int x, int y, Extent bbox, int w, int h, ICancellable cancellable) throws InfoByPointException {
799
                if(provider != null)
800
                        return provider.getInfoByPoint(x, y, bbox, w, h, cancellable);
801
                return "Not implemented";
802
        }
803
        
804
        public ColorInterpretation getColorInterpretation() {
805
                return provider.getColorInterpretation();
806
        }
807

    
808
        /**
809
         * Asigna el objeto que contiene que contiene la interpretaci?n de
810
         * color por banda
811
         * @param DataStoreColorInterpretation
812
         */
813
        public void setColorInterpretation(ColorInterpretation colorInterpretation) {
814
                provider.setColorInterpretation(colorInterpretation);
815
        }
816
        
817
        public int[] getTileSize(int level) {
818
                return provider.getTileServer().getStruct().getTileSizeByLevel(level);
819
        }
820
        
821
        public void deleteLayerFromCache() {
822
                TileCacheManager  manager = TileCacheLocator.getManager();
823
                TileCache tileCache = manager.getTileCache(RasterLibrary.pathTileCache);
824
                if(tiledLayer != null)
825
                        tileCache.removeLayer(tiledLayer);
826
        }
827
        
828
        public TileServer getTileServer() {
829
                return secondLevelTileServer;
830
        }
831
        
832
        public void setSecondLevelTileServer(TileServer tileServer) {
833
                this.secondLevelTileServer = tileServer;
834
        }
835
        
836
        public void setTileServer(Class<?> tileServer) throws InitializeException {
837
                //TODO:Manejar excepciones
838
                //Crear par?metros
839
                TileDataParametersImpl par = new TileDataParametersImpl();
840
                par.setDataParameters(getDataParameters());
841
                par.setSecondLevelCache(true); //No crea un nuevo provider
842
                
843
                //Crea el proveedor de tiles de segundo nivel
844
                TileProvider newProvider = null;
845
                newProvider = new TileProvider(par, null);
846
                newProvider.setProvider(this.provider);
847

    
848
                //Instancia el TileServer pasado por el cliente con el TileProvider de segundo nivel
849
                Constructor<?> constructor;
850
                TileServer tServer = null;
851
                try {
852
                        constructor = tileServer.getConstructor(new Class<?>[]{DefaultRasterProvider.class});
853
                        Object [] args2 = {newProvider};
854
                        tServer = (TileServer)constructor.newInstance(args2);
855
                } catch (SecurityException e) {
856
                        e.printStackTrace();
857
                } catch (NoSuchMethodException e) {
858
                        e.printStackTrace();
859
                } catch (IllegalArgumentException e) {
860
                        e.printStackTrace();
861
                } catch (InstantiationException e) {
862
                        e.printStackTrace();
863
                } catch (IllegalAccessException e) {
864
                        e.printStackTrace();
865
                } catch (InvocationTargetException e) {
866
                        e.printStackTrace();
867
                }
868
                
869
                //Asigna el TileServer al nuevo provider de segundo nivel
870
                newProvider.setSecondLevelTileServer(tServer);
871
                
872
                //Asigna al provider de tiles de primer nivel el de segundo. 
873
                //Solo si las estructuras de cach? son diferentes
874
                if(!provider.getTileServer().getStruct().compare(tServer.getStruct())) {
875
                        this.setProvider(newProvider);
876
                        tiledLayer = null;
877
                }
878
        }
879
        
880
}