Statistics
| Revision:

gvsig-raster / org.gvsig.raster.wcs / branches / org.gvsig.raster.wcs_dataaccess_refactoring / org.gvsig.raster.wcs.io / src / main / java / org / gvsig / raster / wcs / io / WCSProvider.java @ 2426

History | View | Annotate | Download (29.3 KB)

1
package org.gvsig.raster.wcs.io;
2

    
3
import java.awt.Rectangle;
4
import java.awt.geom.AffineTransform;
5
import java.awt.geom.NoninvertibleTransformException;
6
import java.awt.geom.Point2D;
7
import java.awt.geom.Rectangle2D;
8
import java.io.File;
9
import java.io.IOException;
10
import java.net.URL;
11
import java.util.Hashtable;
12

    
13
import org.gvsig.fmap.dal.DALLocator;
14
import org.gvsig.fmap.dal.DataStore;
15
import org.gvsig.fmap.dal.DataStoreParameters;
16
import org.gvsig.fmap.dal.coverage.RasterLocator;
17
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
18
import org.gvsig.fmap.dal.coverage.datastruct.BandList;
19
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
20
import org.gvsig.fmap.dal.coverage.exception.BandAccessException;
21
import org.gvsig.fmap.dal.coverage.exception.BandNotFoundInListException;
22
import org.gvsig.fmap.dal.coverage.exception.FileNotOpenException;
23
import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
24
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
25
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
26
import org.gvsig.fmap.dal.coverage.exception.QueryException;
27
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
28
import org.gvsig.fmap.dal.coverage.exception.RemoteServiceException;
29
import org.gvsig.fmap.dal.coverage.store.RasterQuery;
30
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
31
import org.gvsig.fmap.dal.coverage.store.props.HistogramComputer;
32
import org.gvsig.fmap.dal.coverage.store.props.Transparency;
33
import org.gvsig.fmap.dal.exception.InitializeException;
34
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
35
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
36
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
37
import org.gvsig.metadata.MetadataLocator;
38
import org.gvsig.raster.cache.tile.provider.TileServer;
39
import org.gvsig.raster.impl.buffer.DefaultRasterQuery;
40
import org.gvsig.raster.impl.buffer.SpiRasterQuery;
41
import org.gvsig.raster.impl.datastruct.BandListImpl;
42
import org.gvsig.raster.impl.datastruct.DatasetBandImpl;
43
import org.gvsig.raster.impl.datastruct.ExtentImpl;
44
import org.gvsig.raster.impl.provider.AbstractRasterProvider;
45
import org.gvsig.raster.impl.provider.RasterProvider;
46
import org.gvsig.raster.impl.provider.RemoteRasterProvider;
47
import org.gvsig.raster.impl.store.DefaultRasterStore;
48
import org.gvsig.raster.impl.store.DefaultStoreFactory;
49
import org.gvsig.raster.impl.store.properties.DataStoreColorInterpretation;
50
import org.gvsig.raster.impl.store.properties.DataStoreTransparency;
51
import org.gvsig.raster.impl.store.properties.RemoteDataStoreStatistics;
52
import org.gvsig.raster.impl.store.properties.RemoteStoreHistogram;
53
import org.gvsig.raster.util.DefaultProviderServices;
54
import org.gvsig.raster.wcs.io.downloader.WCSTileServer;
55
import org.gvsig.remoteclient.wcs.WCSStatus;
56
import org.gvsig.tools.ToolsLocator;
57
/**
58
 * Clase que representa al driver de acceso a datos de wcs.
59
 *
60
 * @author Nacho Brodin (nachobrodin@gmail.com)
61
 */
62
public class WCSProvider extends AbstractRasterProvider implements RemoteRasterProvider {
63
        public static String                NAME                     = "Wcs Store";
64
        public static String                DESCRIPTION              = "Wcs Raster file";
65
        public static final String          METADATA_DEFINITION_NAME = "WcsStore";
66
        
67
        private Extent                      viewRequest              = null;
68
        private static Hashtable<URL, WCSConnector>    
69
                                            drivers                  = new Hashtable<URL, WCSConnector> ();
70
        private boolean                     open                     = false;
71
        private DataStoreTransparency       fileTransparency         = null;
72
        private File                        lastRequest              = null;
73
        private AbstractRasterProvider      lastRequestProvider      = null; 
74
        
75
        public static void register() {
76
                DataManagerProviderServices dataman = (DataManagerProviderServices) DALLocator.getDataManager();
77
                if (dataman != null && !dataman.getStoreProviders().contains(NAME)) {
78
                        dataman.registerStoreProvider(NAME,
79
                                        WCSProvider.class, WCSDataParametersImpl.class);
80
                }
81

    
82
                if (!dataman.getExplorerProviders().contains(NAME)) {
83
                        dataman.registerExplorerProvider(NAME, WCSServerExplorer.class, WCSServerExplorerParameters.class);
84
                }
85
                dataman.registerStoreFactory(NAME, DefaultStoreFactory.class);
86
        }
87
        
88
        public WCSProvider() throws NotSupportedExtensionException {
89
                super();
90
        }
91
        
92
        /**
93
         * Constructor. Abre el dataset.
94
         * @param proj Proyecci?n
95
         * @param fName Nombre del fichero
96
         * @throws NotSupportedExtensionException
97
         */
98
        public WCSProvider(String params) throws InitializeException {
99
                super(params);
100
                if(params instanceof String) {
101
                        WCSDataParametersImpl p = new WCSDataParametersImpl();
102
                        p.setURI((String)params);
103
                        super.init(p, null, ToolsLocator.getDynObjectManager()
104
                                        .createDynObject(
105
                                                        MetadataLocator.getMetadataManager().getDefinition(
106
                                                                        DataStore.METADATA_DEFINITION_NAME)));
107
                        init(p, null);
108
                }
109
        }
110
        
111
        public WCSProvider(WCSDataParametersImpl params,
112
                        DataStoreProviderServices storeServices) throws InitializeException {
113
                super(params, storeServices, ToolsLocator.getDynObjectManager()
114
                                .createDynObject(
115
                                                MetadataLocator.getMetadataManager().getDefinition(
116
                                                                DataStore.METADATA_DEFINITION_NAME)));
117
                init(params, storeServices);
118
        }
119
        
120
        /**
121
         * Gets the connector from the URL
122
         * @return
123
         * @throws RemoteServiceException
124
         */
125
        public WCSConnector getConnector() throws RemoteServiceException {
126
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
127
                URL url = null;
128
                try {
129
                        url = new URL(p.getURI());
130
                } catch (Exception e) {
131
                        throw new RemoteServiceException("Malformed URL",e);
132
                }
133
                try {
134
                        return WCSProvider.getConnectorFromURL(url);
135
                } catch (IOException e) {
136
                        throw new RemoteServiceException("Error getting the connector",e);
137
                }
138
        }
139
        
140
        /**
141
         * Crea las referencias al fichero y carga
142
         * las estructuras con la informaci?n y los metadatos.
143
         * @param proj Proyecci?n
144
         * @param param Parametros de carga
145
         * @throws NotSupportedExtensionException
146
         * @throws RasterDriverException 
147
         */
148
        public void init (DataStoreParameters params,
149
                        DataStoreProviderServices storeServices) throws InitializeException {
150
                setParam(storeServices, params);
151
                open = true;
152
                try {
153
                        loadInitialInfo();
154
                } catch (RasterDriverException e) {
155
                        throw new InitializeException(e.getMessage(), e);
156
                }
157
                
158
                stats = new RemoteDataStoreStatistics(this);
159
        }
160
        
161
        public static final WCSConnector getConnectorFromURL(URL url) throws IOException {
162
                WCSConnector drv = (WCSConnector) drivers.get(url);
163
                if (drv == null) {
164
                        drv = new WCSConnector(url);
165
                        drivers.put(url, drv);
166
                }
167
                return drv;
168
        }
169
        
170
        /**
171
         * Obtiene el objeto que contiene que contiene la interpretaci?n de
172
         * color por banda
173
         * @return
174
         */
175
        public ColorInterpretation getColorInterpretation() {
176
                if(super.getColorInterpretation() == null) {
177
                        ColorInterpretation colorInterpretation = new DataStoreColorInterpretation();
178
                        colorInterpretation.initColorInterpretation(getBandCount());
179
                        if(getBandCount() == 3) {
180
                                colorInterpretation = DataStoreColorInterpretation.createRGBInterpretation();
181
                        } else {
182
                                for (int i = 0; i < getBandCount(); i++) {
183
                                        colorInterpretation.setColorInterpValue(i, DataStoreColorInterpretation.GRAY_BAND);
184
                                }
185
                        }
186
                        setColorInterpretation(colorInterpretation);
187
                }
188
                return super.getColorInterpretation();
189
        }
190
        
191
        /**
192
         * Gets WCS parameters
193
         * @return
194
         */
195
        public WCSDataParameters getParameters() {
196
                return (WCSDataParameters)parameters;
197
        }
198
        
199
        public AffineTransform getAffineTransform() {
200
                Extent e = getExtent();
201
                double resolutionX = e.width() / getWidth();
202
                double resolutionY = e.height() / getHeight();
203
                ownTransformation = new AffineTransform(
204
                                resolutionX, 
205
                                0, 
206
                                0, 
207
                                -resolutionY, 
208
                                e.getULX() - (resolutionX / 2),
209
                                e.getULY() - (resolutionY / 2));
210
                externalTransformation = (AffineTransform) ownTransformation.clone();
211
                return ownTransformation;
212
        }
213
        
214
        /**
215
         * Calcula el extent en coordenadas del mundo real
216
         * @return Extent
217
         */
218
        public Extent getExtent() {
219
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
220
                try {
221
                        Rectangle2D r = getConnector().getFullExtent(p.getCoverageName(), p.getSRSCode());
222
                        if(r == null)
223
                                return null;
224
                        return new ExtentImpl(r.getX(),  r.getY() + r.getHeight(), r.getX() + r.getWidth(), r.getY());
225
                } catch (RemoteServiceException e1) {
226
                        e1.printStackTrace();
227
                } catch (IOException e) {
228
                        e.printStackTrace();
229
                }
230
                return null;
231
        }
232

    
233
        public Rectangle2D getLayerExtent(String layerName, String srs) throws RemoteServiceException {
234
                return null;
235
        }
236

    
237
        public RasterProvider load() {
238
                return this;
239
        }
240
        
241
        public boolean isOpen() {
242
                return open;
243
        }
244

    
245
        public void close() {
246
                open = false;
247
        }
248
        
249
        public Transparency getTransparency() {
250
                if(fileTransparency == null)
251
                        fileTransparency = new DataStoreTransparency(getColorInterpretation());
252
                return fileTransparency;
253
        }
254

    
255
        public String translateFileName(String fileName) {
256
                return fileName;
257
        }
258

    
259
        public void setView(Extent e) {
260
                viewRequest = e;
261
        }
262

    
263
        public Extent getView() {
264
                return viewRequest;
265
        }
266
        
267
        public double getWidth() {
268
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
269
                try {
270
                        return getConnector().getWidth(p.getCoverageName());
271
                } catch (RemoteServiceException e) {
272
                        e.printStackTrace();
273
                }
274
                return 0;
275
        }
276

    
277
        public double getHeight() {
278
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
279
                try {
280
                        return getConnector().getHeight(p.getCoverageName());
281
                } catch (RemoteServiceException e) {
282
                        e.printStackTrace();
283
                }
284
                return 0;
285
        }
286

    
287
        public Object readCompleteLine(int line, int band)
288
                throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
289
                return null;
290
        }
291
        
292
        /**
293
         * When the remote layer has fixed size this method downloads the file and return its reference. 
294
         * File layer has in the long side FIXED_SIZE pixels and the bounding box is complete. This file could be
295
         * useful to build an histogram or calculate statistics. This represents a sample of data.
296
         * @return
297
         * @throws RasterDriverException
298
         */
299
        public File getFileLayer() throws RasterDriverException {
300
                Extent e = getExtent();
301
                Rectangle2D bBox = new Rectangle2D.Double(e.getULX(), e.getLRY(), e.width(), e.height());
302
                WCSStatus wcsStatus = loadWCSStatus(bBox);
303
                
304
                return downloadFile(wcsStatus, e, (int)getWidth(), (int)getHeight());
305
        }
306

    
307
        /**
308
         * Reads a complete block of data and returns an tridimensional array of the right type. This function is useful
309
         * to read a file very fast without setting a view. In a WCS service when the size is fixed then it will read the
310
         * entire image but when the source hasn't pixel size it will read a sample of data. This set of data will have
311
         * the size defined in FIXED_SIZE. 
312
         * 
313
         * @param pos Posici?n donde se empieza  a leer
314
         * @param blockHeight Altura m?xima del bloque leido
315
         * @return Object que es un array tridimendional del tipo de datos del raster. (Bandas X Filas X Columnas)
316
         * @throws InvalidSetViewException
317
         * @throws FileNotOpenException
318
         * @throws RasterDriverException
319
         */
320
        public Object readBlock(int pos, int blockHeight, double scale) 
321
        throws InvalidSetViewException, FileNotOpenException, RasterDriverException, ProcessInterruptedException {
322
                File lastFile = getFileLayer();
323
                BandList bandList = new BandListImpl();
324
                for (int i = 0; i < 3; i++) {
325
                        try {
326
                                bandList.addBand(new DatasetBandImpl(lastFile.getPath(), pos, Buffer.TYPE_BYTE, 3));
327
                        } catch (BandNotFoundInListException e1) {
328
                        }
329
                }
330
                bandList.setDrawableBands(new int[]{0, 1, 2});
331

    
332
                try {
333
                        lastRequestProvider = openLastRequest();
334
                        return lastRequestProvider.readBlock(pos, blockHeight, scale);
335
                } catch (ProviderNotRegisteredException exc) {
336
                        throw new RasterDriverException("Error building GdalDriver", exc);
337
                } catch (InitializeException exc) {
338
                        throw new RasterDriverException("Error building GdalDriver", exc);
339
                }
340
        }
341
        
342
        public double getLastRequestHeight() throws RasterDriverException {
343
                if(lastRequestProvider == null) {
344
                        try {
345
                                lastRequestProvider = openLastRequest();
346
                        } catch (ProviderNotRegisteredException e) {
347
                                throw new RasterDriverException("Error building GdalDriver", e);
348
                        } catch (InitializeException e) {
349
                                throw new RasterDriverException("Error building GdalDriver", e);
350
                        }
351
                }
352
                return lastRequestProvider.getHeight();
353
        }
354
        
355
        public double getLastRequestWidth() throws RasterDriverException {
356
                if(lastRequestProvider == null) {
357
                        try {
358
                                lastRequestProvider = openLastRequest();
359
                        } catch (ProviderNotRegisteredException e) {
360
                                throw new RasterDriverException("Error building GdalDriver", e);
361
                        } catch (InitializeException e) {
362
                                throw new RasterDriverException("Error building GdalDriver", e);
363
                        }
364
                }
365
                return lastRequestProvider.getWidth();
366
        }
367
        
368
        public File getLastRequest() {
369
                return lastRequest;
370
        }
371
        
372
        public Buffer getBufferLastRequest() throws ProcessInterruptedException, RasterDriverException {
373
                try {
374
                        lastRequestProvider = openLastRequest();
375
                        
376
                        /*BandList bandList = new BandListImpl();
377
                        for (int i = 0; i < lastRequestProvider.getBandCount(); i++) {
378
                                try {
379
                                        bandList.addBand(new DatasetBandImpl(lastRequest.getPath(), i, Buffer.TYPE_BYTE, 3));
380
                                } catch (BandNotFoundInListException e1) {
381
                                }
382
                        }
383
                        bandList.setDrawableBands(new int[]{0, 1, 2});*/
384
                        
385
                        RasterQuery q = RasterLocator.getManager().createQuery();
386
                        q.setAreaOfInterest(lastRequestProvider.getExtent(), 
387
                                        (int)lastRequestProvider.getWidth(), 
388
                                        (int)lastRequestProvider.getHeight());
389
                        q.setAllDrawableBands();
390
                        q.setAdjustToExtent(true);
391
                        
392
                        DefaultRasterStore store = new DefaultRasterStore();
393
                        store.setProvider(lastRequestProvider);
394
                        return store.query(q);
395
                } catch (ProviderNotRegisteredException e) {
396
                        throw new RasterDriverException("Error building GdalDriver", e);
397
                } catch (InitializeException e) {
398
                        throw new RasterDriverException("Error building GdalDriver", e);
399
                } catch (QueryException e) {
400
                        throw new RasterDriverException("Error reading data", e);
401
                }
402
        }
403
        
404
        /**
405
         * Opens the last request downloaded
406
         * @return
407
         * @throws ProviderNotRegisteredException
408
         * @throws InitializeException
409
         * @throws RasterDriverException
410
         */
411
        private AbstractRasterProvider openLastRequest() throws ProviderNotRegisteredException, InitializeException, RasterDriverException {
412
                if(lastRequestProvider != null)
413
                        lastRequestProvider.close();
414
                File lastFile = getFileLayer();
415
                lastRequestProvider = DefaultProviderServices.loadProvider(new File(lastFile.getPath()));
416
                return lastRequestProvider;
417
        }
418

    
419
        public Object getData(int x, int y, int band)
420
                throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
421
                int w = 25;
422
                int h = 25;
423
                
424
                Point2D p1 = rasterToWorld(new Point2D.Double(x, y));
425
                Point2D p2 = rasterToWorld(new Point2D.Double(x + w, y + h));
426
                Rectangle2D bBox = new Rectangle2D.Double(p1.getX(), p1.getY(), Math.abs(p1.getX() - p2.getX()), Math.abs(p1.getY() - p2.getY()));
427
                
428
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
429
                WCSStatus wcsStatus = new WCSStatus();
430
                wcsStatus.setCoveraName(p.getCoverageName());
431
                wcsStatus.setSrs(p.getSRSCode());
432
                wcsStatus.setFormat(p.getFormat());
433
                wcsStatus.setOnlineResource(p.getOnlineResource() != null ? (String) p.getOnlineResource().get("GetCoverage") : null);
434
                wcsStatus.setExtent(bBox);
435
                wcsStatus.setHeight(h);
436
                wcsStatus.setWidth(w);
437
                wcsStatus.setDepth(p.getDepth());
438
                wcsStatus.setParameters(p.getParameter());
439
                wcsStatus.setTime(p.getTime());
440
                
441
                lastRequest = downloadFile(wcsStatus, p1.getX(), p1.getY(), p2.getX(), p2.getY(), w, h);
442
                
443
                AbstractRasterProvider driver = null;
444
                try {
445
                        driver = DefaultProviderServices.loadProvider(new File(lastRequest.getPath()));
446
                        /*Buffer buf = DefaultRasterManager.getInstance().createBuffer(getDataType()[0], w, h, getBandCount(), true);
447
                        BandList bandList = new BandListImpl();
448
                        int[] drawable = new int[getBandCount()];
449
                        for (int i = 0; i < getBandCount(); i++) {
450
                                try {
451
                                        bandList.addBand(new DatasetBandImpl(lastRequest.getPath(), i, getDataType()[i], getBandCount()));
452
                                        drawable[i] = i;
453
                                } catch (BandNotFoundInListException e1) {
454
                                }
455
                        }
456
                        bandList.setDrawableBands(drawable);*/
457
                        
458
                        RasterQuery q = RasterLocator.getManager().createQuery();
459
                        Rectangle r = new Rectangle(0, 0, 25, 25);
460
                        q.setAreaOfInterest(r);
461
                        q.setAllDrawableBands();
462
                        DefaultRasterStore store = new DefaultRasterStore();
463
                        store.setProvider(driver);
464
                        
465
                        Buffer buf = store.query(q);
466
                        driver.close();
467
                        if(buf.getDataType() == Buffer.TYPE_BYTE) {
468
                                return new Integer(buf.getElemByte(0, 0, band));
469
                        }
470
                        if(buf.getDataType() == Buffer.TYPE_SHORT) {
471
                                return new Integer(buf.getElemShort(0, 0, band));
472
                        }
473
                        if(buf.getDataType() == Buffer.TYPE_INT) {
474
                                return new Integer(buf.getElemInt(0, 0, band));
475
                        }
476
                        if(buf.getDataType() == Buffer.TYPE_FLOAT) {
477
                                return new Float(buf.getElemFloat(0, 0, band));
478
                        }
479
                        if(buf.getDataType() == Buffer.TYPE_DOUBLE) {
480
                                return new Double(buf.getElemDouble(0, 0, band));
481
                        }
482
                } catch(InitializeException e) {
483
                        throw new RasterDriverException("", e);
484
                } catch (ProviderNotRegisteredException e) {
485
                        throw new RasterDriverException("", e);
486
                } catch (ProcessInterruptedException e) {
487
                } catch (QueryException e) {
488
                        throw new RasterDriverException("", e);
489
                }
490
                return null;
491
        }
492
        
493
        /**
494
         * Gets the georeferencing file name form a raster file
495
         * @param file
496
         * a raster file
497
         * @return
498
         * a georeferencing file
499
         */
500
        private String getWorldFile(String file){                
501
                String worldFile = file;
502
                int index = file.lastIndexOf(".");
503
                if (index > 0) {                        
504
                        worldFile = file.substring(0, index) + getExtensionWorldFile();
505
                } else {
506
                        worldFile = file + getExtensionWorldFile();
507
                }
508
                return worldFile;
509
        }
510
        
511
        /**
512
         * Obtiene la extensi?n del fichero de georreferenciaci?n
513
         * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
514
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
515
         */
516
        private String getExtensionWorldFile() {
517
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
518
                String extWorldFile = ".wld";
519
                if(p.getFormat().equals("image/tif") || p.getFormat().equals("image/tiff")) {
520
                        extWorldFile = ".tfw";
521
                }
522
                return extWorldFile;
523
        }
524
        
525
        private WCSStatus loadWCSStatus(Rectangle2D bBox) {
526
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
527
                WCSStatus wcsStatus = new WCSStatus();
528
                wcsStatus.setCoveraName(p.getCoverageName());
529
                wcsStatus.setSrs(p.getSRSCode());
530
                wcsStatus.setFormat(p.getFormat());
531
                wcsStatus.setOnlineResource(p.getOnlineResource() != null ? (String) p.getOnlineResource().get("GetCoverage") : null);
532
                wcsStatus.setExtent(bBox);
533
                wcsStatus.setHeight(p.getHeight());
534
                wcsStatus.setWidth(p.getWidth());
535
                wcsStatus.setDepth(p.getDepth());
536
                wcsStatus.setParameters(p.getParameter());
537
                wcsStatus.setTime(p.getTime());
538
                return wcsStatus;
539
        }
540
        
541
        public boolean needEnhanced() {
542
                return (getDataType()[0] != Buffer.TYPE_BYTE || 
543
                                (getBandCount() == 1 && getDataType()[0] == Buffer.TYPE_BYTE));
544
        }
545
        
546
        /**
547
         * This function downloads the file and creates the georeferencing file
548
         * @param wcsStatus
549
         * @param ulx
550
         * @param uly
551
         * @param lrx
552
         * @param lry
553
         * @param w
554
         * @param h
555
         * @return
556
         * @throws RasterDriverException
557
         */
558
        private File downloadFile(WCSStatus wcsStatus, double ulx, double uly, double lrx, double lry, int w, int h) throws RasterDriverException {
559
                Extent extent = new ExtentImpl(ulx, uly, lrx, lry);
560
                return downloadFile(wcsStatus, extent, w, h);
561
        }
562
        
563
        /**
564
         * This function downloads the file and creates the georeferencing file
565
         * @param wcsStatus
566
         * @param ulx
567
         * @param uly
568
         * @param lrx
569
         * @param lry
570
         * @param w
571
         * @param h
572
         * @return
573
         * @throws RasterDriverException
574
         */
575
        private File downloadFile(WCSStatus wcsStatus, Extent extent, int w, int h) throws RasterDriverException {
576
                try {
577
                        lastRequest = getConnector().getCoverage(wcsStatus, ((WCSDataParametersImpl)parameters).getCancellable());
578
                } catch (RemoteServiceException e) {
579
                        throw new RasterDriverException(e.getMessage(), e);
580
                }
581
                
582
                String nameWorldFile = getWorldFile(lastRequest.getPath());
583
                try {
584
                        fileUtil.createWorldFile(nameWorldFile, extent, w, h);
585
                } catch (IOException e) {
586
                        throw new RasterDriverException("Error downloading file", e);
587
                }
588

    
589
                return lastRequest;
590
        }
591
        
592
        /**
593
         * Assigns the list of bands RGB and read a window of data
594
         * @param rasterBuf
595
         * @param bandList
596
         * @param lastFile
597
         * @param ulx
598
         * @param uly
599
         * @param lrx
600
         * @param lry
601
         * @return
602
         * @throws RasterDriverException
603
         * @throws ProcessInterruptedException
604
         */
605
        public Buffer getBuffer(BandList bandList, File lastFile, 
606
                        double ulx, double uly, double lrx, double lry) throws RasterDriverException, ProcessInterruptedException {
607
                try {
608
                        //El nombre de fichero que ha puesto en el bandList es el del servidor y no el del fichero en disco
609
                        /*String serverName = bandList.getBand(0).getFileName();
610
                        for (int i = 0; i < bandList.getBandCount(); i++) {
611
                                bandList.getBand(i).setFileName(lastFile.getPath());
612
                        }*/
613
                        
614
                        AbstractRasterProvider driver = DefaultProviderServices.loadProvider(new File(lastFile.getPath()));
615
                        
616
                        RasterQuery q = RasterLocator.getManager().createQuery();
617
                        q.setAreaOfInterest(new ExtentImpl(ulx, uly, lrx, lry));
618
                        q.setDrawableBands(bandList.getDrawableBands());
619
                        DefaultRasterStore store = new DefaultRasterStore();
620
                        store.setProvider(driver);
621
                        Buffer buf = store.query(q);
622
                        
623
                        /*for (int i = 0; i < bandList.getBandCount(); i++) {
624
                                bandList.getBand(i).setFileName(serverName);
625
                        }*/
626
                        
627
                        return buf;
628
                } catch (ProviderNotRegisteredException e) {
629
                        throw new RasterDriverException("Error building GdalDriver", e);
630
                } catch (InitializeException e) {
631
                        throw new RasterDriverException("Error building GdalDriver", e);
632
                } catch (QueryException e) {
633
                        throw new RasterDriverException("Error reading data", e);
634
                }
635
        }
636
        
637
        @Override
638
        public void loadBuffer(SpiRasterQuery query)
639
                        throws ProcessInterruptedException, RasterDriverException {
640
                Extent ex = query.getAdjustedRequestBoundingBox();
641
                WCSStatus wcsStatus = loadWCSStatus(ex.toRectangle2D());
642
                
643
                lastRequest = downloadFile(
644
                                wcsStatus, 
645
                                ex, 
646
                                query.getAdjustedBufWidth(), 
647
                                query.getAdjustedBufHeight());
648
                
649
                if (lastRequest == null) {
650
                        return;
651
                }
652
                
653
                try {
654
                        AbstractRasterProvider driver = DefaultProviderServices.loadProvider(new File(lastRequest.getPath()));
655
                        DefaultRasterStore store = new DefaultRasterStore();
656
                        store.setProvider(driver);
657
                        query.createBuffer(store);
658
                        store.query((RasterQuery)query);
659
                } catch (ProviderNotRegisteredException e) {
660
                        throw new RasterDriverException("Error building GdalDriver", e);
661
                } catch (InitializeException e) {
662
                        throw new RasterDriverException("Error building GdalDriver", e);
663
                } catch (QueryException e) {
664
                        throw new RasterDriverException("Error reading data", e);
665
                }
666
                
667
        }
668
        
669
        /**
670
         * When a WCS provider is opened the information of data type and number of bands is not
671
         * available. Only after the first time a raster has been downloaded it can be know.
672
         * @param newDataType
673
         * @param buf
674
         * @param bandList
675
         * @return
676
         * @throws RasterDriverException 
677
         */
678
        private void loadInitialInfo() throws RasterDriverException {
679
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
680
                Extent ext = getExtent();
681
                Rectangle2D bBox = ext.toRectangle2D();
682
                int w = 0;
683
                int h = 0;
684
                if(ext.width() > ext.height()) {
685
                        w = 200;
686
                        h = (int)((ext.height() * w) / ext.width());
687
                } else {
688
                        h = 200;
689
                        w = (int)((ext.width() * h) / ext.height());
690
                }
691
                p.setWidth(w);
692
                p.setHeight(h);
693
                p.setExtent(bBox);
694
                WCSStatus wcsStatus = loadWCSStatus(bBox);
695
                
696
                lastRequest = downloadFile(wcsStatus, ext.getULX(), ext.getULY(), ext.getLRX(), ext.getLRY(), w, h);
697
                AbstractRasterProvider driver;
698
                try {
699
                        driver = DefaultProviderServices.loadProvider(lastRequest);
700
                        setDataType(driver.getDataType());
701
                        bandCount = driver.getBandCount();
702
                        driver.close();
703
                } catch (ProviderNotRegisteredException e) {
704
                        throw new RasterDriverException("", e);
705
                } catch (InitializeException e) {
706
                        throw new RasterDriverException("", e);
707
                }
708
        }
709
        
710
        /**
711
         * When a WCS provider is opened the information of data type and number of bands is not
712
         * available. Only after the first time a raster has been downloaded it can be know.
713
         * @param newDataType
714
         * @param buf
715
         * @param bandList
716
         * @return
717
         */
718
        /*private Buffer changeBufferDataType(int newDataType, Buffer buf, BandList bandList) {
719
                Buffer newBuffer = null;
720
                if(buf.getDataType() != newDataType) {
721
                        newBuffer = DefaultRasterManager.getInstance().createReadOnlyBuffer(newDataType, buf.getWidth(), buf.getHeight(), buf.getBandCount()); 
722
                        buf.free();
723
                } else 
724
                        return buf;
725
                
726
                bandList.clear();
727
                for(int i = 0; i < getBandCount(); i++)
728
                        try {
729
                                int dataType = getDataType()[i];
730
                                DatasetBand band = new DatasetBandImpl(getFName(), i, dataType, getBandCount());
731
                                bandList.addBand(band, i);
732
                        } catch(BandNotFoundInListException ex) {
733
                                //No a?adimos la banda
734
                        }
735
                return newBuffer;
736
        }*/
737

    
738
        /*public Buffer getWindow(int x, int y, int w, int h, 
739
                        BandList bandList, Buffer rasterBuf, TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
740
                Point2D p1 = rasterToWorld(new Point2D.Double(x, y));
741
                Point2D p2 = rasterToWorld(new Point2D.Double(x + w, y + h));
742
                Rectangle2D bBox = new Rectangle2D.Double(p1.getX(), p1.getY(), Math.abs(p1.getX() - p2.getX()), Math.abs(p1.getY() - p2.getY()));
743
                WCSStatus wcsStatus = loadWCSStatus(bBox);
744
                
745
                lastRequest = downloadFile(wcsStatus, p1.getX(), p1.getY(), p2.getX(), p2.getY(), rasterBuf.getWidth(), rasterBuf.getHeight());
746
                
747
                if (lastRequest == null) {
748
                        return rasterBuf;
749
                }
750

751
                AbstractRasterProvider driver = null;
752
                try {
753
                        driver = DefaultProviderServices.loadProvider(new File(lastRequest.getPath()));
754
                        
755
                        //El nombre de fichero que ha puesto en el bandList es el del servidor y no el del fichero en disco
756
                        String serverName = bandList.getBand(0).getFileName();
757
                        for (int i = 0; i < bandList.getBandCount(); i++) {
758
                                bandList.getBand(i).setFileName(lastRequest.getPath());
759
                        }
760
                        
761
                        DefaultRasterQuery q = (DefaultRasterQuery)RasterLocator.getManager().createQuery();
762
                        q.setAreaOfInterest(0, 0, w, h);
763
                        q.setBandList(bandList);
764
                        q.setBuffer(rasterBuf);
765
                        Buffer buf = driver.getDataSet(q);
766

767
                        for (int i = 0; i < bandList.getBandCount(); i++) {
768
                                bandList.getBand(i).setFileName(serverName);
769
                        }
770
                        driver.close();
771
                        return buf;
772
                } catch (ProviderNotRegisteredException e) {
773
                        throw new RasterDriverException("Error building GdalDriver", e);
774
                } catch (InitializeException e) {
775
                        throw new RasterDriverException("Error building GdalDriver", e);
776
                }
777
        }*/
778

    
779
        public int getBlockSize() {
780
                return 0;
781
        }
782

    
783
        public void setAffineTransform(AffineTransform t){
784
                
785
        }
786

    
787
        public int getOverviewCount(int band) throws BandAccessException, RasterDriverException {
788
                return 0;
789
        }
790

    
791
        public int getOverviewWidth(int band, int overview) throws BandAccessException, RasterDriverException {
792
                return 0;
793
        }
794

    
795
        public int getOverviewHeight(int band, int overview) throws BandAccessException, RasterDriverException {
796
                return 0;
797
        }
798

    
799
        public boolean isOverviewsSupported() {
800
                return false;
801
        }
802

    
803
        public boolean isReproyectable() {
804
                return false;
805
        }
806

    
807
        public String getName() {
808
                return NAME;
809
        }
810
        
811
        /**
812
         * Convierte un punto desde coordenadas pixel a coordenadas del mundo.
813
         * @param pt Punto a transformar
814
         * @return punto transformado en coordenadas del mundo
815
         */
816
        public Point2D rasterToWorld(Point2D pt) {
817
                Point2D p = new Point2D.Double();
818
                getAffineTransform().transform(pt, p);
819
                return p;
820
        }
821

    
822
        /**
823
         * Convierte un punto desde del mundo a coordenadas pixel.
824
         * @param pt Punto a transformar
825
         * @return punto transformado en coordenadas pixel
826
         */
827
        public Point2D worldToRaster(Point2D pt) {
828
                Point2D p = new Point2D.Double();
829
                try {
830
                        getAffineTransform().inverseTransform(pt, p);
831
                } catch (NoninvertibleTransformException e) {
832
                        return pt;
833
                }
834
                return p;
835
        }
836
        
837
        public void setStatus(RasterProvider provider) {
838
                if(provider instanceof WCSProvider) {
839
                }
840
        }
841
        
842
        /**
843
         * ASigna el par?metro de inicializaci?n del driver.
844
         */
845
        public void setParam(DataStoreProviderServices storeServices, DataStoreParameters param) {
846
                if(param instanceof WCSDataParametersImpl)
847
                        this.uri = ((WCSDataParametersImpl)param).getURI();
848
                this.param = param;
849
        }
850
        
851
        /**
852
         * Gets the suffix of the downloaded image
853
         * @return
854
         */
855
        public String getFileSuffix() {
856
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
857
                String format = p.getFormat().toLowerCase();
858
                if (format == null) {
859
                        return "xml";
860
                }
861
                if (format.indexOf("png") >= 0){
862
                return "png";
863
                }        
864
            if (format.indexOf("xml") >= 0){
865
                return "xml";
866
            }        
867
            if (format.indexOf("gif") >= 0){
868
                return "gif";
869
            }
870
            if (format.indexOf("tif") >= 0){
871
                return "tif";
872
            }
873
            if (format.indexOf("bmp") >= 0){
874
                return "bmp";
875
            }
876
            if (format.indexOf("jpg") >= 0
877
                || format.indexOf("jpeg") >= 0){
878
                return "jpg";                         
879
            }
880
                return "xml";
881
        }
882
        
883
        public TileServer getTileServer() {
884
                if(tileServer == null) {
885
                        DefaultRasterStore store = new DefaultRasterStore();
886
                        store.setProvider(this);
887
                        tileServer = new WCSTileServer(store);
888
                }
889
                return tileServer;
890
        }
891
        
892
        public boolean isRasterEnclosed() {
893
                return true;
894
        }
895
        
896
        public String getRMFFile() {
897
                if(lastRequest != null)
898
                        return fileUtil.getNameWithoutExtension(lastRequest.getAbsolutePath()) + ".rmf";
899
                return null;
900
        }
901
        
902
        public HistogramComputer getHistogramComputer() {
903
                if (histogram == null)
904
                        histogram = new RemoteStoreHistogram(this);
905
                return histogram;
906
        }
907

    
908
}