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

History | View | Annotate | Download (31.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.URI;
11
import java.net.URISyntaxException;
12
import java.net.URL;
13
import java.util.ArrayList;
14
import java.util.Hashtable;
15

    
16
import org.apache.commons.io.FilenameUtils;
17
import org.apache.commons.lang3.StringUtils;
18
import org.slf4j.Logger;
19
import org.slf4j.LoggerFactory;
20

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

    
76
        private Extent                      viewRequest              = null;
77
        private static Hashtable<URL, WCSConnector>
78
        drivers                  = new Hashtable<URL, WCSConnector> ();
79
        private boolean                     open                     = false;
80
        private DataStoreTransparency       fileTransparency         = null;
81
        private File                        lastRequest              = null;
82
        private AbstractRasterProvider      lastRequestProvider      = null;
83
        private static final Logger         logger                    = LoggerFactory.getLogger(WCSProvider.class);
84

    
85
        public static void register() {
86
                DataManagerProviderServices dataman = (DataManagerProviderServices) DALLocator.getDataManager();
87
                if (dataman != null && !dataman.getStoreProviders().contains(NAME)) {
88
                        dataman.registerStoreProvider(NAME,
89
                                        WCSProvider.class, WCSDataParametersImpl.class);
90
                }
91

    
92
                if (!dataman.getExplorerProviders().contains(NAME)) {
93
                        dataman.registerExplorerProvider(NAME, WCSServerExplorer.class, WCSServerExplorerParameters.class);
94
                }
95
                dataman.registerStoreFactory(NAME, DefaultStoreFactory.class);
96
        }
97

    
98
        public WCSProvider() throws NotSupportedExtensionException {
99
                super();
100
        }
101

    
102
        /**
103
         * Constructor. Abre el dataset.
104
         * @throws OpenException
105
         * @throws NotSupportedExtensionException
106
     * @deprecated use {@link #WCSProvider(URI)}, this constructor will be removed in gvSIG 2.5
107
     */
108
        public WCSProvider(String params) throws InitializeException, OpenException {
109
                super(params);
110
        logger.info("Deprecated use of WCSProvider constructor");
111
                if(params instanceof String) {
112
                        WCSDataParametersImpl p = new WCSDataParametersImpl();
113
            try {
114
                p.setURI(new URI((String) params));
115
            } catch (URISyntaxException e) {
116
                throw new OpenException("Can't create URI from" + (String) params, e);
117
            }
118
            super.init(p, null, ToolsLocator.getDynObjectManager()
119
                                        .createDynObject(
120
                                                        MetadataLocator.getMetadataManager().getDefinition(
121
                                                                        DataStore.METADATA_DEFINITION_NAME)));
122
                        init(p, null);
123
                }
124
        }
125

    
126
    public WCSProvider(URI uri) throws InitializeException, OpenException {
127
        super(uri);
128
        WCSDataParametersImpl p = new WCSDataParametersImpl();
129
            p.setURI(uri);
130
        super.init(
131
            p,
132
            null,
133
            ToolsLocator.getDynObjectManager().createDynObject(
134
                MetadataLocator.getMetadataManager().getDefinition(DataStore.METADATA_DEFINITION_NAME)));
135
        init(p, null);
136
    }
137

    
138
        public WCSProvider(WCSDataParametersImpl params,
139
                        DataStoreProviderServices storeServices) throws InitializeException {
140
                super(params, storeServices, ToolsLocator.getDynObjectManager()
141
                                .createDynObject(
142
                                                MetadataLocator.getMetadataManager().getDefinition(
143
                                                                DataStore.METADATA_DEFINITION_NAME)));
144
                init(params, storeServices);
145
        }
146

    
147
        /**
148
         * Gets the connector from the URL
149
         * @return
150
         * @throws RemoteServiceException
151
         */
152
        public WCSConnector getConnector() throws RemoteServiceException {
153
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
154
                URL url = null;
155
                try {
156
                        url = p.getURI().toURL();
157
                } catch (Exception e) {
158
                        throw new RemoteServiceException("Malformed URL",e);
159
                }
160
                try {
161
                        return WCSProvider.getConnectorFromURL(url);
162
                } catch (IOException e) {
163
                        throw new RemoteServiceException("Error getting the connector",e);
164
                }
165
        }
166

    
167
        /**
168
         * Crea las referencias al fichero y carga
169
         * las estructuras con la informaci?n y los metadatos.
170
         * @param proj Proyecci?n
171
         * @param param Parametros de carga
172
         * @throws NotSupportedExtensionException
173
         * @throws RasterDriverException
174
         */
175
        public void init (DataStoreParameters params,
176
                        DataStoreProviderServices storeServices) throws InitializeException {
177
                setParam(storeServices, params);
178
                open = true;
179
                try {
180
                        loadInitialInfo();
181
                } catch (RasterDriverException e) {
182
                        throw new InitializeException(e.getMessage(), e);
183
                }
184

    
185
                stats = new RemoteDataStoreStatistics(this);
186
        }
187

    
188
        public static final WCSConnector getConnectorFromURL(URL url) throws IOException {
189
                WCSConnector drv = (WCSConnector) drivers.get(url);
190
                if (drv == null) {
191
                        drv = new WCSConnector(url);
192
                        drivers.put(url, drv);
193
                }
194
                return drv;
195
        }
196

    
197
        /**
198
         * Obtiene el objeto que contiene que contiene la interpretaci?n de
199
         * color por banda
200
         * @return
201
         */
202
        public ColorInterpretation getColorInterpretation() {
203
                if(super.getColorInterpretation() == null) {
204
                        ColorInterpretation colorInterpretation = new DataStoreColorInterpretation();
205
                        colorInterpretation.initColorInterpretation(getBandCount());
206
                        if(getBandCount() == 3) {
207
                                colorInterpretation = DataStoreColorInterpretation.createRGBInterpretation();
208
                        } else {
209
                                for (int i = 0; i < getBandCount(); i++) {
210
                                        colorInterpretation.setColorInterpValue(i, DataStoreColorInterpretation.GRAY_BAND);
211
                                }
212
                        }
213
                        setColorInterpretation(colorInterpretation);
214
                }
215
                return super.getColorInterpretation();
216
        }
217

    
218
        /**
219
         * Gets WCS parameters
220
         * @return
221
         */
222
        public WCSDataParameters getParameters() {
223
                return (WCSDataParameters)parameters;
224
        }
225

    
226
        public AffineTransform getAffineTransform() {
227
                Extent e = getExtent();
228
                double resolutionX = e.width() / getWidth();
229
                double resolutionY = e.height() / getHeight();
230

    
231

    
232
                ownTransformation = new AffineTransform(
233
                                resolutionX,                        // ESCALADO en X
234
                                0,                                  // CIZALLAMIENTO de la Y
235
                                0,                                  // CIZALLAMIENTO de la X
236
                                -resolutionY,                       // ESCALADO en Y
237
                                e.getULX() - (resolutionX / 2),     // TRASLACION en X
238
                                e.getULY() - (resolutionY / 2));    // TRASLACION en Y
239

    
240
                externalTransformation = (AffineTransform) ownTransformation.clone();
241
                return ownTransformation;
242
        }
243

    
244
        /**
245
         * Calcula el extent en coordenadas del mundo real
246
         * @return Extent
247
         */
248
        public Extent getExtent() {
249
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
250
                try {
251
                        p.setFormat("image/tiff");
252
                        if(p.getSRSCode() == null){
253
                                WCSConnector connector = WCSProvider.getConnectorFromURL(p.getURI().toURL());
254
                                ArrayList srs = connector.getSRSs(p.getCoverageName());
255
                                if(!srs.isEmpty() && !StringUtils.isBlank((String)srs.get(0))){
256
                                        p.setSRSID((String) srs.get(0));
257
                                }else{
258
                                        return null;
259
                                }
260
                        }
261
                        Rectangle2D r = getConnector().getFullExtent(p.getCoverageName(), p.getSRSCode());
262
                        if(r == null)
263
                                return null;
264
                        return new ExtentImpl(r.getX(),  r.getY() + r.getHeight(), r.getX() + r.getWidth(), r.getY());
265
                } catch (RemoteServiceException e1) {
266
                        e1.printStackTrace();
267
                } catch (IOException e) {
268
                        e.printStackTrace();
269
                }
270
                return null;
271
        }
272

    
273
        public Rectangle2D getLayerExtent(String layerName, String srs) throws RemoteServiceException {
274
                return null;
275
        }
276

    
277
        public RasterProvider load() {
278
                return this;
279
        }
280

    
281
        public boolean isOpen() {
282
                return open;
283
        }
284

    
285
        public void close() {
286
                open = false;
287
        }
288

    
289
        public Transparency getTransparency() {
290
                if(fileTransparency == null)
291
                        fileTransparency = new DataStoreTransparency(getColorInterpretation());
292
                return fileTransparency;
293
        }
294

    
295
        public URI translateURI(URI uri) {
296
                return uri;
297
        }
298

    
299
        public void setView(Extent e) {
300
                viewRequest = e;
301
        }
302

    
303
        public Extent getView() {
304
                return viewRequest;
305
        }
306

    
307
        public double getWidth() {
308
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
309
                try {
310
                        return getConnector().getWidth(p.getCoverageName());
311
                } catch (RemoteServiceException e) {
312
                        e.printStackTrace();
313
                }
314
                return 0;
315
        }
316

    
317
        public double getHeight() {
318
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
319
                try {
320
                        return getConnector().getHeight(p.getCoverageName());
321
                } catch (RemoteServiceException e) {
322
                        e.printStackTrace();
323
                }
324
                return 0;
325
        }
326

    
327
        public Object readCompleteLine(int line, int band)
328
                        throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
329
                return null;
330
        }
331

    
332
        /**
333
         * When the remote layer has fixed size this method downloads the file and return its reference.
334
         * File layer has in the long side FIXED_SIZE pixels and the bounding box is complete. This file could be
335
         * useful to build an histogram or calculate statistics. This represents a sample of data.
336
         * @return
337
         * @throws RasterDriverException
338
         */
339
        public File getFileLayer() throws RasterDriverException {
340
                Extent e = getExtent();
341
                Rectangle2D bBox = new Rectangle2D.Double(e.getULX(), e.getLRY(), e.width(), e.height());
342
                WCSStatus wcsStatus = loadWCSStatus(bBox);
343

    
344
                return downloadFile(wcsStatus, e, (int)getWidth(), (int)getHeight());
345
        }
346

    
347
        /**
348
         * Reads a complete block of data and returns an tridimensional array of the right type. This function is useful
349
         * to read a file very fast without setting a view. In a WCS service when the size is fixed then it will read the
350
         * entire image but when the source hasn't pixel size it will read a sample of data. This set of data will have
351
         * the size defined in FIXED_SIZE.
352
         *
353
         * @param pos Posici?n donde se empieza  a leer
354
         * @param blockHeight Altura m?xima del bloque leido
355
         * @return Object que es un array tridimendional del tipo de datos del raster. (Bandas X Filas X Columnas)
356
         * @throws InvalidSetViewException
357
         * @throws FileNotOpenException
358
         * @throws RasterDriverException
359
         */
360
        public Object readBlock(int pos, int blockHeight, double scale)
361
                        throws InvalidSetViewException, FileNotOpenException, RasterDriverException, ProcessInterruptedException {
362
                File lastFile = getFileLayer();
363
                BandList bandList = new BandListImpl();
364
                for (int i = 0; i < 3; i++) {
365
                        try {
366
                                bandList.addBand(new DatasetBandImpl(lastFile.getPath(), pos, Buffer.TYPE_BYTE, 3));
367
                        } catch (BandNotFoundInListException e1) {
368
                        }
369
                }
370
                bandList.setDrawableBands(new int[]{0, 1, 2});
371

    
372
                try {
373
                        lastRequestProvider = openLastRequest();
374
                        return lastRequestProvider.readBlock(pos, blockHeight, scale);
375
                } catch (ProviderNotRegisteredException exc) {
376
                        throw new RasterDriverException("Error building GdalDriver", exc);
377
                } catch (InitializeException exc) {
378
                        throw new RasterDriverException("Error building GdalDriver", exc);
379
                }
380
        }
381

    
382
        public double getLastRequestHeight() throws RasterDriverException {
383
                if(lastRequestProvider == null) {
384
                        try {
385
                                lastRequestProvider = openLastRequest();
386
                        } catch (ProviderNotRegisteredException e) {
387
                                throw new RasterDriverException("Error building GdalDriver", e);
388
                        } catch (InitializeException e) {
389
                                throw new RasterDriverException("Error building GdalDriver", e);
390
                        }
391
                }
392
                return lastRequestProvider.getHeight();
393
        }
394

    
395
        public double getLastRequestWidth() throws RasterDriverException {
396
                if(lastRequestProvider == null) {
397
                        try {
398
                                lastRequestProvider = openLastRequest();
399
                        } catch (ProviderNotRegisteredException e) {
400
                                throw new RasterDriverException("Error building GdalDriver", e);
401
                        } catch (InitializeException e) {
402
                                throw new RasterDriverException("Error building GdalDriver", e);
403
                        }
404
                }
405
                return lastRequestProvider.getWidth();
406
        }
407

    
408
        public File getLastRequest() {
409
                return lastRequest;
410
        }
411

    
412
        public Buffer getBufferLastRequest() throws ProcessInterruptedException, RasterDriverException {
413
                try {
414
                        lastRequestProvider = openLastRequest();
415

    
416
                        /*BandList bandList = new BandListImpl();
417
                        for (int i = 0; i < lastRequestProvider.getBandCount(); i++) {
418
                                try {
419
                                        bandList.addBand(new DatasetBandImpl(lastRequest.getPath(), i, Buffer.TYPE_BYTE, 3));
420
                                } catch (BandNotFoundInListException e1) {
421
                                }
422
                        }
423
                        bandList.setDrawableBands(new int[]{0, 1, 2});*/
424

    
425
                        RasterQuery q = RasterLocator.getManager().createQuery();
426
                        q.setAreaOfInterest(lastRequestProvider.getExtent(),
427
                                        (int)lastRequestProvider.getWidth(),
428
                                        (int)lastRequestProvider.getHeight());
429
                        q.setAllDrawableBands();
430
                        q.setAdjustToExtent(true);
431

    
432
                        DefaultRasterStore store = new DefaultRasterStore();
433
                        store.setProvider(lastRequestProvider);
434
                        return store.query(q);
435
                } catch (ProviderNotRegisteredException e) {
436
                        throw new RasterDriverException("Error building GdalDriver", e);
437
                } catch (InitializeException e) {
438
                        throw new RasterDriverException("Error building GdalDriver", e);
439
                } catch (QueryException e) {
440
                        throw new RasterDriverException("Error reading data", e);
441
                }
442
        }
443

    
444
        /**
445
         * Opens the last request downloaded
446
         * @return
447
         * @throws ProviderNotRegisteredException
448
         * @throws InitializeException
449
         * @throws RasterDriverException
450
         */
451
        private AbstractRasterProvider openLastRequest() throws ProviderNotRegisteredException, InitializeException, RasterDriverException {
452
                if(lastRequestProvider != null)
453
                        lastRequestProvider.close();
454
                File lastFile = getFileLayer();
455
                lastRequestProvider = DefaultProviderServices.loadProvider(new File(lastFile.getPath()));
456
                return lastRequestProvider;
457
        }
458

    
459
        public Object getData(int x, int y, int band)
460
                        throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
461
                int w = 25;
462
                int h = 25;
463

    
464
                Point2D p1 = rasterToWorld(new Point2D.Double(x, y));
465
                Point2D p2 = rasterToWorld(new Point2D.Double(x + w, y + h));
466
                Rectangle2D bBox = new Rectangle2D.Double(p1.getX(), p1.getY(), Math.abs(p1.getX() - p2.getX()), Math.abs(p1.getY() - p2.getY()));
467

    
468
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
469
                WCSStatus wcsStatus = new WCSStatus();
470
                wcsStatus.setCoveraName(p.getCoverageName());
471
                wcsStatus.setSrs(p.getSRSCode());
472
                wcsStatus.setFormat(p.getFormat());
473
                wcsStatus.setOnlineResource(p.getOnlineResource() != null ? (String) p.getOnlineResource().get("GetCoverage") : null);
474
                wcsStatus.setExtent(bBox);
475
                wcsStatus.setHeight(h);
476
                wcsStatus.setWidth(w);
477
                wcsStatus.setDepth(p.getDepth());
478
                wcsStatus.setParameters(p.getParameter());
479
                wcsStatus.setTime(p.getTime());
480

    
481
                lastRequest = downloadFile(wcsStatus, p1.getX(), p1.getY(), p2.getX(), p2.getY(), w, h);
482

    
483
                AbstractRasterProvider driver = null;
484
                try {
485
                        driver = DefaultProviderServices.loadProvider(new File(lastRequest.getPath()));
486
                        /*Buffer buf = DefaultRasterManager.getInstance().createBuffer(getDataType()[0], w, h, getBandCount(), true);
487
                        BandList bandList = new BandListImpl();
488
                        int[] drawable = new int[getBandCount()];
489
                        for (int i = 0; i < getBandCount(); i++) {
490
                                try {
491
                                        bandList.addBand(new DatasetBandImpl(lastRequest.getPath(), i, getDataType()[i], getBandCount()));
492
                                        drawable[i] = i;
493
                                } catch (BandNotFoundInListException e1) {
494
                                }
495
                        }
496
                        bandList.setDrawableBands(drawable);*/
497

    
498
                        RasterQuery q = RasterLocator.getManager().createQuery();
499
                        Rectangle r = new Rectangle(0, 0, 25, 25);
500
                        q.setAreaOfInterest(r);
501
                        q.setAllDrawableBands();
502
                        DefaultRasterStore store = new DefaultRasterStore();
503
                        store.setProvider(driver);
504

    
505
                        Buffer buf = store.query(q);
506
                        driver.close();
507
                        if(buf.getDataType() == Buffer.TYPE_BYTE) {
508
                                return new Integer(buf.getElemByte(0, 0, band));
509
                        }
510
                        if(buf.getDataType() == Buffer.TYPE_SHORT) {
511
                                return new Integer(buf.getElemShort(0, 0, band));
512
                        }
513
                        if(buf.getDataType() == Buffer.TYPE_INT) {
514
                                return new Integer(buf.getElemInt(0, 0, band));
515
                        }
516
                        if(buf.getDataType() == Buffer.TYPE_FLOAT) {
517
                                return new Float(buf.getElemFloat(0, 0, band));
518
                        }
519
                        if(buf.getDataType() == Buffer.TYPE_DOUBLE) {
520
                                return new Double(buf.getElemDouble(0, 0, band));
521
                        }
522
                } catch(InitializeException e) {
523
                        throw new RasterDriverException("", e);
524
                } catch (ProviderNotRegisteredException e) {
525
                        throw new RasterDriverException("", e);
526
                } catch (ProcessInterruptedException e) {
527
                } catch (QueryException e) {
528
                        throw new RasterDriverException("", e);
529
                }
530
                return null;
531
        }
532

    
533
        /**
534
         * Gets the georeferencing file name form a raster file
535
         * @param file
536
         * a raster file
537
         * @return
538
         * a georeferencing file
539
         */
540
        private String getWorldFile(String file){
541
                String worldFile = file;
542
                int index = file.lastIndexOf(".");
543
                if (index > 0) {
544
                        worldFile = file.substring(0, index) + getExtensionWorldFile();
545
                } else {
546
                        worldFile = file + getExtensionWorldFile();
547
                }
548
                return worldFile;
549
        }
550

    
551
        /**
552
         * Obtiene la extensi?n del fichero de georreferenciaci?n
553
         * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
554
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
555
         */
556
        private String getExtensionWorldFile() {
557
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
558
                String extWorldFile = ".wld";
559
                if(p.getFormat().equals("image/tif") || p.getFormat().equals("image/tiff")) {
560
                        extWorldFile = ".tfw";
561
                }
562
                return extWorldFile;
563
        }
564

    
565
        private WCSStatus loadWCSStatus(Rectangle2D bBox) {
566
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
567
                WCSStatus wcsStatus = new WCSStatus();
568
                wcsStatus.setCoveraName(p.getCoverageName());
569
                wcsStatus.setSrs(p.getSRSCode());
570
                wcsStatus.setFormat(p.getFormat());
571
                wcsStatus.setOnlineResource(p.getOnlineResource() != null ? (String) p.getOnlineResource().get("GetCoverage") : null);
572
                wcsStatus.setExtent(bBox);
573
                wcsStatus.setHeight(p.getHeight());
574
                wcsStatus.setWidth(p.getWidth());
575
                wcsStatus.setDepth(p.getDepth());
576
                wcsStatus.setParameters(p.getParameter());
577
                wcsStatus.setTime(p.getTime());
578
                return wcsStatus;
579
        }
580

    
581
        public boolean needEnhanced() {
582
                return (getDataType()[0] != Buffer.TYPE_BYTE ||
583
                                (getBandCount() == 1 && getDataType()[0] == Buffer.TYPE_BYTE));
584
        }
585

    
586
        /**
587
         * This function downloads the file and creates the georeferencing file
588
         * @param wcsStatus
589
         * @param ulx
590
         * @param uly
591
         * @param lrx
592
         * @param lry
593
         * @param w
594
         * @param h
595
         * @return
596
         * @throws RasterDriverException
597
         */
598
        private File downloadFile(WCSStatus wcsStatus, double ulx, double uly, double lrx, double lry, int w, int h) throws RasterDriverException {
599
                Extent extent = new ExtentImpl(ulx, uly, lrx, lry);
600
                return downloadFile(wcsStatus, extent, w, h);
601
        }
602

    
603
        /**
604
         * This function downloads the file and creates the georeferencing file
605
         * @param wcsStatus
606
         * @param ulx
607
         * @param uly
608
         * @param lrx
609
         * @param lry
610
         * @param w
611
         * @param h
612
         * @return
613
         * @throws RasterDriverException
614
         */
615
        private File downloadFile(WCSStatus wcsStatus, Extent extent, int w, int h) throws RasterDriverException {
616
                try {
617
                        lastRequest = getConnector().getCoverage(wcsStatus, ((WCSDataParametersImpl)parameters).getCancellable());
618
                } catch (RemoteServiceException e) {
619
                        throw new RasterDriverException(e.getMessage(), e);
620
                }
621

    
622
                String nameWorldFile = getWorldFile(lastRequest.getPath());
623
                try {
624
                        fileUtil.createWorldFile(nameWorldFile, extent, w, h);
625
                } catch (IOException e) {
626
                        throw new RasterDriverException("Error downloading file", e);
627
                }
628

    
629
                return lastRequest;
630
        }
631

    
632
        /**
633
         * Assigns the list of bands RGB and read a window of data
634
         * @param rasterBuf
635
         * @param bandList
636
         * @param lastFile
637
         * @param ulx
638
         * @param uly
639
         * @param lrx
640
         * @param lry
641
         * @return
642
         * @throws RasterDriverException
643
         * @throws ProcessInterruptedException
644
         */
645
        public Buffer getBuffer(BandList bandList, File lastFile,
646
                        double ulx, double uly, double lrx, double lry) throws RasterDriverException, ProcessInterruptedException {
647
                try {
648
                        //El nombre de fichero que ha puesto en el bandList es el del servidor y no el del fichero en disco
649
                        /*String serverName = bandList.getBand(0).getFileName();
650
                        for (int i = 0; i < bandList.getBandCount(); i++) {
651
                                bandList.getBand(i).setFileName(lastFile.getPath());
652
                        }*/
653

    
654
                        AbstractRasterProvider driver = DefaultProviderServices.loadProvider(lastFile);
655

    
656
                        RasterQuery q = RasterLocator.getManager().createQuery();
657
                        q.setAreaOfInterest(new ExtentImpl(ulx, uly, lrx, lry));
658
                        q.setDrawableBands(bandList.getDrawableBands());
659
                        DefaultRasterStore store = new DefaultRasterStore();
660
                        store.setProvider(driver);
661
                        Buffer buf = store.query(q);
662

    
663
                        /*for (int i = 0; i < bandList.getBandCount(); i++) {
664
                                bandList.getBand(i).setFileName(serverName);
665
                        }*/
666

    
667
                        return buf;
668
                } catch (ProviderNotRegisteredException e) {
669
                        throw new RasterDriverException("Error building GdalDriver", e);
670
                } catch (InitializeException e) {
671
                        throw new RasterDriverException("Error building GdalDriver", e);
672
                } catch (QueryException e) {
673
                        throw new RasterDriverException("Error reading data", e);
674
                }
675
        }
676

    
677
        @Override
678
        public void loadBuffer(SpiRasterQuery query)
679
                        throws ProcessInterruptedException, RasterDriverException {
680
                Extent ex = query.getAdjustedRequestBoundingBox();
681
                WCSStatus wcsStatus = loadWCSStatus(ex.toRectangle2D());
682

    
683
                lastRequest = downloadFile(
684
                                wcsStatus,
685
                                ex,
686
                                query.getAdjustedBufWidth(),
687
                                query.getAdjustedBufHeight());
688

    
689
                if (lastRequest == null) {
690
                        return;
691
                }
692

    
693
                try {
694
                        AbstractRasterProvider driver = DefaultProviderServices.loadProvider(lastRequest);
695
                        DefaultRasterStore store = new DefaultRasterStore();
696
                        store.setProvider(driver);
697
                        query.createBuffer(store);
698
                        store.query((RasterQuery)query);
699
                } catch (ProviderNotRegisteredException e) {
700
                        throw new RasterDriverException("Error building GdalDriver", e);
701
                } catch (InitializeException e) {
702
                        throw new RasterDriverException("Error building GdalDriver", e);
703
                } catch (QueryException e) {
704
                        throw new RasterDriverException("Error reading data", e);
705
                }
706

    
707
        }
708

    
709
        /**
710
         * When a WCS provider is opened the information of data type and number of bands is not
711
         * available. Only after the first time a raster has been downloaded it can be know.
712
         * @param newDataType
713
         * @param buf
714
         * @param bandList
715
         * @return
716
         * @throws RasterDriverException
717
         */
718
        private void loadInitialInfo() throws RasterDriverException {
719
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
720
                Extent ext = getExtent();
721
                if(ext != null){
722
                        Rectangle2D bBox = ext.toRectangle2D();
723
                        int w = 0;
724
                        int h = 0;
725
                        if(ext.width() > ext.height()) {
726
                                w = 200;
727
                                h = (int)((ext.height() * w) / ext.width());
728
                        } else {
729
                                h = 200;
730
                                w = (int)((ext.width() * h) / ext.height());
731
                        }
732
                        p.setWidth(w);
733
                        p.setHeight(h);
734
                        p.setExtent(bBox);
735
                        WCSStatus wcsStatus = loadWCSStatus(bBox);
736

    
737
                        lastRequest = downloadFile(wcsStatus, ext.getULX(), ext.getULY(), ext.getLRX(), ext.getLRY(), w, h);
738
                        AbstractRasterProvider driver;
739
                        try {
740
                                driver = DefaultProviderServices.loadProvider(lastRequest);
741
                                setDataType(driver.getDataType());
742
                                bandCount = driver.getBandCount();
743
                                driver.close();
744
                        } catch (ProviderNotRegisteredException e) {
745
                                throw new RasterDriverException("", e);
746
                        } catch (InitializeException e) {
747
                                throw new RasterDriverException("", e);
748
                        }
749
                }
750
        }
751

    
752
        /**
753
         * When a WCS provider is opened the information of data type and number of bands is not
754
         * available. Only after the first time a raster has been downloaded it can be know.
755
         * @param newDataType
756
         * @param buf
757
         * @param bandList
758
         * @return
759
         */
760
        /*private Buffer changeBufferDataType(int newDataType, Buffer buf, BandList bandList) {
761
                Buffer newBuffer = null;
762
                if(buf.getDataType() != newDataType) {
763
                        newBuffer = DefaultRasterManager.getInstance().createReadOnlyBuffer(newDataType, buf.getWidth(), buf.getHeight(), buf.getBandCount());
764
                        buf.free();
765
                } else
766
                        return buf;
767

768
                bandList.clear();
769
                for(int i = 0; i < getBandCount(); i++)
770
                        try {
771
                                int dataType = getDataType()[i];
772
                                DatasetBand band = new DatasetBandImpl(getFName(), i, dataType, getBandCount());
773
                                bandList.addBand(band, i);
774
                        } catch(BandNotFoundInListException ex) {
775
                                //No a?adimos la banda
776
                        }
777
                return newBuffer;
778
        }*/
779

    
780
        /*public Buffer getWindow(int x, int y, int w, int h,
781
                        BandList bandList, Buffer rasterBuf, TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
782
                Point2D p1 = rasterToWorld(new Point2D.Double(x, y));
783
                Point2D p2 = rasterToWorld(new Point2D.Double(x + w, y + h));
784
                Rectangle2D bBox = new Rectangle2D.Double(p1.getX(), p1.getY(), Math.abs(p1.getX() - p2.getX()), Math.abs(p1.getY() - p2.getY()));
785
                WCSStatus wcsStatus = loadWCSStatus(bBox);
786

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

789
                if (lastRequest == null) {
790
                        return rasterBuf;
791
                }
792

793
                AbstractRasterProvider driver = null;
794
                try {
795
                        driver = DefaultProviderServices.loadProvider(new File(lastRequest.getPath()));
796

797
                        //El nombre de fichero que ha puesto en el bandList es el del servidor y no el del fichero en disco
798
                        String serverName = bandList.getBand(0).getFileName();
799
                        for (int i = 0; i < bandList.getBandCount(); i++) {
800
                                bandList.getBand(i).setFileName(lastRequest.getPath());
801
                        }
802

803
                        DefaultRasterQuery q = (DefaultRasterQuery)RasterLocator.getManager().createQuery();
804
                        q.setAreaOfInterest(0, 0, w, h);
805
                        q.setBandList(bandList);
806
                        q.setBuffer(rasterBuf);
807
                        Buffer buf = driver.getDataSet(q);
808

809
                        for (int i = 0; i < bandList.getBandCount(); i++) {
810
                                bandList.getBand(i).setFileName(serverName);
811
                        }
812
                        driver.close();
813
                        return buf;
814
                } catch (ProviderNotRegisteredException e) {
815
                        throw new RasterDriverException("Error building GdalDriver", e);
816
                } catch (InitializeException e) {
817
                        throw new RasterDriverException("Error building GdalDriver", e);
818
                }
819
        }*/
820

    
821
        public int getBlockSize() {
822
                return 0;
823
        }
824

    
825
        public void setAffineTransform(AffineTransform t){
826

    
827
        }
828

    
829
        public int getOverviewCount(int band) throws BandAccessException, RasterDriverException {
830
                return 0;
831
        }
832

    
833
        public int getOverviewWidth(int band, int overview) throws BandAccessException, RasterDriverException {
834
                return 0;
835
        }
836

    
837
        public int getOverviewHeight(int band, int overview) throws BandAccessException, RasterDriverException {
838
                return 0;
839
        }
840

    
841
        public boolean isOverviewsSupported() {
842
                return false;
843
        }
844

    
845
        public boolean isReproyectable() {
846
                return false;
847
        }
848

    
849
        public String getProviderName() {
850
                return NAME;
851
        }
852

    
853
        public String getName() {
854
                return this.getParameters().getCoverageName();
855
        }
856

    
857
        /**
858
         * Convierte un punto desde coordenadas pixel a coordenadas del mundo.
859
         * @param pt Punto a transformar
860
         * @return punto transformado en coordenadas del mundo
861
         */
862
        public Point2D rasterToWorld(Point2D pt) {
863
                Point2D p = new Point2D.Double();
864
                getAffineTransform().transform(pt, p);
865
                return p;
866
        }
867

    
868
        /**
869
         * Convierte un punto desde del mundo a coordenadas pixel.
870
         * @param pt Punto a transformar
871
         * @return punto transformado en coordenadas pixel
872
         */
873
        public Point2D worldToRaster(Point2D pt) {
874
                Point2D p = new Point2D.Double();
875
                try {
876
                        getAffineTransform().inverseTransform(pt, p);
877
                } catch (NoninvertibleTransformException e) {
878
                        return pt;
879
                }
880
                return p;
881
        }
882

    
883
        public void setStatus(RasterProvider provider) {
884
                if(provider instanceof WCSProvider) {
885
                }
886
        }
887

    
888
        /**
889
         * ASigna el par?metro de inicializaci?n del driver.
890
         */
891
        public void setParam(DataStoreProviderServices storeServices, DataStoreParameters param) {
892
                if(param instanceof WCSDataParametersImpl)
893
                        this.uri = ((WCSDataParametersImpl)param).getURI();
894
                this.param = param;
895
        }
896

    
897
        /**
898
         * Gets the suffix of the downloaded image
899
         * @return
900
         */
901
        public String getFileSuffix() {
902
                WCSDataParametersImpl p = (WCSDataParametersImpl)parameters;
903
                String format = p.getFormat().toLowerCase();
904
                if (format == null) {
905
                        return "xml";
906
                }
907
                if (format.indexOf("png") >= 0){
908
                        return "png";
909
                }
910
                if (format.indexOf("xml") >= 0){
911
                        return "xml";
912
                }
913
                if (format.indexOf("gif") >= 0){
914
                        return "gif";
915
                }
916
                if (format.indexOf("tif") >= 0){
917
                        return "tif";
918
                }
919
                if (format.indexOf("bmp") >= 0){
920
                        return "bmp";
921
                }
922
                if (format.indexOf("jpg") >= 0
923
                                || format.indexOf("jpeg") >= 0){
924
                        return "jpg";
925
                }
926
                return "xml";
927
        }
928

    
929
        public TileServer getTileServer() {
930
                if(tileServer == null) {
931
                        DefaultRasterStore store = new DefaultRasterStore();
932
                        store.setProvider(this);
933
                        tileServer = new WCSTileServer(store);
934
                }
935
                return tileServer;
936
        }
937

    
938
        public boolean isRasterEnclosed() {
939
                return true;
940
        }
941

    
942
        public File getRMFFile() {
943
                if(lastRequest != null)
944
                        return new File(FilenameUtils.removeExtension(lastRequest.getAbsolutePath()) + ".rmf");
945
                return null;
946
        }
947

    
948
        public HistogramComputer getHistogramComputer() {
949
                if (histogram == null)
950
                        histogram = new RemoteStoreHistogram(this);
951
                return histogram;
952
        }
953

    
954
    /* (non-Javadoc)
955
     * @see org.gvsig.raster.impl.provider.RasterProvider#addFile(java.io.File)
956
     */
957
    @Override
958
    public void addFile(File file) throws InvalidSourceException {
959
        // Do nothing
960

    
961
    }
962

    
963
    /* (non-Javadoc)
964
     * @see org.gvsig.raster.impl.provider.RasterProvider#removeFile(java.io.File)
965
     */
966
    @Override
967
    public void removeFile(File file) {
968
        // Do nothing
969

    
970
    }
971

    
972
}