Statistics
| Revision:

svn-gvsig-desktop / tags / v1_0_2_Build_903 / extensions / extWCS / src / com / iver / cit / gvsig / fmap / layers / FLyrWCS.java @ 10704

History | View | Annotate | Download (33.6 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.Dimension;
44
import java.awt.Graphics2D;
45
import java.awt.Point;
46
import java.awt.Rectangle;
47
import java.awt.geom.AffineTransform;
48
import java.awt.geom.NoninvertibleTransformException;
49
import java.awt.geom.Point2D;
50
import java.awt.geom.Rectangle2D;
51
import java.awt.image.BufferedImage;
52
import java.awt.image.DataBuffer;
53
import java.io.File;
54
import java.io.IOException;
55
import java.lang.reflect.Constructor;
56
import java.lang.reflect.InvocationTargetException;
57
import java.net.MalformedURLException;
58
import java.net.URL;
59
import java.util.ArrayList;
60
import java.util.Hashtable;
61
import java.util.Map;
62

    
63
import javax.print.attribute.PrintRequestAttributeSet;
64

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

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

    
98

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

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

    
119
        private WCSStatus                                        wcsStatus = new WCSStatus();
120

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

    
133
        private boolean                                         mustTileDraw = false;
134
        private int                                                 maxTileDrawWidth  = 1023;
135
        private int                                                        maxTileDrawHeight = 1023;
136
        private int                                                 maxTilePrintWidth  = 250;
137
        private int                                                        maxTilePrintHeight = 250;
138
        
139
        private Grid                                                grid = null;
140

    
141
        private class MyCancellable implements ICancellable
142
        {
143

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

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

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

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

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

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

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

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

    
202
        }
203

    
204
        /**
205
         * Clase que contiene los datos de visualizaci?n de WCS. Tiene datos que representan al
206
         * raster en la vista. Este raster puede estar compuesto por tiles por lo que valores
207
         * como el ancho total o el m?nimo o m?ximo deben ser calculados a partir de todos los
208
         * tiles visualizados.
209
         * @author Nacho Brodin (brodin_ign@gva.es)
210
         */
211
        private class VisualStatus {
212
                /**
213
                 * Ancho y alto de la imagen o del conjunto de tiles si los tiene. Coincide con
214
                 * el ancho y alto del viewPort
215
                 */
216
                private        int                                                        width = 0, height = 0;
217
                private double                                                minX = 0D, minY = 0D, maxX = 0D, maxY = 0D;
218
                private int                                                 bandCount = 0;
219
                private int                                                        dataType = DataBuffer.TYPE_UNDEFINED;
220

    
221
                /**
222
                 * Ancho y alto total del raster que ser? la suma de todos los tiles.
223
                 */
224
                private        int                                                        rasterWidth = 0, rasterHeight = 0;
225
                private        double                                                rasterMinX = Double.MAX_VALUE, rasterMinY = Double.MAX_VALUE;
226
                private        double                                                rasterMaxX = 0, rasterMaxY = 0;
227
                /**
228
                 * Lista de nombre de fichero que componen toda la visualizaci?n.
229
                 */
230
                private String[]                                        fileNames = null;
231
        }
232

    
233
        /*
234
         *  (non-Javadoc)
235
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setRGB(int, int, int)
236
         */
237
        public void setRGB(int r, int g, int b) {
238
                this.r = r;
239
                this.g = g;
240
                this.b = b;
241
        }
242

    
243
        /*
244
         *  (non-Javadoc)
245
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getFilterStack()
246
         */
247
        public RasterFilterStack getFilterStack() {
248
                if(raster!=null)
249
                        return raster.filterStack;
250
                return null;
251
        }
252

    
253
        /*
254
         *  (non-Javadoc)
255
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setFilterStack(org.cresques.io.raster.RasterFilterStack)
256
         */
257
        public void setFilterStack(RasterFilterStack stack) {
258
                this.filterStack = stack;
259
        }
260

    
261
        /*
262
         *  (non-Javadoc)
263
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getSource()
264
         */
265
        public RasterAdapter getSource() {
266
                return null;
267
        }
268

    
269
        /*
270
         *  (non-Javadoc)
271
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setSource(com.iver.cit.gvsig.fmap.layers.RasterAdapter)
272
         */
273
        public void setSource(RasterAdapter ra) {
274
        }
275

    
276
        /*
277
         *  (non-Javadoc)
278
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPos(int, int)
279
         */
280
        public void setPos(int x, int y) {
281
                this.posX = x;
282
                this.posY = y;
283
        }
284

    
285
        /*
286
         *  (non-Javadoc)
287
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPosWC(double, double)
288
         */
289
        public void setPosWC(double x, double y) {
290
                this.posXWC = x;
291
                this.posYWC = y;
292
        }
293

    
294
        /*
295
         *  (non-Javadoc)
296
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getPixel(double, double)
297
         */
298
        public int[] getPixel(double wcx, double wcy) {
299
                if(getPxRaster() != null)
300
                        return getPxRaster().getPixel(wcx, wcy);
301
        return null;
302
        }
303

    
304
        /*
305
         *  (non-Javadoc)
306
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setBand(int, int)
307
         */
308
        public void setBand(int flag, int nBand) {
309
                switch(flag){
310
                case GeoRasterFile.RED_BAND:setBandR(nBand);break;
311
                case GeoRasterFile.GREEN_BAND:setBandG(nBand);break;
312
                case GeoRasterFile.BLUE_BAND:setBandB(nBand);break;
313
                }
314
        }
315

    
316
        /**
317
         * Sets the R-band.
318
         *
319
         * Asigna la banda R.
320
         * @param r
321
         */
322
        public void setBandR(int r){
323
                this.rband = r;
324
        }
325

    
326
        /**
327
         * Sets the G-band.
328
         *
329
         * Asigna la banda G
330
         * @param g
331
         */
332
        public void setBandG(int g){
333
                this.gband = g;
334
        }
335

    
336
        /**
337
         * Sets the B-band.
338
         *
339
         * Asigna la banda B
340
         * @param b
341
         */
342
        public void setBandB(int b){
343
                this.bband = b;
344
        }
345

    
346
        /*
347
         *  (non-Javadoc)
348
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getAttributes()
349
         */
350
        public ArrayList getAttributes() {
351
                if (rasterFile != null){
352
                        ArrayList attr = new ArrayList();
353
                        String dataType = "Byte";
354
                        if (rasterFile.getDataType() == DataBuffer.TYPE_BYTE) dataType = "Byte";
355
                        else if (visualStatus.dataType == DataBuffer.TYPE_SHORT)
356
                                dataType = "Short";
357
                        else if (visualStatus.dataType == DataBuffer.TYPE_USHORT)
358
                                dataType = "Unsigned Short";
359
                        else if (visualStatus.dataType == DataBuffer.TYPE_INT)
360
                                dataType = "Integer";
361
                        else if (visualStatus.dataType == DataBuffer.TYPE_FLOAT)
362
                                dataType = "Float";
363
                        else if (visualStatus.dataType == DataBuffer.TYPE_DOUBLE)
364
                                dataType = "Double";
365
                        else
366
                                dataType = "Unknown";
367

    
368
                        Object [][] a = {
369
                                {"Filename",rasterFile.getName().substring(rasterFile.getName().lastIndexOf("/")+1, rasterFile.getName().length())},
370
                                {"Filesize",new Long(0)},
371
                                {"Width",new Integer((int)this.getWidth())},
372
                                {"Height", new Integer((int)this.getHeight())},
373
                                {"Bands", new Integer(visualStatus.bandCount)},
374
                                {"BandDataType", dataType}
375
                        };
376
                        for (int i=0; i<a.length; i++)
377
                                attr.add(a[i]);
378

    
379
                        return attr;
380
                }
381
                return  null;
382
        }
383

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

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

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

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

    
416
        /*
417
         *  (non-Javadoc)
418
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getWidth()
419
         */
420
        public double getWidth() {
421
                return visualStatus.width;
422
        }
423

    
424
        /*
425
         *  (non-Javadoc)
426
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getHeight()
427
         */
428
        public double getHeight() {
429
                return visualStatus.height;
430
        }
431

    
432
        /**
433
         * @deprecated
434
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#getInfo
435
         */
436
        public String queryByPoint(Point p) throws DriverException {
437
                String data = "<file:"+getName().replaceAll("[^a-zA-Z0-9]","")+">\n";
438
                ArrayList attr = this.getAttributes();
439
                data += "  <raster\n";
440
                data += "    File=\""+getName()+"\"\n";
441
                for (int i=0; i<attr.size(); i++) {
442
                        Object [] a = (Object []) attr.get(i);
443

    
444
                        data += "    "+a[0].toString()+"=";
445
                        if (a[1].toString() instanceof String)
446
                                data += "\""+a[1].toString()+"\"\n";
447
                        else
448
                                data += a[1].toString()+"\n";
449
                }
450
                data += "    Point=\""+posX+" , "+posY+"\"\n";
451
                data += "    Point_WC=\""+posXWC+" , "+posYWC+"\"\n";
452
                data += "    RGB=\""+r+", "+g+", "+b+"\"\n";
453
                data += "  />\n";
454

    
455
                data += "</file:"+getName().replaceAll("[^a-zA-Z0-9]","")+">\n";
456
                System.out.println(data);
457
                return data;
458
        }
459
        /**
460
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#getInfo
461
         */
462
        public XMLItem[] getInfo(Point point, double tolerance, Cancellable cancel ) throws DriverException {
463
                String data = "<file:"+getName().replaceAll("[^a-zA-Z0-9]","")+">\n";
464

    
465
                Point2D pReal = getMapContext().getViewPort().toMapPoint(point);
466
                Point2D px = null;
467
                if(        pReal.getX() > this.getMinX() &&
468
                        pReal.getX() < this.getMaxX() &&
469
                        pReal.getY() > this.getMinY() &&
470
                        pReal.getY() < this.getMaxY()){
471

    
472
                        px = new Point2D.Double();
473
                        double w = (visualStatus.rasterMaxX - visualStatus.rasterMinX);
474
                        double h = (visualStatus.rasterMaxY - visualStatus.rasterMinY);
475
                        px.setLocation(((pReal.getX() - visualStatus.rasterMinX) * visualStatus.rasterWidth) / w,
476
                                                        ((visualStatus.rasterMaxY - pReal.getY()) * visualStatus.rasterHeight) / h);
477
                }
478

    
479
                int[] rgb = this.getPixel(pReal.getX(), pReal.getY());
480

    
481
                StringXMLItem[] item = new StringXMLItem[1];
482

    
483
                data += "  <raster\n";
484
                data += "    View_Point=\""+point.getX()+" , "+point.getY()+"\"\n";
485
                data += "    World_Point=\""+DoubleUtilities.format(pReal.getX(), 3)+" , "+ DoubleUtilities.format(pReal.getY(), 3)+"\"\n";
486
                if(        px == null || px.getX() > visualStatus.rasterWidth || px.getX() < 0 ||
487
                                px.getY() > visualStatus.rasterHeight || px.getY() < 0)
488
                                data += "    Pixel_Point=\"Out\"\n";
489
                        else{
490
                                data += "    Pixel_Point=\""+(int)px.getX()+" , "+(int)px.getY()+"\"\n";                
491
                                data += "    Band_Value=\"";
492
                                for(int file = 0; file < visualStatus.fileNames.length; file++ ){
493
                                        GdalFile rf;
494
                                        try {
495
                                                rf = new GdalFile(getMapContext().getViewPort().getProjection(), visualStatus.fileNames[file]);
496
                                        } catch (NotSupportedExtensionException e) {
497
                                                throw new DriverException("Open File Error.");
498
                                        }
499
                                        Extent ex = rf.getExtent();
500
                                        
501
                                        if(pReal.getX() >= ex.minX() && pReal.getX() <= ex.maxX() && pReal.getY() >= ex.minY() && pReal.getY() <= ex.maxY()){
502
                                                for(int i = 0; i < visualStatus.bandCount; i++){
503
                                                        Object pxData = rf.getData((int)px.getX(), (int)px.getY(), i);
504
                                                        if(pxData != null){
505
                                                                if(visualStatus.dataType >= 0 && visualStatus.dataType <= 3)
506
                                                                        data += ((Integer)pxData).intValue()+"  ";
507
                                                                                                                
508
                                                                if(visualStatus.dataType >= 4)
509
                                                                        data += ((Float)pxData).floatValue()+"  ";
510
                                                                        
511
                                                                if(visualStatus.dataType >= 5)
512
                                                                        data += ((Double)pxData).doubleValue()+"  ";
513
                                                        }
514
                                                }
515
                                        }
516
                                        rf.close();
517
                                }
518
                                data += "\"\n";
519
                        }
520
                        
521
                        if(rgb != null)
522
                                data += "    RGB=\""+rgb[1]+"  "+rgb[2]+"  "+rgb[3]+"\"\n";
523
                        
524
                        data += "  />\n";
525
                        data += "</file:"+getName().replaceAll("[^a-zA-Z0-9]","")+">\n";
526

    
527
                        item[0] = new StringXMLItem(data, this);
528
                        return item;
529
        }
530

    
531
        /*
532
         *  (non-Javadoc)
533
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent()
534
         */
535
        public Rectangle2D getFullExtent() {
536
                return fullExtent;
537
        }
538

    
539
        /*
540
         *  (non-Javadoc)
541
         * @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)
542
         */
543
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale) throws DriverException {
544

    
545
                if (isWithinScale(scale)){
546
                        Point2D p = viewPort.getOffset();
547
                        // p will be (0, 0) when drawing a view or other when painting onto
548
                        // the Layout.
549
                        visualStatus.width =  viewPort.getImageWidth();
550
                        visualStatus.height =  viewPort.getImageHeight();
551
                        visualStatus.minX = viewPort.getAdjustedExtent().getMinX();
552
                        visualStatus.minY = viewPort.getAdjustedExtent().getMinY();
553
                        visualStatus.maxX = viewPort.getAdjustedExtent().getMaxX();
554
                        visualStatus.maxY = viewPort.getAdjustedExtent().getMaxY();
555
                        visualStatus.rasterWidth = 0;
556
                        visualStatus.rasterHeight = 0;
557
                        visualStatus.rasterMinX = Double.MAX_VALUE;
558
                        visualStatus.rasterMinY = Double.MAX_VALUE;
559
                        visualStatus.rasterMaxX = 0;
560
                        visualStatus.rasterMaxY = 0;
561
                        visualStatus.fileNames = new String[1];
562

    
563
                        if(mustTileDraw){
564
                                if(viewPort.getImageWidth()<= maxTileDrawWidth && viewPort.getImageHeight()<=maxTileDrawHeight)
565
                                        drawTile(g, viewPort, cancel, 0);
566
                                else{
567
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), viewPort.getImageWidth(), viewPort.getImageHeight());
568
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
569
                                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
570
                                        visualStatus.fileNames = new String[tiles.getNumTiles()];
571
                                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
572
                                                // drawing part
573
                                                try {
574
                                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
575
                                                        drawTile(g, vp, cancel, tileNr);
576
                                                } catch (NoninvertibleTransformException e) {
577
                                                        e.printStackTrace();
578
                                                }
579
                                        }
580
                                }
581
                        }else
582
                                drawTile(g, viewPort, cancel, 0);
583
                }
584
                Runtime r = Runtime.getRuntime();
585
                long mem = r.totalMemory() - r.freeMemory();
586
                System.err.println("Memoria total: " + (mem / 1024) +"KB");
587
        }
588

    
589
        /**
590
         * This is the method used to draw a tile in a WMS mosaic layer.
591
         * @param tile Tile number to draw
592
         */
593
        private void drawTile(Graphics2D g, ViewPort vp, Cancellable cancel, int tile) throws DriverException {
594

    
595
                // Compute the query geometry
596
                // 1. Check if it is within borders
597
                Rectangle2D extent = getFullExtent();
598
        if ((vp.getAdjustedExtent().getMinX() > extent.getMaxX()) ||
599
                (vp.getAdjustedExtent().getMinY() > extent.getMaxY()) ||
600
                (vp.getAdjustedExtent().getMaxX() < extent.getMinX()) ||
601
                (vp.getAdjustedExtent().getMaxY() < extent.getMinY())) {
602
            return;
603
        }
604

    
605
        // 2. Compute extent to be requested.
606
        Rectangle2D bBox = new Rectangle2D.Double();
607
        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
608

    
609
        // 3. Compute size in pixels
610
        double scalex = vp.getAffineTransform().getScaleX();
611
        double scaley = vp.getAffineTransform().getScaleY();
612
        int wImg = (int) Math.ceil(Math.abs(bBox.getWidth() * scalex) + 1);
613
        int hImg = (int) Math.ceil(Math.abs(bBox.getHeight() * scaley) + 1);
614
        Dimension sz = new Dimension(wImg, hImg);
615

    
616
        if ((wImg <= 0) || (hImg <= 0)) {
617
            return;
618
        }
619

    
620
                try {
621
                        sz = new Dimension(wImg, hImg);
622
                        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
623

    
624
                        wcsStatus.setCoveraName( coverageName );
625
                        wcsStatus.setExtent( bBox );
626
                        wcsStatus.setFormat( format );
627
                        wcsStatus.setHeight( hImg );
628
                        wcsStatus.setWidth( wImg );
629
                        wcsStatus.setSrs(srs);
630
                        wcsStatus.setParameters( parameter );
631
                        wcsStatus.setTime( time );
632
                        wcsStatus.setOnlineResource((String) onlineResources.get("GetCoverage"));
633

    
634
                        File f = getDriver().getCoverage(wcsStatus, new MyCancellable(cancel));
635
                        if (f == null)
636
                                return;
637
                        String nameWordFile = f.getPath() + getExtensionWorldFile();
638
                        com.iver.andami.Utilities.createTemp(nameWordFile, this.getDataWorldFile(bBox, sz));
639

    
640
                        /*if(status!=null && firstLoad){
641
                                status.applyStatus(this);
642
                                firstLoad = false;
643
                        }*/
644
                        ViewPortData vpData = new ViewPortData(
645
                                vp.getProjection(), new Extent(bBox), sz );
646
                        vpData.setMat(vp.getAffineTransform());
647

    
648
                        visualStatus.fileNames[tile] = f.getAbsolutePath();
649
                        rasterProcess(g, vpData, f);
650

    
651
                } catch (ValidationException e) {
652
                        UnknownResponseFormatExceptionType type =
653
                                new UnknownResponseFormatExceptionType();
654
                        type.setLayerName(getName());
655
                        try {
656
                                type.setDriverName(getDriver().getName());
657
                        } catch (Exception e1) {
658
                                e1.printStackTrace();
659
                        }
660
                        type.setFormat(format);
661
                        type.setHost(host);
662
                        type.setProtocol("WCS");
663
                        DriverException exception = new DriverException("unknown_response_format", type);
664
                        throw exception;
665
//        azabala                throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
666
                }
667
                catch (UnsupportedVersionException e) {
668
                        UnsuportedProtocolVersionExceptionType type =
669
                                new UnsuportedProtocolVersionExceptionType();
670
                        type.setLayerName(getName());
671
                        try {
672
                                type.setDriverName(getDriver().getName());
673
                        } catch (Exception ex){
674
                        }
675
                        type.setUrl(host);
676
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e, type);
677

    
678
//        azabala                throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
679
                } catch (IOException e) {
680
                        ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
681
                        type.setLayerName(getName());
682
                        try {
683
                                type.setDriverName(getDriver().getName());
684
                        } catch (Exception e1) {
685
                        }
686
                        type.setHost(host);
687
                        throw new DriverException(PluginServices.
688
                                        getText(this, "connect_error"), e, type);
689
                } catch (WCSException e) {
690
//azabala: la capturamos y la convertimos en DriverException
691
                        WCSDriverExceptionType type = new WCSDriverExceptionType();
692
                        type.setLayerName(getName());
693
                        try {
694
                                type.setDriverName(getDriver().getName());
695
                        } catch (Exception e1) {
696
                        }
697
                        type.setWcsStatus(wcsStatus);
698
                        this.setVisible(false);
699
                        throw new DriverException("Error WCS", e,  type);
700

    
701
//            JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
702

    
703
        }//catch
704
        }
705

    
706
        /**
707
         * Devuelve el FMapWMSDriver.
708
         *
709
         * @return FMapWMSDriver
710
         *
711
         * @throws IllegalStateException
712
         * @throws ValidationException
713
         * @throws UnsupportedVersionException
714
         * @throws IOException
715
         */
716
        private FMapWCSDriver getDriver() throws IllegalStateException, ValidationException, UnsupportedVersionException, IOException {
717
                if (wcs == null) {
718
                        wcs = FMapWCSDriverFactory.getFMapDriverForURL(host);
719
                }
720
                return wcs;
721
        }
722

    
723
        /**
724
         * Calcula el contenido del fichero de georreferenciaci?n de una imagen.
725
         * @param bBox Tama?o y posici?n de la imagen (en coordenadas de usuario)
726
         * @param sz Tama?o de la imagen en pixeles.
727
         * @return el 'WorldFile', como String.
728
         * @throws IOException
729
         */
730
        public String getDataWorldFile(Rectangle2D bBox, Dimension sz) throws IOException {
731
                StringBuffer data = new StringBuffer();
732
            data.append((bBox.getMaxX() - bBox.getMinX())/(sz.getWidth() - 1)+"\n");
733
            data.append("0.0\n");
734
            data.append("0.0\n");
735
            data.append("-"+(bBox.getMaxY() - bBox.getMinY())/(sz.getHeight() - 1)+"\n");
736
            data.append(""+bBox.getMinX()+"\n");
737
            data.append(""+bBox.getMaxY()+"\n");
738
            return data.toString();
739
        }
740

    
741
        /**
742
         * Dibuja una imagen usando PxRaster
743
         * @param g        Graphics2D en el que hay que dibujar.
744
         * @param vpData Par?metros de visualizaci?n
745
         * @param file La imagen en cuesti?n.
746
         */
747
        private void rasterProcess(Graphics2D g, ViewPortData vpData, File file)throws DriverException {
748

    
749
                //Creamos el PxRaster
750
                try{
751
                        rasterFile = new GdalFile(vpData.getProjection(), file.getAbsolutePath());
752
                } catch (NotSupportedExtensionException e) {
753
                        throw new DriverException("Open File Error");
754
                }
755
                raster = new PxRaster(rasterFile, null, rasterFile.getExtent());
756

    
757
                if(status!=null && firstLoad){
758
                        status.applyStatus(this);
759
                        firstLoad = false;
760
                }
761
                
762
                grid = new Grid(rasterFile);
763
                grid.addRenderizer(raster);
764
                
765
                visualStatus.rasterWidth += rasterFile.getWidth();
766
                visualStatus.rasterHeight += rasterFile.getHeight();
767
                if(raster.getExtent().getMin().getX() < visualStatus.rasterMinX)
768
                        visualStatus.rasterMinX = raster.getExtent().getMin().getX();
769
                if(raster.getExtent().getMin().getY() < visualStatus.rasterMinY)
770
                        visualStatus.rasterMinY = raster.getExtent().getMin().getY();
771
                if(raster.getExtent().getMax().getX() > visualStatus.rasterMaxX)
772
                        visualStatus.rasterMaxX = raster.getExtent().getMax().getX();
773
                if(raster.getExtent().getMax().getY() > visualStatus.rasterMaxY)
774
                        visualStatus.rasterMaxY = raster.getExtent().getMax().getY();
775
                
776
                //Recuperamos la pila de filtros si ya hubiese sido cargado antes
777
                if (this.filterStack!=null)
778
                        raster.filterStack = this.filterStack;
779

    
780
                raster.setTransparency(false);
781

    
782
                //Asignamos transparencia y orden de bandas
783
                if (getTransparency() == -1 && !firstLoad);
784
                else
785
                        raster.setTransparency(getTransparency());
786

    
787
                raster.setBand(GeoRasterFile.RED_BAND,rband);
788
                raster.setBand(GeoRasterFile.GREEN_BAND, gband);
789
                raster.setBand(GeoRasterFile.BLUE_BAND, bband);
790

    
791
                //Despues del primer pxRaster asignamos el stackManager guardado para los siguientes.
792
                //Con esto conseguimos asignar los cambios que se hayan producido desde el cuadro de
793
                //propiedades cuando creamos un nuevo pxRaster
794
                if (this.stackManager != null)
795
                        raster.setStackManager(this.stackManager);
796

    
797
                if (visualStatus != null){
798
                        visualStatus.bandCount = raster.getBandCount();
799
                        visualStatus.dataType = raster.getDataType();
800
                }
801

    
802
                raster.draw(g, vpData);
803

    
804
                //En el primer pxRaster de una imagen obtenemos el Stack Manager para poder modificarlo
805
                //si queremos desde las propiedades
806

    
807
                if (this.stackManager == null)
808
                        this.stackManager = raster.getStackManager();
809

    
810
                if (this.filterStack == null)
811
                        this.filterStack = raster.filterStack;
812

    
813
                rasterFile.close();
814
        }
815

    
816
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet properties) throws DriverException {
817
                draw(null, g, viewPort, cancel, scale);
818
        }
819

    
820
        /**
821
         * @return Returns the raster.
822
         */
823
        public PxRaster getPxRaster() {
824
                return raster;
825
        }
826

    
827
        /**
828
         * Returns the XMLEntity containing the necessary info for reproduce
829
         * the layer.
830
         *
831
         * Devuelve el XMLEntity con la informaci?n necesaria para reproducir
832
         * la capa.
833
         *
834
         * @return XMLEntity.
835
         * @throws XMLException
836
         */
837
        public XMLEntity getXMLEntity() throws XMLException {
838
                XMLEntity xml = super.getXMLEntity();
839

    
840
                xml.putProperty("wcs.host", getHost());
841
                xml.putProperty("wcs.fullExtent", StringUtilities.rect2String( fullExtent ));
842
                xml.putProperty("wcs.layerQuery", coverageName );
843
                xml.putProperty("wcs.format", format );
844
                xml.putProperty("wcs.srs", srs );
845
                xml.putProperty("wcs.time", time );
846
                xml.putProperty("wcs.parameter", parameter );
847
                xml.putProperty("wcs.coverageName", coverageName );
848
                xml.putProperty("wcs.maxResX", maxRes.getX());
849
                xml.putProperty("wcs.maxResY", maxRes.getY());
850
                if (status!=null)
851
                        status.getXMLEntity(xml, true, this);
852
                else{
853
                        status = new StatusLayerRaster();
854
                        status.getXMLEntity(xml, true, this);
855
                }
856
                return xml;
857
        }
858

    
859
        /**
860
         * Reproduces the layer from an XMLEntity.
861
         *
862
         * A partir del XMLEntity reproduce la capa.
863
         *
864
          * @param xml XMLEntity
865
         *
866
         * @throws XMLException
867
         * @throws DriverException
868
         * @throws DriverIOException
869
         */
870
        public void setXMLEntity(XMLEntity xml) throws XMLException {
871
                super.setXMLEntity(xml);
872

    
873
                // host
874
                try {
875
                        host = new URL(xml.getStringProperty("wcs.host"));
876
                } catch (MalformedURLException e) {
877
                        throw new XMLException(e);
878
                }
879

    
880
                // full extent
881
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty("wcs.fullExtent"));
882

    
883
                // coverageQuery
884
                coverageName = xml.getStringProperty("wcs.layerQuery");
885

    
886
                // format
887
                format = xml.getStringProperty("wcs.format");
888

    
889
                // srs
890
                srs = xml.getStringProperty("wcs.srs");
891

    
892
                // time
893
                time = xml.getStringProperty("wcs.time");
894

    
895
                // parameter
896
                parameter = xml.getStringProperty("wcs.parameter");
897

    
898
                // coverage name
899
                coverageName = xml.getStringProperty("wcs.coverageName");
900

    
901
                // max resolution
902
                if (xml.contains("wcs.maxRes"))
903
                        maxRes = new Point2D.Double(xml.getDoubleProperty("wcs.maxRes"), xml.getDoubleProperty("wcs.maxRes"));
904
                else if (xml.contains("wcs.maxResX") && xml.contains("wcs.maxResY"))
905
                        maxRes = new Point2D.Double(xml.getDoubleProperty("wcs.maxResX"), xml.getDoubleProperty("wcs.maxResY"));
906

    
907
                // OnlineResources
908
        if (xml.contains("onlineResources")) {
909
                String[] operations = xml.getStringProperty("onlineResources").split("~##SEP1##~");
910
                for (int i = 0; i < operations.length; i++) {
911
                                String[] resources = operations[i].split("~##SEP2##~");
912
                                if (resources.length==2 && resources[1]!="")
913
                                        onlineResources.put(resources[0], resources[1]);
914
                        }
915
        }
916
                String claseStr = null;
917
                if (xml.contains("raster.class")) {
918
                        claseStr = xml.getStringProperty("raster.class");
919
                }
920
                if (status!=null)
921
                        status.setXMLEntity(xml, this);
922
                else {
923
                        //Cuando cargamos un proyecto
924

    
925
                        if(claseStr!=null && !claseStr.equals("")){
926
                                try{
927
                                        Class clase = Class.forName(claseStr);
928
                                        Constructor constr = clase.getConstructor(null);
929
                                        status = (StatusRasterInterface)constr.newInstance(null);
930
                                        if(status!=null)
931
                                                status.setXMLEntity(xml, this);
932
                                } catch(ClassNotFoundException exc) {
933
                                        exc.printStackTrace();
934
                                } catch(InstantiationException exc) {
935
                                        exc.printStackTrace();
936
                                } catch(IllegalAccessException exc) {
937
                                        exc.printStackTrace();
938
                                } catch(NoSuchMethodException exc) {
939
                                        exc.printStackTrace();
940
                                } catch(InvocationTargetException exc) {
941
                                        exc.printStackTrace();
942
                                }
943
                        }
944
                }
945
                firstLoad = true;
946
        }
947

    
948
        public void setCoverageName(String coverageName) {
949
                this.coverageName = coverageName;
950
        }
951

    
952
        public void setParameter(String parametersString) {
953
                this.parameter = parametersString;
954
        }
955

    
956
        public void setTime(String time) {
957
                this.time = time;
958
        }
959

    
960
        public void setSRS(String srs) {
961
                this.srs = srs;
962
        }
963

    
964
        public void setFormat(String format) {
965
                this.format = format;
966
        }
967

    
968

    
969
        /**
970
         * Inserta el URL.
971
         *
972
         * @param host String.
973
         * @throws MalformedURLException
974
         */
975
        public void setHost(String host) {
976
                try {
977
                        setHost(new URL(host));
978
                } catch (MalformedURLException e) {
979

    
980
                }
981
        }
982

    
983
        /**
984
         * Inserta el URL.
985
         *
986
         * @param host URL.
987
         */
988
        public void setHost(URL host) {
989
                this.host = host;
990
        }
991

    
992
        /**
993
         * Sets the layer's full extent.
994
         *
995
         * Establece la extensi?n m?xima de la capa.
996
         *
997
         * @param rect
998
         */
999
        public void setFullExtent(Rectangle2D rect) {
1000
                this.fullExtent = rect;
1001
        }
1002

    
1003
        /**
1004
         * Devuelve el URL.
1005
         *
1006
         * @return URL.
1007
         */
1008
        public URL getHost() {
1009
                return host;
1010
        }
1011

    
1012
        /**
1013
         * Remote source layers have a bunch of properties that are required for get them from
1014
         * the servers. This method supplies a hash table containing any needed field. This hash
1015
         * table may be used to let the client to connect to a server and restore a previously saved
1016
         * layer. So, the layer itself may not be saved to the disk since the actual saved
1017
         * info is just its properties.
1018
         *
1019
         * @return Returns a hash table containing all the required information for
1020
         * set up a wms layer
1021
         */
1022
        public Hashtable getProperties(){
1023
                Hashtable info = new Hashtable();
1024
                info.put(   "name", coverageName);
1025
                info.put(   "host", getHost());
1026
                info.put(    "crs", srs);
1027
                info.put( "format", format);
1028
                String str = time;
1029
                if (str==null)
1030
                        str = "";
1031
                info.put(   "time", str);
1032
                str = parameter;
1033
                if (str==null)
1034
                        str = "";
1035
                info.put("parameter", str);
1036

    
1037
                return info;
1038
        }
1039

    
1040
        /**
1041
         * Obtiene la extensi?n del fichero de georreferenciaci?n
1042
         * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
1043
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
1044
         */
1045
        private String getExtensionWorldFile(){
1046
                String extWorldFile = ".wld";
1047
            if (format.equals("image/tif") || format.equals("image/tiff"))
1048
                    extWorldFile = ".tfw";
1049
            if (format.equals("image/jpeg"))
1050
                    extWorldFile = ".jpgw";
1051
            return extWorldFile;
1052
        }
1053

    
1054
        public void setMaxResolution(Point2D maxResolution) {
1055
                this.maxRes = maxResolution;
1056
        }
1057

    
1058
        /**
1059
         * Gets the last open GeoRasterFile against the temp file received
1060
         *
1061
         * Obtiene el ?ltimo GeoRasterFile abierto sobre el temporal recibido
1062
         * @return
1063
         */
1064
        public GeoRasterFile getGeoRasterFile(){
1065
                return rasterFile;
1066
        }
1067

    
1068

    
1069
        /**
1070
         * Asignar el estado del raster
1071
         * @param status
1072
         */
1073
        public void setStatus(StatusRasterInterface status){
1074
                this.status = status;
1075
        }
1076

    
1077
        /**
1078
         * Obtiene el estado del raster
1079
         * @return
1080
         */
1081
        public StatusRasterInterface getStatus(){
1082
                return this.status;
1083
        }
1084

    
1085
        /**
1086
         * Gets the max resolution allowed by the coverage. Requesting a higher resolution
1087
         * than this value does not cause any error, but the info responsed is just an
1088
         * interpolation.
1089
         *
1090
         * In exchange for obtaining a greater file and without additional information,
1091
         * we can easily connect it at the View.
1092
         *
1093
         *
1094
         * Obtiene la resoluci?n m?xima soportada por la cobertura. La petici?n
1095
         * de una resoluci?n superior a la soportada no provoca ning?n error, aunque
1096
         * la informaci?n obtenida s?lo es una mera interpolaci?n de informaci?n.
1097
         *
1098
         * A cambio de obtener un archivo mayor y sin informaci?n adicional, podemos
1099
         * f?cilmente acoplarlo a la vista.
1100
         *
1101
         * @return double
1102
         */
1103
        public Point2D getMaxResolution() {
1104
                if (maxRes==null)
1105
                        maxRes = wcs.getMaxResolution(coverageName);
1106
                return maxRes;
1107
        }
1108

    
1109

    
1110
        public void setDriver(FMapWCSDriver driver) {
1111
                this.wcs = driver;
1112
        }
1113

    
1114
        /*
1115
         *  (non-Javadoc)
1116
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1117
         */
1118
        public int[] getTileSize() {
1119
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1120
                return size;
1121
        }
1122

    
1123
        /*
1124
         *  (non-Javadoc)
1125
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1126
         */
1127
        public boolean isTiled() {
1128
                return mustTileDraw;
1129
        }
1130
        
1131
        /**
1132
         * Obtiene el tipo de dato de la capa raster
1133
         * @return Entero que representa el tipo de dato de la capa raster.
1134
         */
1135
        public int getDataType() {
1136
                return rasterFile.getDataType();
1137
        }
1138
        
1139
        /**
1140
         * Obtiene el grid asociado al raster que hay cargado en ese momento
1141
         * @return grid
1142
         */
1143
        public Grid getGrid(){
1144
                return grid;
1145
        }
1146
}