Statistics
| Revision:

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

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.px.Extent;
71
import org.cresques.px.PxRaster;
72
import org.exolab.castor.xml.ValidationException;
73
import org.gvsig.remoteClient.wcs.WCSStatus;
74
import org.gvsig.remoteClient.wms.ICancellable;
75

    
76
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
77
import com.iver.andami.PluginServices;
78
import com.iver.cit.gvsig.exceptions.layers.ConnectionErrorLayerException;
79
import com.iver.cit.gvsig.exceptions.layers.LoadLayerException;
80
import com.iver.cit.gvsig.exceptions.layers.UnsupportedVersionLayerException;
81
import com.iver.cit.gvsig.exceptions.visitors.VisitorException;
82
import com.iver.cit.gvsig.fmap.ConnectionErrorExceptionType;
83
import com.iver.cit.gvsig.fmap.UnknownResponseFormatExceptionType;
84
import com.iver.cit.gvsig.fmap.UnsuportedProtocolVersionExceptionType;
85
import com.iver.cit.gvsig.fmap.ViewPort;
86
import com.iver.cit.gvsig.fmap.WCSDriverExceptionType;
87
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
88
import com.iver.cit.gvsig.fmap.drivers.wcs.FMapWCSDriver;
89
import com.iver.cit.gvsig.fmap.drivers.wcs.FMapWCSDriverFactory;
90
import com.iver.cit.gvsig.fmap.drivers.wcs.WCSDriverException;
91
import com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint;
92
import com.iver.cit.gvsig.fmap.layers.layerOperations.StringXMLItem;
93
import com.iver.cit.gvsig.fmap.layers.layerOperations.XMLItem;
94
import com.iver.utiles.DoubleUtilities;
95
import com.iver.utiles.StringUtilities;
96
import com.iver.utiles.XMLEntity;
97
import com.iver.utiles.swing.threads.Cancellable;
98

    
99

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

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

    
120
        private WCSStatus                                        wcsStatus = new WCSStatus();
121

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

    
134
        private boolean                                         mustTileDraw = false;
135
        private int                                                 maxTileDrawWidth  = 1023;
136
        private int                                                        maxTileDrawHeight = 1023;
137
        private int                                                 maxTilePrintWidth  = 250;
138
        private int                                                        maxTilePrintHeight = 250;
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(false, 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 WCS. Tiene datos que representan al
205
         * raster en la vista. Este raster puede estar compuesto por tiles por lo que valores
206
         * como el ancho total o el m?nimo o m?ximo deben ser calculados a partir de todos los
207
         * tiles visualizados.
208
         * @author Nacho Brodin (brodin_ign@gva.es)
209
         */
210
        private class VisualStatus {
211
                /**
212
                 * Ancho y alto de la imagen o del conjunto de tiles si los tiene. Coincide con
213
                 * el ancho y alto del viewPort
214
                 */
215
                private        int                                                        width = 0, height = 0;
216
                private double                                                minX = 0D, minY = 0D, maxX = 0D, maxY = 0D;
217
                private int                                                 bandCount = 0;
218
                private int                                                        dataType = DataBuffer.TYPE_UNDEFINED;
219

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
482
                data += "  <raster\n";
483
                data += "    View_Point=\""+point.getX()+" , "+point.getY()+"\"\n";
484
                data += "    World_Point=\""+DoubleUtilities.format(pReal.getX(), 3)+" , "+ DoubleUtilities.format(pReal.getY(), 3)+"\"\n";
485
                if(        px == null || px.getX() > visualStatus.rasterWidth || px.getX() < 0 ||
486
                        px.getY() > visualStatus.rasterHeight || px.getY() < 0)
487
                        data += "    Pixel_Point=\"Out\"\n";
488
                else
489
                        data += "    Pixel_Point=\""+(int)px.getX()+" , "+(int)px.getY()+"\"\n";
490
                if(rgb != null)
491
                        data += "    RGB=\""+rgb[1]+"  "+rgb[2]+"  "+rgb[3]+"\"\n";
492
                data += "    Band_Value=\"";
493

    
494
                for(int file = 0; file < visualStatus.fileNames.length; file++ ){
495
                        GdalFile rf = new GdalFile(getMapContext().getViewPort().getProjection(), visualStatus.fileNames[file]);
496
                        Extent ex = rf.getExtent();
497
                        if(pReal.getX() >= ex.minX() && pReal.getX() <= ex.maxX() && pReal.getY() >= ex.minY() && pReal.getY() <= ex.maxY()){
498
                                if(visualStatus.dataType >= 0 && visualStatus.dataType <= 3){
499
                                        for(int i = 0; i < visualStatus.bandCount; i++){
500
                                                Integer value = (Integer)rf.getData((int)px.getX(), (int)px.getY(), i);
501
                                                if(value != null)
502
                                                        data += value.intValue()+"  ";
503
                                        }
504
                                }
505
                                if(visualStatus.dataType >= 4){
506
                                        for(int i = 0; i < visualStatus.bandCount; i++){
507
                                                Float value = (Float)rf.getData((int)px.getX(), (int)px.getY(), i);
508
                                                if(value != null)
509
                                                        data += value.floatValue()+"  ";
510
                                        }
511
                                }
512
                                if(visualStatus.dataType >= 5){
513
                                        for(int i = 0; i < visualStatus.bandCount; i++){
514
                                                Double value = (Double)rf.getData((int)px.getX(), (int)px.getY(), i);
515
                                                if(value != null)
516
                                                        data += value.doubleValue()+"  ";
517
                                        }
518
                                }
519
                        }
520
                        rf.close();
521
                }
522

    
523
                data += "\"\n";
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 ReadDriverException {
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
                        try {
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
                        }catch (ConnectionErrorLayerException e) {
584
                                e.printStackTrace();
585
                        }catch (UnsupportedVersionLayerException e) {
586
                                e.printStackTrace();
587
                        }catch (LoadLayerException e) {
588
                                e.printStackTrace();
589
                        }
590
                }
591
                Runtime r = Runtime.getRuntime();
592
                long mem = r.totalMemory() - r.freeMemory();
593
                System.err.println("Memoria total: " + (mem / 1024) +"KB");
594
        }
595

    
596
        /**
597
         * This is the method used to draw a tile in a WMS mosaic layer.
598
         * @param tile Tile number to draw
599
         */
600
        private void drawTile(Graphics2D g, ViewPort vp, Cancellable cancel, int tile) throws LoadLayerException {
601

    
602
                // Compute the query geometry
603
                // 1. Check if it is within borders
604
                Rectangle2D extent = getFullExtent();
605
        if ((vp.getAdjustedExtent().getMinX() > extent.getMaxX()) ||
606
                (vp.getAdjustedExtent().getMinY() > extent.getMaxY()) ||
607
                (vp.getAdjustedExtent().getMaxX() < extent.getMinX()) ||
608
                (vp.getAdjustedExtent().getMaxY() < extent.getMinY())) {
609
            return;
610
        }
611

    
612
        // 2. Compute extent to be requested.
613
        Rectangle2D bBox = new Rectangle2D.Double();
614
        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
615

    
616
        // 3. Compute size in pixels
617
        double scalex = vp.getAffineTransform().getScaleX();
618
        double scaley = vp.getAffineTransform().getScaleY();
619
        int wImg = (int) Math.ceil(Math.abs(bBox.getWidth() * scalex) + 1);
620
        int hImg = (int) Math.ceil(Math.abs(bBox.getHeight() * scaley) + 1);
621
        Dimension sz = new Dimension(wImg, hImg);
622

    
623
        if ((wImg <= 0) || (hImg <= 0)) {
624
            return;
625
        }
626

    
627
                try {
628
                        sz = new Dimension(wImg, hImg);
629
                        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
630

    
631
                        wcsStatus.setCoveraName( coverageName );
632
                        wcsStatus.setExtent( bBox );
633
                        wcsStatus.setFormat( format );
634
                        wcsStatus.setHeight( hImg );
635
                        wcsStatus.setWidth( wImg );
636
                        wcsStatus.setSrs(srs);
637
                        wcsStatus.setParameters( parameter );
638
                        wcsStatus.setTime( time );
639
                        wcsStatus.setOnlineResource((String) onlineResources.get("GetCoverage"));
640

    
641
                        File f = getDriver().getCoverage(wcsStatus, new MyCancellable(cancel));
642
                        if (f == null)
643
                                return;
644
                        String nameWordFile = f.getPath() + getExtensionWorldFile();
645
                        com.iver.andami.Utilities.createTemp(nameWordFile, this.getDataWorldFile(bBox, sz));
646

    
647
                        if(status!=null && firstLoad){
648
                                status.applyStatus(this);
649
                                firstLoad = false;
650
                        }
651
                        ViewPortData vpData = new ViewPortData(
652
                                vp.getProjection(), new Extent(bBox), sz );
653
                        vpData.setMat(vp.getAffineTransform());
654

    
655
                        visualStatus.fileNames[tile] = f.getAbsolutePath();
656
                        rasterProcess(g, vpData, f);
657

    
658
//                } catch (ValidationException e) {
659
//                        UnknownResponseFormatExceptionType type =
660
//                                new UnknownResponseFormatExceptionType();
661
//                        type.setLayerName(getName());
662
//                        try {
663
//                                type.setDriverName(getDriver().getName());
664
//                        } catch (Exception e1) {
665
//                                e1.printStackTrace();
666
//                        }
667
//                        type.setFormat(format);
668
//                        type.setHost(host);
669
//                        type.setProtocol("WCS");
670
//                        ReadDriverException exception = new ReadDriverException("unknown_response_format",type);
671
//                        throw exception;
672
//        azabala                throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
673
//                }
674
//                catch (UnsupportedVersionLayerException e) {
675
//                        UnsuportedProtocolVersionExceptionType type =
676
//                                new UnsuportedProtocolVersionExceptionType();
677
//                        type.setLayerName(getName());
678
//                        try {
679
//                                type.setDriverName(getDriver().getName());
680
//                        } catch (Exception ex){
681
//                        }
682
//                        type.setUrl(host);
683
//                        throw new ReadDriverException(PluginServices.getText(this, "version_conflict"), e, type);
684

    
685
//        azabala                throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
686
                } catch (IOException e) {
687
//                        ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
688
//                        type.setLayerName(getName());
689
//                        try {
690
//                                type.setDriverName(getDriver().getName());
691
//                        } catch (Exception e1) {
692
//                        }
693
//                        type.setHost(host);
694
                        throw new ConnectionErrorLayerException(getName(),e);
695
                }
696
//                catch (WCSLayerException e) {
697
////azabala: la capturamos y la convertimos en DriverException
698
//                        WCSDriverExceptionType type = new WCSDriverExceptionType();
699
//                        type.setLayerName(getName());
700
//                        try {
701
//                                type.setDriverName(getDriver().getName());
702
//                        } catch (Exception e1) {
703
//                        }
704
//                        type.setWcsStatus(wcsStatus);
705
//                        this.setVisible(false);
706
//                        throw new WDriverException("Error WCS", e,  type);
707
//
708
////            JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
709
//
710
//        }//
711
                catch (WCSDriverException e) {
712
                        throw new LoadLayerException(getName(),e);
713
                } catch (IllegalStateException e) {
714
                        throw new LoadLayerException(getName(),e);
715
                }
716
        }
717

    
718
        /**
719
         * Devuelve el FMapWMSDriver.
720
         *
721
         * @return FMapWMSDriver
722
         *
723
         * @throws IllegalStateException
724
         * @throws ValidationException
725
         * @throws UnsupportedVersionLayerException
726
         * @throws IOException
727
         */
728
        private FMapWCSDriver getDriver() throws IllegalStateException, IOException {
729
                if (wcs == null) {
730
                        wcs = FMapWCSDriverFactory.getFMapDriverForURL(host);
731
                }
732
                return wcs;
733
        }
734

    
735
        /**
736
         * Calcula el contenido del fichero de georreferenciaci?n de una imagen.
737
         * @param bBox Tama?o y posici?n de la imagen (en coordenadas de usuario)
738
         * @param sz Tama?o de la imagen en pixeles.
739
         * @return el 'WorldFile', como String.
740
         * @throws IOException
741
         */
742
        public String getDataWorldFile(Rectangle2D bBox, Dimension sz) throws IOException {
743
                StringBuffer data = new StringBuffer();
744
            data.append((bBox.getMaxX() - bBox.getMinX())/(sz.getWidth() - 1)+"\n");
745
            data.append("0.0\n");
746
            data.append("0.0\n");
747
            data.append("-"+(bBox.getMaxY() - bBox.getMinY())/(sz.getHeight() - 1)+"\n");
748
            data.append(""+bBox.getMinX()+"\n");
749
            data.append(""+bBox.getMaxY()+"\n");
750
            return data.toString();
751
        }
752

    
753
        /**
754
         * Dibuja una imagen usando PxRaster
755
         * @param g        Graphics2D en el que hay que dibujar.
756
         * @param vpData Par?metros de visualizaci?n
757
         * @param file La imagen en cuesti?n.
758
         */
759
        private void rasterProcess(Graphics2D g, ViewPortData vpData, File file) {
760

    
761
                //Creamos el PxRaster
762
                rasterFile = new GdalFile(vpData.getProjection(), file.getAbsolutePath());
763
                raster = new PxRaster(rasterFile, null, rasterFile.getExtent());
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 ReadDriverException {
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
}