Statistics
| Revision:

gvsig-raster / org.gvsig.raster.wcs / trunk / org.gvsig.raster.wcs / org.gvsig.raster.wcs.io / src / main / java / org / gvsig / raster / wcs / io / WCSProvider.java @ 3483

History | View | Annotate | Download (29.7 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.ArrayList;
12
import java.util.Hashtable;
13

    
14
import org.apache.commons.lang3.StringUtils;
15
import org.cresques.cts.IProjection;
16
import org.gvsig.fmap.dal.DALLocator;
17
import org.gvsig.fmap.dal.DataStore;
18
import org.gvsig.fmap.dal.DataStoreParameters;
19
import org.gvsig.fmap.dal.coverage.RasterLocator;
20
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
21
import org.gvsig.fmap.dal.coverage.datastruct.BandList;
22
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
23
import org.gvsig.fmap.dal.coverage.exception.BandAccessException;
24
import org.gvsig.fmap.dal.coverage.exception.BandNotFoundInListException;
25
import org.gvsig.fmap.dal.coverage.exception.FileNotOpenException;
26
import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
27
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
28
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
29
import org.gvsig.fmap.dal.coverage.exception.QueryException;
30
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
31
import org.gvsig.fmap.dal.coverage.exception.RemoteServiceException;
32
import org.gvsig.fmap.dal.coverage.store.RasterQuery;
33
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
34
import org.gvsig.fmap.dal.coverage.store.props.HistogramComputer;
35
import org.gvsig.fmap.dal.coverage.store.props.Transparency;
36
import org.gvsig.fmap.dal.exception.InitializeException;
37
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
38
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
39
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
40
import org.gvsig.metadata.MetadataLocator;
41
import org.gvsig.raster.cache.tile.provider.TileServer;
42
import org.gvsig.raster.impl.buffer.DefaultRasterQuery;
43
import org.gvsig.raster.impl.buffer.SpiRasterQuery;
44
import org.gvsig.raster.impl.datastruct.BandListImpl;
45
import org.gvsig.raster.impl.datastruct.DatasetBandImpl;
46
import org.gvsig.raster.impl.datastruct.ExtentImpl;
47
import org.gvsig.raster.impl.provider.AbstractRasterProvider;
48
import org.gvsig.raster.impl.provider.RasterProvider;
49
import org.gvsig.raster.impl.provider.RemoteRasterProvider;
50
import org.gvsig.raster.impl.store.DefaultRasterStore;
51
import org.gvsig.raster.impl.store.DefaultStoreFactory;
52
import org.gvsig.raster.impl.store.properties.DataStoreColorInterpretation;
53
import org.gvsig.raster.impl.store.properties.DataStoreTransparency;
54
import org.gvsig.raster.impl.store.properties.RemoteDataStoreStatistics;
55
import org.gvsig.raster.impl.store.properties.RemoteStoreHistogram;
56
import org.gvsig.raster.util.DefaultProviderServices;
57
import org.gvsig.raster.wcs.io.downloader.WCSTileServer;
58
import org.gvsig.remoteclient.wcs.WCSStatus;
59
import org.gvsig.tools.ToolsLocator;
60
/**
61
 * Clase que representa al driver de acceso a datos de wcs.
62
 *
63
 * @author Nacho Brodin (nachobrodin@gmail.com)
64
 */
65
public class WCSProvider extends AbstractRasterProvider implements RemoteRasterProvider {
66
        public static String                NAME                     = "Wcs Store";
67
        public static String                DESCRIPTION              = "Wcs Raster file";
68
        public static final String          METADATA_DEFINITION_NAME = "WcsStore";
69

    
70
        private Extent                      viewRequest              = null;
71
        private static Hashtable<URL, WCSConnector>    
72
        drivers                  = new Hashtable<URL, WCSConnector> ();
73
        private boolean                     open                     = false;
74
        private DataStoreTransparency       fileTransparency         = null;
75
        private File                        lastRequest              = null;
76
        private AbstractRasterProvider      lastRequestProvider      = null; 
77

    
78
        public static void register() {
79
                DataManagerProviderServices dataman = (DataManagerProviderServices) DALLocator.getDataManager();
80
                if (dataman != null && !dataman.getStoreProviders().contains(NAME)) {
81
                        dataman.registerStoreProvider(NAME,
82
                                        WCSProvider.class, WCSDataParametersImpl.class);
83
                }
84

    
85
                if (!dataman.getExplorerProviders().contains(NAME)) {
86
                        dataman.registerExplorerProvider(NAME, WCSServerExplorer.class, WCSServerExplorerParameters.class);
87
                }
88
                dataman.registerStoreFactory(NAME, DefaultStoreFactory.class);
89
        }
90

    
91
        public WCSProvider() throws NotSupportedExtensionException {
92
                super();
93
        }
94

    
95
        /**
96
         * Constructor. Abre el dataset.
97
         * @param proj Proyecci?n
98
         * @param fName Nombre del fichero
99
         * @throws NotSupportedExtensionException
100
         */
101
        public WCSProvider(String params) throws InitializeException {
102
                super(params);
103
                if(params instanceof String) {
104
                        WCSDataParametersImpl p = new WCSDataParametersImpl();
105
                        p.setURI((String)params);
106
                        super.init(p, null, ToolsLocator.getDynObjectManager()
107
                                        .createDynObject(
108
                                                        MetadataLocator.getMetadataManager().getDefinition(
109
                                                                        DataStore.METADATA_DEFINITION_NAME)));
110
                        init(p, null);
111
                }
112
        }
113

    
114
        public WCSProvider(WCSDataParametersImpl params,
115
                        DataStoreProviderServices storeServices) throws InitializeException {
116
                super(params, storeServices, ToolsLocator.getDynObjectManager()
117
                                .createDynObject(
118
                                                MetadataLocator.getMetadataManager().getDefinition(
119
                                                                DataStore.METADATA_DEFINITION_NAME)));
120
                init(params, storeServices);
121
        }
122

    
123
        /**
124
         * Gets the connector from the URL
125
         * @return
126
         * @throws RemoteServiceException
127
         */
128
        public WCSConnector getConnector() throws RemoteServiceException {
129
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
130
                URL url = null;
131
                try {
132
                        url = new URL(p.getURI());
133
                } catch (Exception e) {
134
                        throw new RemoteServiceException("Malformed URL",e);
135
                }
136
                try {
137
                        return WCSProvider.getConnectorFromURL(url);
138
                } catch (IOException e) {
139
                        throw new RemoteServiceException("Error getting the connector",e);
140
                }
141
        }
142

    
143
        /**
144
         * Crea las referencias al fichero y carga
145
         * las estructuras con la informaci?n y los metadatos.
146
         * @param proj Proyecci?n
147
         * @param param Parametros de carga
148
         * @throws NotSupportedExtensionException
149
         * @throws RasterDriverException 
150
         */
151
        public void init (DataStoreParameters params,
152
                        DataStoreProviderServices storeServices) throws InitializeException {
153
                setParam(storeServices, params);
154
                open = true;
155
                try {
156
                        loadInitialInfo();
157
                } catch (RasterDriverException e) {
158
                        throw new InitializeException(e.getMessage(), e);
159
                }
160

    
161
                stats = new RemoteDataStoreStatistics(this);
162
        }
163

    
164
        public static final WCSConnector getConnectorFromURL(URL url) throws IOException {
165
                WCSConnector drv = (WCSConnector) drivers.get(url);
166
                if (drv == null) {
167
                        drv = new WCSConnector(url);
168
                        drivers.put(url, drv);
169
                }
170
                return drv;
171
        }
172

    
173
        /**
174
         * Obtiene el objeto que contiene que contiene la interpretaci?n de
175
         * color por banda
176
         * @return
177
         */
178
        public ColorInterpretation getColorInterpretation() {
179
                if(super.getColorInterpretation() == null) {
180
                        ColorInterpretation colorInterpretation = new DataStoreColorInterpretation();
181
                        colorInterpretation.initColorInterpretation(getBandCount());
182
                        if(getBandCount() == 3) {
183
                                colorInterpretation = DataStoreColorInterpretation.createRGBInterpretation();
184
                        } else {
185
                                for (int i = 0; i < getBandCount(); i++) {
186
                                        colorInterpretation.setColorInterpValue(i, DataStoreColorInterpretation.GRAY_BAND);
187
                                }
188
                        }
189
                        setColorInterpretation(colorInterpretation);
190
                }
191
                return super.getColorInterpretation();
192
        }
193

    
194
        /**
195
         * Gets WCS parameters
196
         * @return
197
         */
198
        public WCSDataParameters getParameters() {
199
                return (WCSDataParameters)parameters;
200
        }
201

    
202
        public AffineTransform getAffineTransform() {
203
                Extent e = getExtent();
204
                double resolutionX = e.width() / getWidth();
205
                double resolutionY = e.height() / getHeight();
206
                ownTransformation = new AffineTransform(
207
                                resolutionX, 
208
                                0, 
209
                                0, 
210
                                -resolutionY, 
211
                                e.getULX() - (resolutionX / 2),
212
                                e.getULY() - (resolutionY / 2));
213
                externalTransformation = (AffineTransform) ownTransformation.clone();
214
                return ownTransformation;
215
        }
216

    
217
        /**
218
         * Calcula el extent en coordenadas del mundo real
219
         * @return Extent
220
         */
221
        public Extent getExtent() {
222
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
223
                try {
224
                        p.setFormat("image/tiff");
225
                        if(p.getSRSCode() == null){
226
                                WCSConnector connector = WCSProvider.getConnectorFromURL(new URL(p.getURI()));
227
                                ArrayList srs = connector.getSRSs(p.getCoverageName());
228
                                if(!srs.isEmpty() && !StringUtils.isBlank((String)srs.get(0))){
229
                                        p.setSRSID((String) srs.get(0));
230
                                }else{
231
                                        return null;
232
                                }
233
                        }
234
                        Rectangle2D r = getConnector().getFullExtent(p.getCoverageName(), p.getSRSCode());
235
                        if(r == null)
236
                                return null;
237
                        return new ExtentImpl(r.getX(),  r.getY() + r.getHeight(), r.getX() + r.getWidth(), r.getY());
238
                } catch (RemoteServiceException e1) {
239
                        e1.printStackTrace();
240
                } catch (IOException e) {
241
                        e.printStackTrace();
242
                }
243
                return null;
244
        }
245

    
246
        public Rectangle2D getLayerExtent(String layerName, String srs) throws RemoteServiceException {
247
                return null;
248
        }
249

    
250
        public RasterProvider load() {
251
                return this;
252
        }
253

    
254
        public boolean isOpen() {
255
                return open;
256
        }
257

    
258
        public void close() {
259
                open = false;
260
        }
261

    
262
        public Transparency getTransparency() {
263
                if(fileTransparency == null)
264
                        fileTransparency = new DataStoreTransparency(getColorInterpretation());
265
                return fileTransparency;
266
        }
267

    
268
        public String translateFileName(String fileName) {
269
                return fileName;
270
        }
271

    
272
        public void setView(Extent e) {
273
                viewRequest = e;
274
        }
275

    
276
        public Extent getView() {
277
                return viewRequest;
278
        }
279

    
280
        public double getWidth() {
281
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
282
                try {
283
                        return getConnector().getWidth(p.getCoverageName());
284
                } catch (RemoteServiceException e) {
285
                        e.printStackTrace();
286
                }
287
                return 0;
288
        }
289

    
290
        public double getHeight() {
291
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
292
                try {
293
                        return getConnector().getHeight(p.getCoverageName());
294
                } catch (RemoteServiceException e) {
295
                        e.printStackTrace();
296
                }
297
                return 0;
298
        }
299

    
300
        public Object readCompleteLine(int line, int band)
301
                        throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
302
                return null;
303
        }
304

    
305
        /**
306
         * When the remote layer has fixed size this method downloads the file and return its reference. 
307
         * File layer has in the long side FIXED_SIZE pixels and the bounding box is complete. This file could be
308
         * useful to build an histogram or calculate statistics. This represents a sample of data.
309
         * @return
310
         * @throws RasterDriverException
311
         */
312
        public File getFileLayer() throws RasterDriverException {
313
                Extent e = getExtent();
314
                Rectangle2D bBox = new Rectangle2D.Double(e.getULX(), e.getLRY(), e.width(), e.height());
315
                WCSStatus wcsStatus = loadWCSStatus(bBox);
316

    
317
                return downloadFile(wcsStatus, e, (int)getWidth(), (int)getHeight());
318
        }
319

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

    
345
                try {
346
                        lastRequestProvider = openLastRequest();
347
                        return lastRequestProvider.readBlock(pos, blockHeight, scale);
348
                } catch (ProviderNotRegisteredException exc) {
349
                        throw new RasterDriverException("Error building GdalDriver", exc);
350
                } catch (InitializeException exc) {
351
                        throw new RasterDriverException("Error building GdalDriver", exc);
352
                }
353
        }
354

    
355
        public double getLastRequestHeight() 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.getHeight();
366
        }
367

    
368
        public double getLastRequestWidth() throws RasterDriverException {
369
                if(lastRequestProvider == null) {
370
                        try {
371
                                lastRequestProvider = openLastRequest();
372
                        } catch (ProviderNotRegisteredException e) {
373
                                throw new RasterDriverException("Error building GdalDriver", e);
374
                        } catch (InitializeException e) {
375
                                throw new RasterDriverException("Error building GdalDriver", e);
376
                        }
377
                }
378
                return lastRequestProvider.getWidth();
379
        }
380

    
381
        public File getLastRequest() {
382
                return lastRequest;
383
        }
384

    
385
        public Buffer getBufferLastRequest() throws ProcessInterruptedException, RasterDriverException {
386
                try {
387
                        lastRequestProvider = openLastRequest();
388

    
389
                        /*BandList bandList = new BandListImpl();
390
                        for (int i = 0; i < lastRequestProvider.getBandCount(); i++) {
391
                                try {
392
                                        bandList.addBand(new DatasetBandImpl(lastRequest.getPath(), i, Buffer.TYPE_BYTE, 3));
393
                                } catch (BandNotFoundInListException e1) {
394
                                }
395
                        }
396
                        bandList.setDrawableBands(new int[]{0, 1, 2});*/
397

    
398
                        RasterQuery q = RasterLocator.getManager().createQuery();
399
                        q.setAreaOfInterest(lastRequestProvider.getExtent(), 
400
                                        (int)lastRequestProvider.getWidth(), 
401
                                        (int)lastRequestProvider.getHeight());
402
                        q.setAllDrawableBands();
403
                        q.setAdjustToExtent(true);
404

    
405
                        DefaultRasterStore store = new DefaultRasterStore();
406
                        store.setProvider(lastRequestProvider);
407
                        return store.query(q);
408
                } catch (ProviderNotRegisteredException e) {
409
                        throw new RasterDriverException("Error building GdalDriver", e);
410
                } catch (InitializeException e) {
411
                        throw new RasterDriverException("Error building GdalDriver", e);
412
                } catch (QueryException e) {
413
                        throw new RasterDriverException("Error reading data", e);
414
                }
415
        }
416

    
417
        /**
418
         * Opens the last request downloaded
419
         * @return
420
         * @throws ProviderNotRegisteredException
421
         * @throws InitializeException
422
         * @throws RasterDriverException
423
         */
424
        private AbstractRasterProvider openLastRequest() throws ProviderNotRegisteredException, InitializeException, RasterDriverException {
425
                if(lastRequestProvider != null)
426
                        lastRequestProvider.close();
427
                File lastFile = getFileLayer();
428
                lastRequestProvider = DefaultProviderServices.loadProvider(new File(lastFile.getPath()));
429
                return lastRequestProvider;
430
        }
431

    
432
        public Object getData(int x, int y, int band)
433
                        throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
434
                int w = 25;
435
                int h = 25;
436

    
437
                Point2D p1 = rasterToWorld(new Point2D.Double(x, y));
438
                Point2D p2 = rasterToWorld(new Point2D.Double(x + w, y + h));
439
                Rectangle2D bBox = new Rectangle2D.Double(p1.getX(), p1.getY(), Math.abs(p1.getX() - p2.getX()), Math.abs(p1.getY() - p2.getY()));
440

    
441
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
442
                WCSStatus wcsStatus = new WCSStatus();
443
                wcsStatus.setCoveraName(p.getCoverageName());
444
                wcsStatus.setSrs(p.getSRSCode());
445
                wcsStatus.setFormat(p.getFormat());
446
                wcsStatus.setOnlineResource(p.getOnlineResource() != null ? (String) p.getOnlineResource().get("GetCoverage") : null);
447
                wcsStatus.setExtent(bBox);
448
                wcsStatus.setHeight(h);
449
                wcsStatus.setWidth(w);
450
                wcsStatus.setDepth(p.getDepth());
451
                wcsStatus.setParameters(p.getParameter());
452
                wcsStatus.setTime(p.getTime());
453

    
454
                lastRequest = downloadFile(wcsStatus, p1.getX(), p1.getY(), p2.getX(), p2.getY(), w, h);
455

    
456
                AbstractRasterProvider driver = null;
457
                try {
458
                        driver = DefaultProviderServices.loadProvider(new File(lastRequest.getPath()));
459
                        /*Buffer buf = DefaultRasterManager.getInstance().createBuffer(getDataType()[0], w, h, getBandCount(), true);
460
                        BandList bandList = new BandListImpl();
461
                        int[] drawable = new int[getBandCount()];
462
                        for (int i = 0; i < getBandCount(); i++) {
463
                                try {
464
                                        bandList.addBand(new DatasetBandImpl(lastRequest.getPath(), i, getDataType()[i], getBandCount()));
465
                                        drawable[i] = i;
466
                                } catch (BandNotFoundInListException e1) {
467
                                }
468
                        }
469
                        bandList.setDrawableBands(drawable);*/
470

    
471
                        RasterQuery q = RasterLocator.getManager().createQuery();
472
                        Rectangle r = new Rectangle(0, 0, 25, 25);
473
                        q.setAreaOfInterest(r);
474
                        q.setAllDrawableBands();
475
                        DefaultRasterStore store = new DefaultRasterStore();
476
                        store.setProvider(driver);
477

    
478
                        Buffer buf = store.query(q);
479
                        driver.close();
480
                        if(buf.getDataType() == Buffer.TYPE_BYTE) {
481
                                return new Integer(buf.getElemByte(0, 0, band));
482
                        }
483
                        if(buf.getDataType() == Buffer.TYPE_SHORT) {
484
                                return new Integer(buf.getElemShort(0, 0, band));
485
                        }
486
                        if(buf.getDataType() == Buffer.TYPE_INT) {
487
                                return new Integer(buf.getElemInt(0, 0, band));
488
                        }
489
                        if(buf.getDataType() == Buffer.TYPE_FLOAT) {
490
                                return new Float(buf.getElemFloat(0, 0, band));
491
                        }
492
                        if(buf.getDataType() == Buffer.TYPE_DOUBLE) {
493
                                return new Double(buf.getElemDouble(0, 0, band));
494
                        }
495
                } catch(InitializeException e) {
496
                        throw new RasterDriverException("", e);
497
                } catch (ProviderNotRegisteredException e) {
498
                        throw new RasterDriverException("", e);
499
                } catch (ProcessInterruptedException e) {
500
                } catch (QueryException e) {
501
                        throw new RasterDriverException("", e);
502
                }
503
                return null;
504
        }
505

    
506
        /**
507
         * Gets the georeferencing file name form a raster file
508
         * @param file
509
         * a raster file
510
         * @return
511
         * a georeferencing file
512
         */
513
        private String getWorldFile(String file){                
514
                String worldFile = file;
515
                int index = file.lastIndexOf(".");
516
                if (index > 0) {                        
517
                        worldFile = file.substring(0, index) + getExtensionWorldFile();
518
                } else {
519
                        worldFile = file + getExtensionWorldFile();
520
                }
521
                return worldFile;
522
        }
523

    
524
        /**
525
         * Obtiene la extensi?n del fichero de georreferenciaci?n
526
         * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
527
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
528
         */
529
        private String getExtensionWorldFile() {
530
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
531
                String extWorldFile = ".wld";
532
                if(p.getFormat().equals("image/tif") || p.getFormat().equals("image/tiff")) {
533
                        extWorldFile = ".tfw";
534
                }
535
                return extWorldFile;
536
        }
537

    
538
        private WCSStatus loadWCSStatus(Rectangle2D bBox) {
539
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
540
                WCSStatus wcsStatus = new WCSStatus();
541
                wcsStatus.setCoveraName(p.getCoverageName());
542
                wcsStatus.setSrs(p.getSRSCode());
543
                wcsStatus.setFormat(p.getFormat());
544
                wcsStatus.setOnlineResource(p.getOnlineResource() != null ? (String) p.getOnlineResource().get("GetCoverage") : null);
545
                wcsStatus.setExtent(bBox);
546
                wcsStatus.setHeight(p.getHeight());
547
                wcsStatus.setWidth(p.getWidth());
548
                wcsStatus.setDepth(p.getDepth());
549
                wcsStatus.setParameters(p.getParameter());
550
                wcsStatus.setTime(p.getTime());
551
                return wcsStatus;
552
        }
553

    
554
        public boolean needEnhanced() {
555
                return (getDataType()[0] != Buffer.TYPE_BYTE || 
556
                                (getBandCount() == 1 && getDataType()[0] == Buffer.TYPE_BYTE));
557
        }
558

    
559
        /**
560
         * This function downloads the file and creates the georeferencing file
561
         * @param wcsStatus
562
         * @param ulx
563
         * @param uly
564
         * @param lrx
565
         * @param lry
566
         * @param w
567
         * @param h
568
         * @return
569
         * @throws RasterDriverException
570
         */
571
        private File downloadFile(WCSStatus wcsStatus, double ulx, double uly, double lrx, double lry, int w, int h) throws RasterDriverException {
572
                Extent extent = new ExtentImpl(ulx, uly, lrx, lry);
573
                return downloadFile(wcsStatus, extent, w, h);
574
        }
575

    
576
        /**
577
         * This function downloads the file and creates the georeferencing file
578
         * @param wcsStatus
579
         * @param ulx
580
         * @param uly
581
         * @param lrx
582
         * @param lry
583
         * @param w
584
         * @param h
585
         * @return
586
         * @throws RasterDriverException
587
         */
588
        private File downloadFile(WCSStatus wcsStatus, Extent extent, int w, int h) throws RasterDriverException {
589
                try {
590
                        lastRequest = getConnector().getCoverage(wcsStatus, ((WCSDataParametersImpl)parameters).getCancellable());
591
                } catch (RemoteServiceException e) {
592
                        throw new RasterDriverException(e.getMessage(), e);
593
                }
594

    
595
                String nameWorldFile = getWorldFile(lastRequest.getPath());
596
                try {
597
                        fileUtil.createWorldFile(nameWorldFile, extent, w, h);
598
                } catch (IOException e) {
599
                        throw new RasterDriverException("Error downloading file", e);
600
                }
601

    
602
                return lastRequest;
603
        }
604

    
605
        /**
606
         * Assigns the list of bands RGB and read a window of data
607
         * @param rasterBuf
608
         * @param bandList
609
         * @param lastFile
610
         * @param ulx
611
         * @param uly
612
         * @param lrx
613
         * @param lry
614
         * @return
615
         * @throws RasterDriverException
616
         * @throws ProcessInterruptedException
617
         */
618
        public Buffer getBuffer(BandList bandList, File lastFile, 
619
                        double ulx, double uly, double lrx, double lry) throws RasterDriverException, ProcessInterruptedException {
620
                try {
621
                        //El nombre de fichero que ha puesto en el bandList es el del servidor y no el del fichero en disco
622
                        /*String serverName = bandList.getBand(0).getFileName();
623
                        for (int i = 0; i < bandList.getBandCount(); i++) {
624
                                bandList.getBand(i).setFileName(lastFile.getPath());
625
                        }*/
626

    
627
                        AbstractRasterProvider driver = DefaultProviderServices.loadProvider(new File(lastFile.getPath()));
628

    
629
                        RasterQuery q = RasterLocator.getManager().createQuery();
630
                        q.setAreaOfInterest(new ExtentImpl(ulx, uly, lrx, lry));
631
                        q.setDrawableBands(bandList.getDrawableBands());
632
                        DefaultRasterStore store = new DefaultRasterStore();
633
                        store.setProvider(driver);
634
                        Buffer buf = store.query(q);
635

    
636
                        /*for (int i = 0; i < bandList.getBandCount(); i++) {
637
                                bandList.getBand(i).setFileName(serverName);
638
                        }*/
639

    
640
                        return buf;
641
                } catch (ProviderNotRegisteredException e) {
642
                        throw new RasterDriverException("Error building GdalDriver", e);
643
                } catch (InitializeException e) {
644
                        throw new RasterDriverException("Error building GdalDriver", e);
645
                } catch (QueryException e) {
646
                        throw new RasterDriverException("Error reading data", e);
647
                }
648
        }
649

    
650
        @Override
651
        public void loadBuffer(SpiRasterQuery query)
652
                        throws ProcessInterruptedException, RasterDriverException {
653
                Extent ex = query.getAdjustedRequestBoundingBox();
654
                WCSStatus wcsStatus = loadWCSStatus(ex.toRectangle2D());
655

    
656
                lastRequest = downloadFile(
657
                                wcsStatus, 
658
                                ex, 
659
                                query.getAdjustedBufWidth(), 
660
                                query.getAdjustedBufHeight());
661

    
662
                if (lastRequest == null) {
663
                        return;
664
                }
665

    
666
                try {
667
                        AbstractRasterProvider driver = DefaultProviderServices.loadProvider(new File(lastRequest.getPath()));
668
                        DefaultRasterStore store = new DefaultRasterStore();
669
                        store.setProvider(driver);
670
                        query.createBuffer(store);
671
                        store.query((RasterQuery)query);
672
                } catch (ProviderNotRegisteredException e) {
673
                        throw new RasterDriverException("Error building GdalDriver", e);
674
                } catch (InitializeException e) {
675
                        throw new RasterDriverException("Error building GdalDriver", e);
676
                } catch (QueryException e) {
677
                        throw new RasterDriverException("Error reading data", e);
678
                }
679

    
680
        }
681

    
682
        /**
683
         * When a WCS provider is opened the information of data type and number of bands is not
684
         * available. Only after the first time a raster has been downloaded it can be know.
685
         * @param newDataType
686
         * @param buf
687
         * @param bandList
688
         * @return
689
         * @throws RasterDriverException 
690
         */
691
        private void loadInitialInfo() throws RasterDriverException {
692
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
693
                Extent ext = getExtent();
694
                if(ext != null){
695
                        Rectangle2D bBox = ext.toRectangle2D();
696
                        int w = 0;
697
                        int h = 0;
698
                        if(ext.width() > ext.height()) {
699
                                w = 200;
700
                                h = (int)((ext.height() * w) / ext.width());
701
                        } else {
702
                                h = 200;
703
                                w = (int)((ext.width() * h) / ext.height());
704
                        }
705
                        p.setWidth(w);
706
                        p.setHeight(h);
707
                        p.setExtent(bBox);
708
                        WCSStatus wcsStatus = loadWCSStatus(bBox);
709

    
710
                        lastRequest = downloadFile(wcsStatus, ext.getULX(), ext.getULY(), ext.getLRX(), ext.getLRY(), w, h);
711
                        AbstractRasterProvider driver;
712
                        try {
713
                                driver = DefaultProviderServices.loadProvider(lastRequest);
714
                                setDataType(driver.getDataType());
715
                                bandCount = driver.getBandCount();
716
                                driver.close();
717
                        } catch (ProviderNotRegisteredException e) {
718
                                throw new RasterDriverException("", e);
719
                        } catch (InitializeException e) {
720
                                throw new RasterDriverException("", e);
721
                        }
722
                }
723
        }
724

    
725
        /**
726
         * When a WCS provider is opened the information of data type and number of bands is not
727
         * available. Only after the first time a raster has been downloaded it can be know.
728
         * @param newDataType
729
         * @param buf
730
         * @param bandList
731
         * @return
732
         */
733
        /*private Buffer changeBufferDataType(int newDataType, Buffer buf, BandList bandList) {
734
                Buffer newBuffer = null;
735
                if(buf.getDataType() != newDataType) {
736
                        newBuffer = DefaultRasterManager.getInstance().createReadOnlyBuffer(newDataType, buf.getWidth(), buf.getHeight(), buf.getBandCount()); 
737
                        buf.free();
738
                } else 
739
                        return buf;
740

741
                bandList.clear();
742
                for(int i = 0; i < getBandCount(); i++)
743
                        try {
744
                                int dataType = getDataType()[i];
745
                                DatasetBand band = new DatasetBandImpl(getFName(), i, dataType, getBandCount());
746
                                bandList.addBand(band, i);
747
                        } catch(BandNotFoundInListException ex) {
748
                                //No a?adimos la banda
749
                        }
750
                return newBuffer;
751
        }*/
752

    
753
        /*public Buffer getWindow(int x, int y, int w, int h, 
754
                        BandList bandList, Buffer rasterBuf, TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
755
                Point2D p1 = rasterToWorld(new Point2D.Double(x, y));
756
                Point2D p2 = rasterToWorld(new Point2D.Double(x + w, y + h));
757
                Rectangle2D bBox = new Rectangle2D.Double(p1.getX(), p1.getY(), Math.abs(p1.getX() - p2.getX()), Math.abs(p1.getY() - p2.getY()));
758
                WCSStatus wcsStatus = loadWCSStatus(bBox);
759

760
                lastRequest = downloadFile(wcsStatus, p1.getX(), p1.getY(), p2.getX(), p2.getY(), rasterBuf.getWidth(), rasterBuf.getHeight());
761

762
                if (lastRequest == null) {
763
                        return rasterBuf;
764
                }
765

766
                AbstractRasterProvider driver = null;
767
                try {
768
                        driver = DefaultProviderServices.loadProvider(new File(lastRequest.getPath()));
769

770
                        //El nombre de fichero que ha puesto en el bandList es el del servidor y no el del fichero en disco
771
                        String serverName = bandList.getBand(0).getFileName();
772
                        for (int i = 0; i < bandList.getBandCount(); i++) {
773
                                bandList.getBand(i).setFileName(lastRequest.getPath());
774
                        }
775

776
                        DefaultRasterQuery q = (DefaultRasterQuery)RasterLocator.getManager().createQuery();
777
                        q.setAreaOfInterest(0, 0, w, h);
778
                        q.setBandList(bandList);
779
                        q.setBuffer(rasterBuf);
780
                        Buffer buf = driver.getDataSet(q);
781

782
                        for (int i = 0; i < bandList.getBandCount(); i++) {
783
                                bandList.getBand(i).setFileName(serverName);
784
                        }
785
                        driver.close();
786
                        return buf;
787
                } catch (ProviderNotRegisteredException e) {
788
                        throw new RasterDriverException("Error building GdalDriver", e);
789
                } catch (InitializeException e) {
790
                        throw new RasterDriverException("Error building GdalDriver", e);
791
                }
792
        }*/
793

    
794
        public int getBlockSize() {
795
                return 0;
796
        }
797

    
798
        public void setAffineTransform(AffineTransform t){
799

    
800
        }
801

    
802
        public int getOverviewCount(int band) throws BandAccessException, RasterDriverException {
803
                return 0;
804
        }
805

    
806
        public int getOverviewWidth(int band, int overview) throws BandAccessException, RasterDriverException {
807
                return 0;
808
        }
809

    
810
        public int getOverviewHeight(int band, int overview) throws BandAccessException, RasterDriverException {
811
                return 0;
812
        }
813

    
814
        public boolean isOverviewsSupported() {
815
                return false;
816
        }
817

    
818
        public boolean isReproyectable() {
819
                return false;
820
        }
821

    
822
        public String getProviderName() {
823
                return NAME;
824
        }
825

    
826
        public String getName() {
827
                return this.getParameters().getCoverageName();
828
        }
829

    
830
        /**
831
         * Convierte un punto desde coordenadas pixel a coordenadas del mundo.
832
         * @param pt Punto a transformar
833
         * @return punto transformado en coordenadas del mundo
834
         */
835
        public Point2D rasterToWorld(Point2D pt) {
836
                Point2D p = new Point2D.Double();
837
                getAffineTransform().transform(pt, p);
838
                return p;
839
        }
840

    
841
        /**
842
         * Convierte un punto desde del mundo a coordenadas pixel.
843
         * @param pt Punto a transformar
844
         * @return punto transformado en coordenadas pixel
845
         */
846
        public Point2D worldToRaster(Point2D pt) {
847
                Point2D p = new Point2D.Double();
848
                try {
849
                        getAffineTransform().inverseTransform(pt, p);
850
                } catch (NoninvertibleTransformException e) {
851
                        return pt;
852
                }
853
                return p;
854
        }
855

    
856
        public void setStatus(RasterProvider provider) {
857
                if(provider instanceof WCSProvider) {
858
                }
859
        }
860

    
861
        /**
862
         * ASigna el par?metro de inicializaci?n del driver.
863
         */
864
        public void setParam(DataStoreProviderServices storeServices, DataStoreParameters param) {
865
                if(param instanceof WCSDataParametersImpl)
866
                        this.uri = ((WCSDataParametersImpl)param).getURI();
867
                this.param = param;
868
        }
869

    
870
        /**
871
         * Gets the suffix of the downloaded image
872
         * @return
873
         */
874
        public String getFileSuffix() {
875
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
876
                String format = p.getFormat().toLowerCase();
877
                if (format == null) {
878
                        return "xml";
879
                }
880
                if (format.indexOf("png") >= 0){
881
                        return "png";
882
                }        
883
                if (format.indexOf("xml") >= 0){
884
                        return "xml";
885
                }        
886
                if (format.indexOf("gif") >= 0){
887
                        return "gif";
888
                }
889
                if (format.indexOf("tif") >= 0){
890
                        return "tif";
891
                }
892
                if (format.indexOf("bmp") >= 0){
893
                        return "bmp";
894
                }
895
                if (format.indexOf("jpg") >= 0
896
                                || format.indexOf("jpeg") >= 0){
897
                        return "jpg";                         
898
                }
899
                return "xml";
900
        }
901

    
902
        public TileServer getTileServer() {
903
                if(tileServer == null) {
904
                        DefaultRasterStore store = new DefaultRasterStore();
905
                        store.setProvider(this);
906
                        tileServer = new WCSTileServer(store);
907
                }
908
                return tileServer;
909
        }
910

    
911
        public boolean isRasterEnclosed() {
912
                return true;
913
        }
914

    
915
        public String getRMFFile() {
916
                if(lastRequest != null)
917
                        return fileUtil.getNameWithoutExtension(lastRequest.getAbsolutePath()) + ".rmf";
918
                return null;
919
        }
920

    
921
        public HistogramComputer getHistogramComputer() {
922
                if (histogram == null)
923
                        histogram = new RemoteStoreHistogram(this);
924
                return histogram;
925
        }
926

    
927
}