Statistics
| Revision:

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

History | View | Annotate | Download (34 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.Iterator;
62
import java.util.Map;
63

    
64
import javax.print.attribute.PrintRequestAttributeSet;
65

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

    
79
import com.iver.andami.PluginServices;
80
import com.iver.cit.gvsig.fmap.ConnectionErrorExceptionType;
81
import com.iver.cit.gvsig.fmap.DriverException;
82
import com.iver.cit.gvsig.fmap.UnknownResponseFormatExceptionType;
83
import com.iver.cit.gvsig.fmap.UnsuportedProtocolVersionExceptionType;
84
import com.iver.cit.gvsig.fmap.ViewPort;
85
import com.iver.cit.gvsig.fmap.WCSDriverExceptionType;
86
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
87
import com.iver.cit.gvsig.fmap.drivers.UnsupportedVersionException;
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.WCSException;
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 Grid                                                grid = null;
141

    
142
        private class MyCancellable implements ICancellable
143
        {
144

    
145
                private Cancellable original;
146
                public MyCancellable(Cancellable cancelOriginal)
147
                {
148
                        this.original = cancelOriginal;
149
                }
150
                public boolean isCanceled() {
151
                        return original.isCanceled();
152
                }
153
                public Object getID(){
154
                        return this;
155
                }
156

    
157
        }
158
        public FLyrWCS(){
159
                super();
160
        }
161

    
162
        public FLyrWCS(Map args) throws DriverIOException{
163
                FMapWCSDriver drv = null;
164
                String host = (String)args.get("HOST");
165
                String sCoverage = (String) args.get((String) "COVERAGE");
166

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

    
180
                try{
181
                        if (!drv.connect(false, null)){
182
                                throw new DriverIOException("Can't connect to host '" + host + "'.");
183
                        }
184
                }catch(Exception e){
185
                        throw new DriverIOException("Can't connect to host '" + host + "'.");
186
                }
187

    
188
                WCSLayer wcsNode = drv.getLayer(sCoverage);
189

    
190
                if (wcsNode == null){
191
                        throw new DriverIOException("The server '" + host + "' doesn't has the coverage '" + sCoverage + "'.");
192
                }
193

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

    
206
        }
207

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

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

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

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

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

    
265
        /*
266
         *  (non-Javadoc)
267
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getSource()
268
         */
269
        public RasterAdapter getSource() {
270
                return null;
271
        }
272

    
273
        /*
274
         *  (non-Javadoc)
275
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setSource(com.iver.cit.gvsig.fmap.layers.RasterAdapter)
276
         */
277
        public void setSource(RasterAdapter ra) {
278
        }
279

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

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

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

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

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

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

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

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

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

    
383
                        return attr;
384
                }
385
                return  null;
386
        }
387

    
388
        /*
389
         *  (non-Javadoc)
390
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxX()
391
         */
392
        public double getMaxX() {
393
                return visualStatus.maxX;
394
        }
395

    
396
        /*
397
         *  (non-Javadoc)
398
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxY()
399
         */
400
        public double getMaxY() {
401
                return visualStatus.maxY;
402
        }
403

    
404
        /*
405
         *  (non-Javadoc)
406
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinX()
407
         */
408
        public double getMinX() {
409
                return visualStatus.minX;
410
        }
411

    
412
        /*
413
         *  (non-Javadoc)
414
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinY()
415
         */
416
        public double getMinY() {
417
                return visualStatus.minY;
418
        }
419

    
420
        /*
421
         *  (non-Javadoc)
422
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getWidth()
423
         */
424
        public double getWidth() {
425
                return visualStatus.width;
426
        }
427

    
428
        /*
429
         *  (non-Javadoc)
430
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getHeight()
431
         */
432
        public double getHeight() {
433
                return visualStatus.height;
434
        }
435

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

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

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

    
469
                Point2D pReal = getMapContext().getViewPort().toMapPoint(point);
470
                Point2D px = null;
471
                if(        pReal.getX() > this.getMinX() &&
472
                        pReal.getX() < this.getMaxX() &&
473
                        pReal.getY() > this.getMinY() &&
474
                        pReal.getY() < this.getMaxY()){
475

    
476
                        px = new Point2D.Double();
477
                        double w = (visualStatus.rasterMaxX - visualStatus.rasterMinX);
478
                        double h = (visualStatus.rasterMaxY - visualStatus.rasterMinY);
479
                        px.setLocation(((pReal.getX() - visualStatus.rasterMinX) * visualStatus.rasterWidth) / w,
480
                                                        ((visualStatus.rasterMaxY - pReal.getY()) * visualStatus.rasterHeight) / h);
481
                }
482

    
483
                int[] rgb = this.getPixel(pReal.getX(), pReal.getY());
484

    
485
                StringXMLItem[] item = new StringXMLItem[1];
486

    
487
                data += "  <raster\n";
488
                data += "    View_Point=\""+point.getX()+" , "+point.getY()+"\"\n";
489
                data += "    World_Point=\""+DoubleUtilities.format(pReal.getX(), 3)+" , "+ DoubleUtilities.format(pReal.getY(), 3)+"\"\n";
490
                if(        px == null || px.getX() > visualStatus.rasterWidth || px.getX() < 0 ||
491
                                px.getY() > visualStatus.rasterHeight || px.getY() < 0)
492
                                data += "    Pixel_Point=\"Out\"\n";
493
                        else{
494
                                data += "    Pixel_Point=\""+(int)px.getX()+" , "+(int)px.getY()+"\"\n";
495
                                data += "    Band_Value=\"";
496
                                for(int file = 0; file < visualStatus.fileNames.length; file++ ){
497
                                        GdalFile rf;
498
                                        try {
499
                                                rf = new GdalFile(getMapContext().getViewPort().getProjection(), visualStatus.fileNames[file]);
500
                                        } catch (NotSupportedExtensionException e) {
501
                                                throw new DriverException("Open File Error.");
502
                                        }
503
                                        Extent ex = rf.getExtent();
504

    
505
                                        if(pReal.getX() >= ex.minX() && pReal.getX() <= ex.maxX() && pReal.getY() >= ex.minY() && pReal.getY() <= ex.maxY()){
506
                                                for(int i = 0; i < visualStatus.bandCount; i++){
507
                                                        Object pxData = rf.getData((int)px.getX(), (int)px.getY(), i);
508
                                                        if(pxData != null){
509
                                                                if(visualStatus.dataType >= 0 && visualStatus.dataType <= 3)
510
                                                                        data += ((Integer)pxData).intValue()+"  ";
511

    
512
                                                                if(visualStatus.dataType >= 4)
513
                                                                        data += ((Float)pxData).floatValue()+"  ";
514

    
515
                                                                if(visualStatus.dataType >= 5)
516
                                                                        data += ((Double)pxData).doubleValue()+"  ";
517
                                                        }
518
                                                }
519
                                        }
520
                                        rf.close();
521
                                }
522
                                data += "\"\n";
523
                        }
524

    
525
                        if(rgb != null)
526
                                data += "    RGB=\""+rgb[1]+"  "+rgb[2]+"  "+rgb[3]+"\"\n";
527

    
528
                        data += "  />\n";
529
                        data += "</file:"+getName().replaceAll("[^a-zA-Z0-9]","")+">\n";
530

    
531
                        item[0] = new StringXMLItem(data, this);
532
                        return item;
533
        }
534

    
535
        /*
536
         *  (non-Javadoc)
537
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent()
538
         */
539
        public Rectangle2D getFullExtent() {
540
                return fullExtent;
541
        }
542

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

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

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

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

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

    
609
        // 2. Compute extent to be requested.
610
        Rectangle2D bBox = new Rectangle2D.Double();
611
        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
612

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

    
620
        if ((wImg <= 0) || (hImg <= 0)) {
621
            return;
622
        }
623

    
624
                try {
625
                        sz = new Dimension(wImg, hImg);
626
                        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
627

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

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

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

    
652
                        visualStatus.fileNames[tile] = f.getAbsolutePath();
653
                        rasterProcess(g, vpData, f);
654

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

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

    
705
//            JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
706

    
707
        }//catch
708
        }
709

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

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

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

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

    
761
                if(status!=null && firstLoad){
762
                        status.applyStatus(this);
763
                        firstLoad = false;
764
                }
765

    
766
                grid = new Grid(rasterFile);
767
                grid.addRenderizer(raster);
768

    
769
                visualStatus.rasterWidth += rasterFile.getWidth();
770
                visualStatus.rasterHeight += rasterFile.getHeight();
771
                if(raster.getExtent().getMin().getX() < visualStatus.rasterMinX)
772
                        visualStatus.rasterMinX = raster.getExtent().getMin().getX();
773
                if(raster.getExtent().getMin().getY() < visualStatus.rasterMinY)
774
                        visualStatus.rasterMinY = raster.getExtent().getMin().getY();
775
                if(raster.getExtent().getMax().getX() > visualStatus.rasterMaxX)
776
                        visualStatus.rasterMaxX = raster.getExtent().getMax().getX();
777
                if(raster.getExtent().getMax().getY() > visualStatus.rasterMaxY)
778
                        visualStatus.rasterMaxY = raster.getExtent().getMax().getY();
779

    
780
                //Recuperamos la pila de filtros si ya hubiese sido cargado antes
781
                if (this.filterStack!=null)
782
                        raster.filterStack = this.filterStack;
783

    
784
                raster.setTransparency(false);
785

    
786
                //Asignamos transparencia y orden de bandas
787
                if (getTransparency() == -1 && !firstLoad);
788
                else
789
                        raster.setTransparency(getTransparency());
790

    
791
                raster.setBand(GeoRasterFile.RED_BAND,rband);
792
                raster.setBand(GeoRasterFile.GREEN_BAND, gband);
793
                raster.setBand(GeoRasterFile.BLUE_BAND, bband);
794

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

    
801
                if (visualStatus != null){
802
                        visualStatus.bandCount = raster.getBandCount();
803
                        visualStatus.dataType = raster.getDataType();
804
                }
805

    
806
                raster.draw(g, vpData);
807

    
808
                //En el primer pxRaster de una imagen obtenemos el Stack Manager para poder modificarlo
809
                //si queremos desde las propiedades
810

    
811
                if (this.stackManager == null)
812
                        this.stackManager = raster.getStackManager();
813

    
814
                if (this.filterStack == null)
815
                        this.filterStack = raster.filterStack;
816

    
817
                rasterFile.close();
818
        }
819

    
820
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet properties) throws DriverException {
821
                if (isVisible() && isWithinScale(scale)){
822
                        draw(null, g, viewPort, cancel, scale);
823
                }
824
        }
825

    
826
        /**
827
         * @return Returns the raster.
828
         */
829
        public PxRaster getPxRaster() {
830
                return raster;
831
        }
832

    
833
        /**
834
         * Returns the XMLEntity containing the necessary info for reproduce
835
         * the layer.
836
         *
837
         * Devuelve el XMLEntity con la informaci?n necesaria para reproducir
838
         * la capa.
839
         *
840
         * @return XMLEntity.
841
         * @throws XMLException
842
         */
843
        public XMLEntity getXMLEntity() throws XMLException {
844
                XMLEntity xml = super.getXMLEntity();
845

    
846
                xml.putProperty("wcs.host", getHost());
847
                xml.putProperty("wcs.fullExtent", StringUtilities.rect2String( fullExtent ));
848
                xml.putProperty("wcs.layerQuery", coverageName );
849
                xml.putProperty("wcs.format", format );
850
                xml.putProperty("wcs.srs", srs );
851
                xml.putProperty("wcs.time", time );
852
                xml.putProperty("wcs.parameter", parameter );
853
                xml.putProperty("wcs.coverageName", coverageName );
854
                xml.putProperty("wcs.maxResX", maxRes.getX());
855
                xml.putProperty("wcs.maxResY", maxRes.getY());
856

    
857
                 Iterator it = onlineResources.keySet().iterator();
858
                 String strOnlines = "";
859
                 while (it.hasNext()) {
860
                         String key = (String) it.next();
861
                         String value = (String) onlineResources.get(key);
862
                         strOnlines += key+"~##SEP2##~"+value;
863
                         if (it.hasNext())
864
                                 strOnlines += "~##SEP1##~";
865
                 }
866
                 xml.putProperty("onlineResources", strOnlines);
867

    
868
                if (status!=null)
869
                        status.getXMLEntity(xml, true, this);
870
                else{
871
                        status = new StatusLayerRaster();
872
                        status.getXMLEntity(xml, true, this);
873
                }
874
                return xml;
875
        }
876

    
877
        /**
878
         * Reproduces the layer from an XMLEntity.
879
         *
880
         * A partir del XMLEntity reproduce la capa.
881
         *
882
          * @param xml XMLEntity
883
         *
884
         * @throws XMLException
885
         * @throws DriverException
886
         * @throws DriverIOException
887
         */
888
        public void setXMLEntity(XMLEntity xml) throws XMLException {
889
                super.setXMLEntity(xml);
890

    
891
                // host
892
                try {
893
                        host = new URL(xml.getStringProperty("wcs.host"));
894
                } catch (MalformedURLException e) {
895
                        throw new XMLException(e);
896
                }
897

    
898
                // full extent
899
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty("wcs.fullExtent"));
900

    
901
                // coverageQuery
902
                coverageName = xml.getStringProperty("wcs.layerQuery");
903

    
904
                // format
905
                format = xml.getStringProperty("wcs.format");
906

    
907
                // srs
908
                srs = xml.getStringProperty("wcs.srs");
909

    
910
                // time
911
                time = xml.getStringProperty("wcs.time");
912

    
913
                // parameter
914
                parameter = xml.getStringProperty("wcs.parameter");
915

    
916
                // coverage name
917
                coverageName = xml.getStringProperty("wcs.coverageName");
918

    
919
                // max resolution
920
                if (xml.contains("wcs.maxRes"))
921
                        maxRes = new Point2D.Double(xml.getDoubleProperty("wcs.maxRes"), xml.getDoubleProperty("wcs.maxRes"));
922
                else if (xml.contains("wcs.maxResX") && xml.contains("wcs.maxResY"))
923
                        maxRes = new Point2D.Double(xml.getDoubleProperty("wcs.maxResX"), xml.getDoubleProperty("wcs.maxResY"));
924

    
925
                // OnlineResources
926
        if (xml.contains("onlineResources")) {
927
                String[] operations = xml.getStringProperty("onlineResources").split("~##SEP1##~");
928
                for (int i = 0; i < operations.length; i++) {
929
                                String[] resources = operations[i].split("~##SEP2##~");
930
                                if (resources.length==2 && resources[1]!="")
931
                                        onlineResources.put(resources[0], resources[1]);
932
                        }
933
        }
934
                String claseStr = null;
935
                if (xml.contains("raster.class")) {
936
                        claseStr = xml.getStringProperty("raster.class");
937
                }
938
                if (status!=null)
939
                        status.setXMLEntity(xml, this);
940
                else {
941
                        //Cuando cargamos un proyecto
942

    
943
                        if(claseStr!=null && !claseStr.equals("")){
944
                                try{
945
                                        Class clase = Class.forName(claseStr);
946
                                        Constructor constr = clase.getConstructor(null);
947
                                        status = (StatusRasterInterface)constr.newInstance(null);
948
                                        if(status!=null)
949
                                                status.setXMLEntity(xml, this);
950
                                } catch(ClassNotFoundException exc) {
951
                                        exc.printStackTrace();
952
                                } catch(InstantiationException exc) {
953
                                        exc.printStackTrace();
954
                                } catch(IllegalAccessException exc) {
955
                                        exc.printStackTrace();
956
                                } catch(NoSuchMethodException exc) {
957
                                        exc.printStackTrace();
958
                                } catch(InvocationTargetException exc) {
959
                                        exc.printStackTrace();
960
                                }
961
                        }
962
                }
963
                firstLoad = true;
964
        }
965

    
966
        public void setCoverageName(String coverageName) {
967
                this.coverageName = coverageName;
968
        }
969

    
970
        public void setParameter(String parametersString) {
971
                this.parameter = parametersString;
972
        }
973

    
974
        public void setTime(String time) {
975
                this.time = time;
976
        }
977

    
978
        public void setSRS(String srs) {
979
                this.srs = srs;
980
        }
981

    
982
        public void setFormat(String format) {
983
                this.format = format;
984
        }
985

    
986

    
987
        /**
988
         * Inserta el URL.
989
         *
990
         * @param host String.
991
         * @throws MalformedURLException
992
         */
993
        public void setHost(String host) {
994
                try {
995
                        setHost(new URL(host));
996
                } catch (MalformedURLException e) {
997

    
998
                }
999
        }
1000

    
1001
        /**
1002
         * Inserta el URL.
1003
         *
1004
         * @param host URL.
1005
         */
1006
        public void setHost(URL host) {
1007
                this.host = host;
1008
        }
1009

    
1010
        /**
1011
         * Sets the layer's full extent.
1012
         *
1013
         * Establece la extensi?n m?xima de la capa.
1014
         *
1015
         * @param rect
1016
         */
1017
        public void setFullExtent(Rectangle2D rect) {
1018
                this.fullExtent = rect;
1019
        }
1020

    
1021
        /**
1022
         * Devuelve el URL.
1023
         *
1024
         * @return URL.
1025
         */
1026
        public URL getHost() {
1027
                return host;
1028
        }
1029

    
1030
        /**
1031
         * Remote source layers have a bunch of properties that are required for get them from
1032
         * the servers. This method supplies a hash table containing any needed field. This hash
1033
         * table may be used to let the client to connect to a server and restore a previously saved
1034
         * layer. So, the layer itself may not be saved to the disk since the actual saved
1035
         * info is just its properties.
1036
         *
1037
         * @return Returns a hash table containing all the required information for
1038
         * set up a wms layer
1039
         */
1040
        public Hashtable getProperties(){
1041
                Hashtable info = new Hashtable();
1042
                info.put(   "name", coverageName);
1043
                info.put(   "host", getHost());
1044
                info.put(    "crs", srs);
1045
                info.put( "format", format);
1046
                String str = time;
1047
                if (str==null)
1048
                        str = "";
1049
                info.put(   "time", str);
1050
                str = parameter;
1051
                if (str==null)
1052
                        str = "";
1053
                info.put("parameter", str);
1054

    
1055
                return info;
1056
        }
1057

    
1058
        /**
1059
         * Obtiene la extensi?n del fichero de georreferenciaci?n
1060
         * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
1061
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
1062
         */
1063
        private String getExtensionWorldFile(){
1064
                String extWorldFile = ".wld";
1065
            if (format.equals("image/tif") || format.equals("image/tiff"))
1066
                    extWorldFile = ".tfw";
1067
            if (format.equals("image/jpeg"))
1068
                    extWorldFile = ".jpgw";
1069
            return extWorldFile;
1070
        }
1071

    
1072
        public void setMaxResolution(Point2D maxResolution) {
1073
                this.maxRes = maxResolution;
1074
        }
1075

    
1076
        /**
1077
         * Gets the last open GeoRasterFile against the temp file received
1078
         *
1079
         * Obtiene el ?ltimo GeoRasterFile abierto sobre el temporal recibido
1080
         * @return
1081
         */
1082
        public GeoRasterFile getGeoRasterFile(){
1083
                return rasterFile;
1084
        }
1085

    
1086

    
1087
        /**
1088
         * Asignar el estado del raster
1089
         * @param status
1090
         */
1091
        public void setStatus(StatusRasterInterface status){
1092
                this.status = status;
1093
        }
1094

    
1095
        /**
1096
         * Obtiene el estado del raster
1097
         * @return
1098
         */
1099
        public StatusRasterInterface getStatus(){
1100
                return this.status;
1101
        }
1102

    
1103
        /**
1104
         * Gets the max resolution allowed by the coverage. Requesting a higher resolution
1105
         * than this value does not cause any error, but the info responsed is just an
1106
         * interpolation.
1107
         *
1108
         * In exchange for obtaining a greater file and without additional information,
1109
         * we can easily connect it at the View.
1110
         *
1111
         *
1112
         * Obtiene la resoluci?n m?xima soportada por la cobertura. La petici?n
1113
         * de una resoluci?n superior a la soportada no provoca ning?n error, aunque
1114
         * la informaci?n obtenida s?lo es una mera interpolaci?n de informaci?n.
1115
         *
1116
         * A cambio de obtener un archivo mayor y sin informaci?n adicional, podemos
1117
         * f?cilmente acoplarlo a la vista.
1118
         *
1119
         * @return double
1120
         */
1121
        public Point2D getMaxResolution() {
1122
                if (maxRes==null)
1123
                        maxRes = wcs.getMaxResolution(coverageName);
1124
                return maxRes;
1125
        }
1126

    
1127

    
1128
        public void setDriver(FMapWCSDriver driver) {
1129
                this.wcs = driver;
1130
        }
1131

    
1132
        /*
1133
         *  (non-Javadoc)
1134
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1135
         */
1136
        public int[] getTileSize() {
1137
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1138
                return size;
1139
        }
1140

    
1141
        /*
1142
         *  (non-Javadoc)
1143
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1144
         */
1145
        public boolean isTiled() {
1146
                return mustTileDraw;
1147
        }
1148

    
1149
        /**
1150
         * Obtiene el tipo de dato de la capa raster
1151
         * @return Entero que representa el tipo de dato de la capa raster.
1152
         */
1153
        public int getDataType() {
1154
                return rasterFile.getDataType();
1155
        }
1156

    
1157
        /**
1158
         * Obtiene el grid asociado al raster que hay cargado en ese momento
1159
         * @return grid
1160
         */
1161
        public Grid getGrid(){
1162
                return grid;
1163
        }
1164
}