Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extWCS / src / com / iver / cit / gvsig / fmap / layers / FLyrWCS.java @ 8218

History | View | Annotate | Download (29.4 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package com.iver.cit.gvsig.fmap.layers;
42

    
43
import java.awt.Component;
44
import java.awt.Dimension;
45
import java.awt.Graphics2D;
46
import java.awt.Point;
47
import java.awt.Rectangle;
48
import java.awt.geom.AffineTransform;
49
import java.awt.geom.NoninvertibleTransformException;
50
import java.awt.geom.Point2D;
51
import java.awt.geom.Rectangle2D;
52
import java.awt.image.BufferedImage;
53
import java.awt.image.DataBuffer;
54
import java.io.File;
55
import java.io.IOException;
56
import java.lang.reflect.Constructor;
57
import java.lang.reflect.InvocationTargetException;
58
import java.net.MalformedURLException;
59
import java.net.URL;
60
import java.util.ArrayList;
61
import java.util.Hashtable;
62
import java.util.Map;
63

    
64
import javax.swing.JOptionPane;
65

    
66
import org.cresques.filter.RasterFilterStack;
67
import org.cresques.filter.RasterFilterStackManager;
68
import org.cresques.geo.ViewPortData;
69
import org.cresques.io.GdalFile;
70
import org.cresques.io.GeoRasterFile;
71
import org.cresques.px.Extent;
72
import org.cresques.px.PxRaster;
73
import org.exolab.castor.xml.ValidationException;
74
import org.gvsig.remoteClient.wcs.WCSStatus;
75
import org.gvsig.remoteClient.wms.ICancellable;
76

    
77
import com.iver.andami.PluginServices;
78
import com.iver.cit.gvsig.fmap.ConnectionErrorExceptionType;
79
import com.iver.cit.gvsig.fmap.DriverException;
80
import com.iver.cit.gvsig.fmap.UnknownResponseFormatExceptionType;
81
import com.iver.cit.gvsig.fmap.UnsuportedProtocolVersionExceptionType;
82
import com.iver.cit.gvsig.fmap.ViewPort;
83
import com.iver.cit.gvsig.fmap.WCSDriverExceptionType;
84
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
85
import com.iver.cit.gvsig.fmap.drivers.UnsupportedVersionException;
86
import com.iver.cit.gvsig.fmap.drivers.wcs.FMapWCSDriver;
87
import com.iver.cit.gvsig.fmap.drivers.wcs.FMapWCSDriverFactory;
88
import com.iver.cit.gvsig.fmap.drivers.wcs.WCSException;
89
import com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint;
90
import com.iver.cit.gvsig.fmap.layers.layerOperations.StringXMLItem;
91
import com.iver.cit.gvsig.fmap.layers.layerOperations.XMLItem;
92
import com.iver.utiles.StringUtilities;
93
import com.iver.utiles.XMLEntity;
94
import com.iver.utiles.swing.threads.Cancellable;
95

    
96

    
97
/**
98
 * Class for the WCS layer.
99
 *
100
 * Capa para el WCS.
101
 *
102
 * @author jaume - jaume.dominguez@iver.es
103
 */
104
public class FLyrWCS extends FLyrDefault implements RasterOperations, InfoByPoint{
105
        private FMapWCSDriver wcs = null;
106

    
107
        private URL                                                 host;
108
        private String                                                coverageName;
109
        private Rectangle2D                                        fullExtent;
110
        private String                                                format;
111
        private String                                                srs;
112
        private String                                                time;
113
        private String                                                parameter;
114
        private Point2D                                                maxRes;
115
        private Hashtable                                         onlineResources = new Hashtable();
116

    
117
        private WCSStatus                                        wcsStatus = new WCSStatus();
118

    
119
        private StatusRasterInterface                status = null;
120
        private int                                                 posX = 0, posY = 0;
121
        private double                                                 posXWC = 0, posYWC = 0;
122
        private int                                                 r = 0, g = 0, b = 0;
123
        private RasterFilterStackManager        stackManager = null;
124
        private PxRaster                                         raster = null;
125
        private GeoRasterFile                                 rasterFile = null;
126
        private RasterFilterStack                         filterStack;
127
        private boolean                                         firstLoad = false;
128
        private int                                                 transparency = -1;
129
        private int                                                        rband = 0, gband = 1, bband = 2;
130
        private VisualStatus                                visualStatus = new VisualStatus();
131

    
132
        private boolean                                         mustTileDraw = false;
133
        private int                                                 maxTileDrawWidth  = 1023;
134
        private int                                                        maxTileDrawHeight = 1023;
135
        private int                                                 maxTilePrintWidth  = 250;
136
        private int                                                        maxTilePrintHeight = 250;
137

    
138
        private FMapWCSDriver driver;
139

    
140
        private class MyCancellable implements ICancellable
141
        {
142

    
143
                private Cancellable original;
144
                public MyCancellable(Cancellable cancelOriginal)
145
                {
146
                        this.original = cancelOriginal;
147
                }
148
                public boolean isCanceled() {
149
                        return original.isCanceled();
150
                }
151

    
152
        }
153
        public FLyrWCS(){
154
                super();
155
        }
156

    
157
        public FLyrWCS(Map args) throws DriverIOException{
158
                FMapWCSDriver drv = null;
159
                String host = (String)args.get("HOST");
160
                String sCoverage = (String) args.get((String) "COVERAGE");
161

    
162
                try {
163
                        this.setHost(new URL(host));
164
                } catch (MalformedURLException e) {
165
                        //e.printStackTrace();
166
                        throw new DriverIOException("Malformed host URL, '" + host + "' (" + e.toString() + ").");
167
                }
168
                try {
169
                        drv = this.getDriver();
170
                } catch (Exception e) {
171
                        // e.printStackTrace();
172
                        throw new DriverIOException("Can't get driver to host '" + host + "' (" + e.toString() + ").");
173
                }
174

    
175
                try{
176
                        if (!drv.connect(null)){
177
                                throw new DriverIOException("Can't connect to host '" + host + "'.");
178
                        }
179
                }catch(Exception e){
180
                        throw new DriverIOException("Can't connect to host '" + host + "'.");
181
                }
182

    
183
                WCSLayer wcsNode = drv.getLayer(sCoverage);
184

    
185
                if (wcsNode == null){
186
                        throw new DriverIOException("The server '" + host + "' doesn't has the coverage '" + sCoverage + "'.");
187
                }
188

    
189
                try{
190
                        this.setFullExtent(drv.getFullExtent(sCoverage,
191
                                        (String) args.get((String) "CRS")));
192
                        this.setFormat((String) args.get((String) "FORMAT"));
193
                        this.setParameter("BANDS=" + (String) args.get((String) "BANDS"));
194
                        this.setSRS((String) args.get((String) "CRS"));
195
                        this.setName(sCoverage);
196
                        this.setCoverageName(sCoverage);
197
                }catch (Exception e){
198
                        throw new DriverIOException("The server '" + host + "' is not able to load the coverage '" + sCoverage + "'.");
199
                }
200

    
201
        }
202

    
203
        /**
204
         * Clase que contiene los datos de visualizaci?n de WMS.
205
         * @author Nacho Brodin (brodin_ign@gva.es)
206
         */
207
        private class VisualStatus {
208
                /**
209
                 * Ancho y alto de la imagen o del conjunto de tiles si los tiene. Coincide con
210
                 * el ancho y alto del viewPort
211
                 */
212
                private        int                                                        width = 0, height = 0;
213
                private double                                                minX = 0D, minY = 0D, maxX = 0D, maxY = 0D;
214
                private int                                                 bandCount = 0;
215
                private int                                                        dataType = DataBuffer.TYPE_UNDEFINED;
216
        }
217

    
218
        /*
219
         *  (non-Javadoc)
220
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setRGB(int, int, int)
221
         */
222
        public void setRGB(int r, int g, int b) {
223
                this.r = r;
224
                this.g = g;
225
                this.b = b;
226
        }
227

    
228
        /*
229
         *  (non-Javadoc)
230
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getFilterStack()
231
         */
232
        public RasterFilterStack getFilterStack() {
233
                if(raster!=null)
234
                        return raster.filterStack;
235
                return null;
236
        }
237

    
238
        /*
239
         *  (non-Javadoc)
240
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setFilterStack(org.cresques.io.raster.RasterFilterStack)
241
         */
242
        public void setFilterStack(RasterFilterStack stack) {
243
                this.filterStack = stack;
244
        }
245

    
246
        /*
247
         *  (non-Javadoc)
248
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getSource()
249
         */
250
        public RasterAdapter getSource() {
251
                return null;
252
        }
253

    
254
        /*
255
         *  (non-Javadoc)
256
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setSource(com.iver.cit.gvsig.fmap.layers.RasterAdapter)
257
         */
258
        public void setSource(RasterAdapter ra) {
259
        }
260

    
261
        /*
262
         *  (non-Javadoc)
263
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPos(int, int)
264
         */
265
        public void setPos(int x, int y) {
266
                this.posX = x;
267
                this.posY = y;
268
        }
269

    
270
        /*
271
         *  (non-Javadoc)
272
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPosWC(double, double)
273
         */
274
        public void setPosWC(double x, double y) {
275
                this.posXWC = x;
276
                this.posYWC = y;
277
        }
278

    
279
        /*
280
         *  (non-Javadoc)
281
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getPixel(double, double)
282
         */
283
        public int[] getPixel(double wcx, double wcy) {
284
                if(getPxRaster() != null)
285
                        return getPxRaster().getPixel(wcx, wcy);
286
        return null;
287
        }
288

    
289
        /*
290
         *  (non-Javadoc)
291
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setBand(int, int)
292
         */
293
        public void setBand(int flag, int nBand) {
294
                switch(flag){
295
                case GeoRasterFile.RED_BAND:setBandR(nBand);break;
296
                case GeoRasterFile.GREEN_BAND:setBandG(nBand);break;
297
                case GeoRasterFile.BLUE_BAND:setBandB(nBand);break;
298
                }
299
        }
300

    
301
        /**
302
         * Sets the R-band.
303
         *
304
         * Asigna la banda R.
305
         * @param r
306
         */
307
        public void setBandR(int r){
308
                this.rband = r;
309
        }
310

    
311
        /**
312
         * Sets the G-band.
313
         *
314
         * Asigna la banda G
315
         * @param g
316
         */
317
        public void setBandG(int g){
318
                this.gband = g;
319
        }
320

    
321
        /**
322
         * Sets the B-band.
323
         *
324
         * Asigna la banda B
325
         * @param b
326
         */
327
        public void setBandB(int b){
328
                this.bband = b;
329
        }
330

    
331
        /*
332
         *  (non-Javadoc)
333
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getAttributes()
334
         */
335
        public ArrayList getAttributes() {
336
                if (rasterFile != null){
337
                        ArrayList attr = new ArrayList();
338
                        String dataType = "Byte";
339
                        if (rasterFile.getDataType() == DataBuffer.TYPE_BYTE) dataType = "Byte";
340
                        else if (visualStatus.dataType == DataBuffer.TYPE_SHORT)
341
                                dataType = "Short";
342
                        else if (visualStatus.dataType == DataBuffer.TYPE_USHORT)
343
                                dataType = "Unsigned Short";
344
                        else if (visualStatus.dataType == DataBuffer.TYPE_INT)
345
                                dataType = "Integer";
346
                        else if (visualStatus.dataType == DataBuffer.TYPE_FLOAT)
347
                                dataType = "Float";
348
                        else if (visualStatus.dataType == DataBuffer.TYPE_DOUBLE)
349
                                dataType = "Double";
350
                        else
351
                                dataType = "Unknown";
352

    
353
                        Object [][] a = {
354
                                {"Filename",rasterFile.getName().substring(rasterFile.getName().lastIndexOf("/")+1, rasterFile.getName().length())},
355
                                {"Filesize",new Long(0)},
356
                                {"Width",new Integer((int)this.getWidth())},
357
                                {"Height", new Integer((int)this.getHeight())},
358
                                {"Bands", new Integer(visualStatus.bandCount)},
359
                                {"BandDataType", dataType}
360
                        };
361
                        for (int i=0; i<a.length; i++)
362
                                attr.add(a[i]);
363

    
364
                        return attr;
365
                }
366
                return  null;
367
        }
368

    
369
        /*
370
         *  (non-Javadoc)
371
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxX()
372
         */
373
        public double getMaxX() {
374
                return visualStatus.maxX;
375
        }
376

    
377
        /*
378
         *  (non-Javadoc)
379
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxY()
380
         */
381
        public double getMaxY() {
382
                return visualStatus.maxY;
383
        }
384

    
385
        /*
386
         *  (non-Javadoc)
387
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinX()
388
         */
389
        public double getMinX() {
390
                return visualStatus.minX;
391
        }
392

    
393
        /*
394
         *  (non-Javadoc)
395
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinY()
396
         */
397
        public double getMinY() {
398
                return visualStatus.minY;
399
        }
400

    
401
        /*
402
         *  (non-Javadoc)
403
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getWidth()
404
         */
405
        public double getWidth() {
406
                return visualStatus.width;
407
        }
408

    
409
        /*
410
         *  (non-Javadoc)
411
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getHeight()
412
         */
413
        public double getHeight() {
414
                return visualStatus.height;
415
        }
416

    
417
        /**
418
         * @deprecated
419
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#getInfo
420
         */
421
        public String queryByPoint(Point p) throws DriverException {
422
                String data = "<file:"+getName().replaceAll("[^a-zA-Z0-9]","")+">\n";
423
                ArrayList attr = this.getAttributes();
424
                data += "  <raster\n";
425
                data += "    File=\""+getName()+"\"\n";
426
                for (int i=0; i<attr.size(); i++) {
427
                        Object [] a = (Object []) attr.get(i);
428

    
429
                        data += "    "+a[0].toString()+"=";
430
                        if (a[1].toString() instanceof String)
431
                                data += "\""+a[1].toString()+"\"\n";
432
                        else
433
                                data += a[1].toString()+"\n";
434
                }
435
                data += "    Point=\""+posX+" , "+posY+"\"\n";
436
                data += "    Point_WC=\""+posXWC+" , "+posYWC+"\"\n";
437
                data += "    RGB=\""+r+", "+g+", "+b+"\"\n";
438
                data += "  />\n";
439

    
440
                data += "</file:"+getName().replaceAll("[^a-zA-Z0-9]","")+">\n";
441
                System.out.println(data);
442
                return data;
443
        }
444
        /**
445
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#getInfo
446
         */
447
        public XMLItem[] getInfo(Point point, double tolerance ) throws DriverException {
448
                String data = "<file:"+getName().replaceAll("[^a-zA-Z0-9]","")+">\n";
449
                ArrayList attr = this.getAttributes();
450
                data += "  <raster\n";
451
                data += "    File=\""+getName()+"\"\n";
452
                for (int i=0; i<attr.size(); i++) {
453
                        Object [] a = (Object []) attr.get(i);
454

    
455
                        data += "    "+a[0].toString()+"=";
456
                        if (a[1].toString() instanceof String)
457
                                data += "\""+a[1].toString()+"\"\n";
458
                        else
459
                                data += a[1].toString()+"\n";
460
                }
461
                data += "    Point=\""+posX+" , "+posY+"\"\n";
462
                data += "    Point_WC=\""+posXWC+" , "+posYWC+"\"\n";
463
                data += "    RGB=\""+r+", "+g+", "+b+"\"\n";
464
                data += "  />\n";
465

    
466
                data += "</file:"+getName().replaceAll("[^a-zA-Z0-9]","")+">\n";
467
                System.out.println(data);
468

    
469
                //return data;
470
                XMLItem[] item =  new XMLItem[1];
471
                item[0]= new StringXMLItem(data, this);
472
                return item;
473
        }
474

    
475
        /*
476
         *  (non-Javadoc)
477
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent()
478
         */
479
        public Rectangle2D getFullExtent() {
480
                return fullExtent;
481
        }
482

    
483
        /*
484
         *  (non-Javadoc)
485
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#draw(java.awt.image.BufferedImage, java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort, com.iver.cit.gvsig.fmap.operations.Cancellable, double)
486
         */
487
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale) throws DriverException {
488

    
489
                if (isWithinScale(scale)){
490
                        Point2D p = viewPort.getOffset();
491
                        // p will be (0, 0) when drawing a view or other when painting onto
492
                        // the Layout.
493
                        visualStatus.width =  viewPort.getImageWidth();
494
                        visualStatus.height =  viewPort.getImageHeight();
495
                        visualStatus.minX = viewPort.getAdjustedExtent().getMinX();
496
                        visualStatus.minY = viewPort.getAdjustedExtent().getMinY();
497
                        visualStatus.maxX = viewPort.getAdjustedExtent().getMaxX();
498
                        visualStatus.maxY = viewPort.getAdjustedExtent().getMaxY();
499

    
500
                        if(mustTileDraw){
501
                                if(viewPort.getImageWidth()<= maxTileDrawWidth && viewPort.getImageHeight()<=maxTileDrawHeight)
502
                                        drawTile(g, viewPort, cancel);
503
                                else{
504
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), viewPort.getImageWidth(), viewPort.getImageHeight());
505
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
506
                                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
507
                                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
508
                                                // drawing part
509
                                                try {
510
                                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
511
                                                        drawTile(g, vp, cancel);
512
                                                } catch (NoninvertibleTransformException e) {
513
                                                        e.printStackTrace();
514
                                                }
515
                                        }
516
                                }
517
                        }else
518
                                drawTile(g, viewPort, cancel);
519
                }
520
                Runtime r = Runtime.getRuntime();
521
                long mem = r.totalMemory() - r.freeMemory();
522
                System.err.println("Memoria total: " + (mem / 1024) +"KB");
523
        }
524

    
525
        /**
526
         * This is the method used to draw a tile in a WMS mosaic layer.
527
         */
528
        private void drawTile(Graphics2D g, ViewPort vp, Cancellable cancel) throws DriverException {
529

    
530
                // Compute the query geometry
531
                // 1. Check if it is within borders
532
                Rectangle2D extent = getFullExtent();
533
        if ((vp.getAdjustedExtent().getMinX() > extent.getMaxX()) ||
534
                (vp.getAdjustedExtent().getMinY() > extent.getMaxY()) ||
535
                (vp.getAdjustedExtent().getMaxX() < extent.getMinX()) ||
536
                (vp.getAdjustedExtent().getMaxY() < extent.getMinY())) {
537
            return;
538
        }
539

    
540
        // 2. Compute extent to be requested.
541
        Rectangle2D bBox = new Rectangle2D.Double();
542
        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
543

    
544
        // 3. Compute size in pixels
545
        double scalex = vp.getAffineTransform().getScaleX();
546
        double scaley = vp.getAffineTransform().getScaleY();
547
        int wImg = (int) Math.ceil(Math.abs(bBox.getWidth() * scalex) + 1);
548
        int hImg = (int) Math.ceil(Math.abs(bBox.getHeight() * scaley) + 1);
549
        Dimension sz = new Dimension(wImg, hImg);
550

    
551
        if ((wImg <= 0) || (hImg <= 0)) {
552
            return;
553
        }
554

    
555
                try {
556
                        wcsStatus.setCoveraName( coverageName );
557
                        wcsStatus.setExtent( bBox );
558
                        wcsStatus.setFormat( format );
559
                        wcsStatus.setHeight( hImg );
560
                        wcsStatus.setWidth( wImg );
561
                        wcsStatus.setSrs(srs);
562
                        wcsStatus.setParameters( parameter );
563
                        wcsStatus.setTime( time );
564
                        wcsStatus.setOnlineResource((String) onlineResources.get("GetCoverage"));
565

    
566
                        File f = getDriver().getCoverage(wcsStatus, new MyCancellable(cancel));
567
                        if (f == null)
568
                                return;
569
                        String nameWordFile = f.getPath() + getExtensionWorldFile();
570
                        com.iver.andami.Utilities.createTemp(nameWordFile, this.getDataWorldFile(bBox, sz));
571

    
572
                        if(status!=null && firstLoad){
573
                                status.applyStatus(this);
574
                                firstLoad = false;
575
                        }
576
                        ViewPortData vpData = new ViewPortData(
577
                                vp.getProjection(), new Extent(bBox), sz );
578
                        vpData.setMat(vp.getAffineTransform());
579

    
580
                        rasterProcess(g, vpData, f);
581

    
582
                } catch (ValidationException e) {
583
                        UnknownResponseFormatExceptionType type = 
584
                                new UnknownResponseFormatExceptionType();
585
                        type.setLayerName(getName());
586
                        try {
587
                                type.setDriverName(getDriver().getName());
588
                        } catch (Exception e1) {
589
                                e1.printStackTrace();
590
                        }
591
                        type.setFormat(format);
592
                        type.setHost(host);
593
                        type.setProtocol("WCS");
594
                        DriverException exception = new DriverException("unknown_response_format", type);
595
                        throw exception;
596
//        azabala                throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
597
                }
598
                catch (UnsupportedVersionException e) {
599
                        UnsuportedProtocolVersionExceptionType type = 
600
                                new UnsuportedProtocolVersionExceptionType();
601
                        type.setLayerName(getName());
602
                        try {
603
                                type.setDriverName(getDriver().getName());
604
                        } catch (Exception ex){        
605
                        }
606
                        type.setUrl(host);
607
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e, type);
608
                        
609
//        azabala                throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
610
                } catch (IOException e) {
611
                        ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
612
                        type.setLayerName(getName());
613
                        try {
614
                                type.setDriverName(getDriver().getName());
615
                        } catch (Exception e1) {
616
                        } 
617
                        type.setHost(host);
618
                        throw new DriverException(PluginServices.
619
                                        getText(this, "connect_error"), e, type);
620
                } catch (WCSException e) {
621
//azabala: la capturamos y la convertimos en DriverException
622
                        WCSDriverExceptionType type = new WCSDriverExceptionType();
623
                        type.setLayerName(getName());
624
                        try {
625
                                type.setDriverName(getDriver().getName());
626
                        } catch (Exception e1) {
627
                        } 
628
                        type.setWcsStatus(wcsStatus);
629
                        this.setVisible(false);
630
                        throw new DriverException("Error WCS", e,  type);
631
                        
632
//            JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
633
            
634
        }//catch
635
        }
636

    
637
        /**
638
         * Devuelve el FMapWMSDriver.
639
         *
640
         * @return FMapWMSDriver
641
         *
642
         * @throws IllegalStateException
643
         * @throws ValidationException
644
         * @throws UnsupportedVersionException
645
         * @throws IOException
646
         */
647
        private FMapWCSDriver getDriver() throws IllegalStateException, ValidationException, UnsupportedVersionException, IOException {
648
                if (wcs == null) {
649
                        wcs = FMapWCSDriverFactory.getFMapDriverForURL(host);
650
                }
651
                return wcs;
652
        }
653

    
654
        /**
655
         * Calcula el contenido del fichero de georreferenciaci?n de una imagen.
656
         * @param bBox Tama?o y posici?n de la imagen (en coordenadas de usuario)
657
         * @param sz Tama?o de la imagen en pixeles.
658
         * @return el 'WorldFile', como String.
659
         * @throws IOException
660
         */
661
        public String getDataWorldFile(Rectangle2D bBox, Dimension sz) throws IOException {
662
                StringBuffer data = new StringBuffer();
663
            data.append((bBox.getMaxX() - bBox.getMinX())/(sz.getWidth() - 1)+"\n");
664
            data.append("0.0\n");
665
            data.append("0.0\n");
666
            data.append((bBox.getMaxY() - bBox.getMinY())/(sz.getHeight() - 1)+"\n");
667
            data.append(""+bBox.getMinX()+"\n");
668
            data.append(""+bBox.getMinY()+"\n");
669
            return data.toString();
670
        }
671

    
672
        /**
673
         * Dibuja una imagen usando PxRaster
674
         * @param g        Graphics2D en el que hay que dibujar.
675
         * @param vpData Par?metros de visualizaci?n
676
         * @param file La imagen en cuesti?n.
677
         */
678
        private void rasterProcess(Graphics2D g, ViewPortData vpData, File file) {
679

    
680
                //Creamos el PxRaster
681
                rasterFile = new GdalFile(vpData.getProjection(), file.getAbsolutePath());
682
                raster = new PxRaster(rasterFile, null, rasterFile.getExtent());
683

    
684
                //Recuperamos la pila de filtros si ya hubiese sido cargado antes
685
                if (this.filterStack!=null)
686
                        raster.filterStack = this.filterStack;
687

    
688
                raster.setTransparency(false);
689

    
690
                //Asignamos transparencia y orden de bandas
691
                if (this.transparency==-1 && !firstLoad);
692
                else
693
                        raster.setTransparency(this.transparency);
694

    
695
                raster.setBand(GeoRasterFile.RED_BAND,rband);
696
                raster.setBand(GeoRasterFile.GREEN_BAND, gband);
697
                raster.setBand(GeoRasterFile.BLUE_BAND, bband);
698

    
699
                //Despues del primer pxRaster asignamos el stackManager guardado para los siguientes.
700
                //Con esto conseguimos asignar los cambios que se hayan producido desde el cuadro de
701
                //propiedades cuando creamos un nuevo pxRaster
702
                if (this.stackManager != null)
703
                        raster.setStackManager(this.stackManager);
704

    
705
                if (visualStatus != null){
706
                        visualStatus.bandCount = raster.getBandCount();
707
                        visualStatus.dataType = raster.getDataType();
708
                }
709

    
710
                raster.draw(g, vpData);
711

    
712
                //En el primer pxRaster de una imagen obtenemos el Stack Manager para poder modificarlo
713
                //si queremos desde las propiedades
714

    
715
                if (this.stackManager == null)
716
                        this.stackManager = raster.getStackManager();
717

    
718
                if (this.filterStack == null)
719
                        this.filterStack = raster.filterStack;
720

    
721
                rasterFile.close();
722
        }
723

    
724
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale) throws DriverException {
725
                draw(null, g, viewPort, cancel, scale);
726
        }
727

    
728
        /**
729
         * @return Returns the raster.
730
         */
731
        public PxRaster getPxRaster() {
732
                return raster;
733
        }
734

    
735
        /**
736
         * Returns the XMLEntity containing the necessary info for reproduce
737
         * the layer.
738
         *
739
         * Devuelve el XMLEntity con la informaci?n necesaria para reproducir
740
         * la capa.
741
         *
742
         * @return XMLEntity.
743
         * @throws XMLException
744
         */
745
        public XMLEntity getXMLEntity() throws XMLException {
746
                XMLEntity xml = super.getXMLEntity();
747

    
748
                xml.putProperty("wcs.host", getHost());
749
                xml.putProperty("wcs.fullExtent", StringUtilities.rect2String( fullExtent ));
750
                xml.putProperty("wcs.layerQuery", coverageName );
751
                xml.putProperty("wcs.format", format );
752
                xml.putProperty("wcs.srs", srs );
753
                xml.putProperty("wcs.time", time );
754
                xml.putProperty("wcs.parameter", parameter );
755
                xml.putProperty("wcs.coverageName", coverageName );
756
                xml.putProperty("wcs.maxResX", maxRes.getX());
757
                xml.putProperty("wcs.maxResY", maxRes.getY());
758
                if (status!=null)
759
                        status.getXMLEntity(xml, true, this);
760
                else{
761
                        status = new StatusLayerRaster();
762
                        status.getXMLEntity(xml, true, this);
763
                }
764
                return xml;
765
        }
766

    
767
        /**
768
         * Reproduces the layer from an XMLEntity.
769
         *
770
         * A partir del XMLEntity reproduce la capa.
771
         *
772
          * @param xml XMLEntity
773
         *
774
         * @throws XMLException
775
         * @throws DriverException
776
         * @throws DriverIOException
777
         */
778
        public void setXMLEntity(XMLEntity xml) throws XMLException {
779
                super.setXMLEntity(xml);
780

    
781
                // host
782
                try {
783
                        host = new URL(xml.getStringProperty("wcs.host"));
784
                } catch (MalformedURLException e) {
785
                        throw new XMLException(e);
786
                }
787

    
788
                // full extent
789
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty("wcs.fullExtent"));
790

    
791
                // coverageQuery
792
                coverageName = xml.getStringProperty("wcs.layerQuery");
793

    
794
                // format
795
                format = xml.getStringProperty("wcs.format");
796

    
797
                // srs
798
                srs = xml.getStringProperty("wcs.srs");
799

    
800
                // time
801
                time = xml.getStringProperty("wcs.time");
802

    
803
                // parameter
804
                parameter = xml.getStringProperty("wcs.parameter");
805

    
806
                // coverage name
807
                coverageName = xml.getStringProperty("wcs.coverageName");
808

    
809
                // max resolution
810
                if (xml.contains("wcs.maxRes"))
811
                        maxRes = new Point2D.Double(xml.getDoubleProperty("wcs.maxRes"), xml.getDoubleProperty("wcs.maxRes"));
812
                else if (xml.contains("wcs.maxResX") && xml.contains("wcs.maxResY"))
813
                        maxRes = new Point2D.Double(xml.getDoubleProperty("wcs.maxResX"), xml.getDoubleProperty("wcs.maxResY"));
814

    
815
                // OnlineResources
816
        if (xml.contains("onlineResources")) {
817
                String[] operations = xml.getStringProperty("onlineResources").split("~##SEP1##~");
818
                for (int i = 0; i < operations.length; i++) {
819
                                String[] resources = operations[i].split("~##SEP2##~");
820
                                if (resources.length==2 && resources[1]!="")
821
                                        onlineResources.put(resources[0], resources[1]);
822
                        }
823
        }
824
                String claseStr = null;
825
                if (xml.contains("raster.class")) {
826
                        claseStr = xml.getStringProperty("raster.class");
827
                }
828
                if (status!=null)
829
                        status.setXMLEntity(xml, this);
830
                else {
831
                        //Cuando cargamos un proyecto
832

    
833
                        if(claseStr!=null && !claseStr.equals("")){
834
                                try{
835
                                        Class clase = Class.forName(claseStr);
836
                                        Constructor constr = clase.getConstructor(null);
837
                                        status = (StatusRasterInterface)constr.newInstance(null);
838
                                        if(status!=null)
839
                                                status.setXMLEntity(xml, this);
840
                                } catch(ClassNotFoundException exc) {
841
                                        exc.printStackTrace();
842
                                } catch(InstantiationException exc) {
843
                                        exc.printStackTrace();
844
                                } catch(IllegalAccessException exc) {
845
                                        exc.printStackTrace();
846
                                } catch(NoSuchMethodException exc) {
847
                                        exc.printStackTrace();
848
                                } catch(InvocationTargetException exc) {
849
                                        exc.printStackTrace();
850
                                }
851
                        }
852
                }
853
                firstLoad = true;
854
        }
855

    
856
        public void setCoverageName(String coverageName) {
857
                this.coverageName = coverageName;
858
        }
859

    
860
        public void setParameter(String parametersString) {
861
                this.parameter = parametersString;
862
        }
863

    
864
        public void setTime(String time) {
865
                this.time = time;
866
        }
867

    
868
        public void setSRS(String srs) {
869
                this.srs = srs;
870
        }
871

    
872
        public void setFormat(String format) {
873
                this.format = format;
874
        }
875

    
876

    
877
        /**
878
         * Inserta el URL.
879
         *
880
         * @param host String.
881
         * @throws MalformedURLException
882
         */
883
        public void setHost(String host) {
884
                try {
885
                        setHost(new URL(host));
886
                } catch (MalformedURLException e) {
887

    
888
                }
889
        }
890

    
891
        /**
892
         * Inserta el URL.
893
         *
894
         * @param host URL.
895
         */
896
        public void setHost(URL host) {
897
                this.host = host;
898
        }
899

    
900
        /**
901
         * Sets the layer's full extent.
902
         *
903
         * Establece la extensi?n m?xima de la capa.
904
         *
905
         * @param rect
906
         */
907
        public void setFullExtent(Rectangle2D rect) {
908
                this.fullExtent = rect;
909
        }
910

    
911
        /**
912
         * Devuelve el URL.
913
         *
914
         * @return URL.
915
         */
916
        public URL getHost() {
917
                return host;
918
        }
919

    
920
        /**
921
         * Remote source layers have a bunch of properties that are required for get them from
922
         * the servers. This method supplies a hash table containing any needed field. This hash
923
         * table may be used to let the client to connect to a server and restore a previously saved
924
         * layer. So, the layer itself may not be saved to the disk since the actual saved
925
         * info is just its properties.
926
         *
927
         * @return Returns a hash table containing all the required information for
928
         * set up a wms layer
929
         */
930
        public Hashtable getProperties(){
931
                Hashtable info = new Hashtable();
932
                info.put(   "name", coverageName);
933
                info.put(   "host", getHost());
934
                info.put(    "crs", srs);
935
                info.put( "format", format);
936
                String str = time;
937
                if (str==null)
938
                        str = "";
939
                info.put(   "time", str);
940
                str = parameter;
941
                if (str==null)
942
                        str = "";
943
                info.put("parameter", str);
944

    
945
                return info;
946
        }
947

    
948
        /**
949
         * Obtiene la extensi?n del fichero de georreferenciaci?n
950
         * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
951
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
952
         */
953
        private String getExtensionWorldFile(){
954
                String extWorldFile = ".wld";
955
            if (format.equals("image/tif") || format.equals("image/tiff"))
956
                    extWorldFile = ".tfw";
957
            if (format.equals("image/jpeg"))
958
                    extWorldFile = ".jpgw";
959
            return extWorldFile;
960
        }
961

    
962
        public void setMaxResolution(Point2D maxResolution) {
963
                this.maxRes = maxResolution;
964
        }
965

    
966
        /**
967
         * Gets the last open GeoRasterFile against the temp file received
968
         *
969
         * Obtiene el ?ltimo GeoRasterFile abierto sobre el temporal recibido
970
         * @return
971
         */
972
        public GeoRasterFile getGeoRasterFile(){
973
                return rasterFile;
974
        }
975

    
976

    
977
        /**
978
         * Asignar el estado del raster
979
         * @param status
980
         */
981
        public void setStatus(StatusRasterInterface status){
982
                this.status = status;
983
        }
984

    
985
        /**
986
         * Obtiene el estado del raster
987
         * @return
988
         */
989
        public StatusRasterInterface getStatus(){
990
                return this.status;
991
        }
992

    
993
        /**
994
         * Gets the max resolution allowed by the coverage. Requesting a higher resolution
995
         * than this value does not cause any error, but the info responsed is just an
996
         * interpolation.
997
         *
998
         * In exchange for obtaining a greater file and without additional information,
999
         * we can easily connect it at the View.
1000
         *
1001
         *
1002
         * Obtiene la resoluci?n m?xima soportada por la cobertura. La petici?n
1003
         * de una resoluci?n superior a la soportada no provoca ning?n error, aunque
1004
         * la informaci?n obtenida s?lo es una mera interpolaci?n de informaci?n.
1005
         *
1006
         * A cambio de obtener un archivo mayor y sin informaci?n adicional, podemos
1007
         * f?cilmente acoplarlo a la vista.
1008
         *
1009
         * @return double
1010
         */
1011
        public Point2D getMaxResolution() {
1012
                if (maxRes==null)
1013
                        maxRes = wcs.getMaxResolution(coverageName);
1014
                return maxRes;
1015
        }
1016

    
1017

    
1018
        public void setDriver(FMapWCSDriver driver) {
1019
                this.driver = driver;
1020
        }
1021

    
1022
        /*
1023
         *  (non-Javadoc)
1024
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1025
         */
1026
        public int[] getTileSize() {
1027
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1028
                return size;
1029
        }
1030

    
1031
        /*
1032
         *  (non-Javadoc)
1033
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1034
         */
1035
        public boolean isTiled() {
1036
                return mustTileDraw;
1037
        }
1038
}