Statistics
| Revision:

svn-gvsig-desktop / tags / v1_0_2_Build_898 / extensions / extWMS / src / com / iver / cit / gvsig / fmap / layers / FLyrWMS.java @ 10513

History | View | Annotate | Download (55.5 KB)

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

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

    
68
import javax.imageio.ImageIO;
69
import javax.print.attribute.PrintRequestAttributeSet;
70
import javax.swing.ImageIcon;
71
import javax.swing.JOptionPane;
72

    
73
import org.cresques.filter.RasterFilterStack;
74
import org.cresques.filter.RasterFilterStackManager;
75
import org.cresques.geo.ViewPortData;
76
import org.cresques.io.GdalFile;
77
import org.cresques.io.GeoRasterFile;
78
import org.cresques.io.data.Grid;
79
import org.cresques.io.exceptions.NotSupportedExtensionException;
80
import org.cresques.px.Extent;
81
import org.cresques.px.PxRaster;
82
import org.exolab.castor.xml.ValidationException;
83
import org.gvsig.remoteClient.utils.Utilities;
84
import org.gvsig.remoteClient.wms.ICancellable;
85
import org.gvsig.remoteClient.wms.WMSStatus;
86

    
87
import com.iver.andami.PluginServices;
88
import com.iver.andami.messages.NotificationManager;
89
import com.iver.cit.gvsig.fmap.ConnectionErrorExceptionType;
90
import com.iver.cit.gvsig.fmap.DriverException;
91
import com.iver.cit.gvsig.fmap.UnknownResponseFormatExceptionType;
92
import com.iver.cit.gvsig.fmap.UnsuportedProtocolVersionExceptionType;
93
import com.iver.cit.gvsig.fmap.ViewPort;
94
import com.iver.cit.gvsig.fmap.WMSDriverExceptionType;
95
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
96
import com.iver.cit.gvsig.fmap.drivers.UnsupportedVersionException;
97
import com.iver.cit.gvsig.fmap.drivers.wms.FMapWMSDriver;
98
import com.iver.cit.gvsig.fmap.drivers.wms.FMapWMSDriverFactory;
99
import com.iver.cit.gvsig.fmap.drivers.wms.WMSException;
100
import com.iver.cit.gvsig.fmap.layers.WMSLayerNode.FMapWMSStyle;
101
import com.iver.cit.gvsig.fmap.layers.layerOperations.IHasImageLegend;
102
import com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint;
103
import com.iver.cit.gvsig.fmap.layers.layerOperations.StringXMLItem;
104
import com.iver.cit.gvsig.fmap.layers.layerOperations.XMLItem;
105
import com.iver.cit.gvsig.fmap.rendering.XmlBuilder;
106
import com.iver.cit.gvsig.wmc.WebMapContextTags;
107
import com.iver.utiles.StringUtilities;
108
import com.iver.utiles.XMLEntity;
109
import com.iver.utiles.swing.threads.Cancellable;
110

    
111

    
112

    
113
/**
114
* FMap's WMS Layer class.
115
*
116
* @author Jaume Dominguez Faus
117
*                   Nacho Brodin
118
*
119
*/
120
public class FLyrWMS extends FLyrDefault implements InfoByPoint, RasterOperations, IHasImageLegend {
121
        private boolean                                         isPrinting = false;
122
        private boolean                                         mustTileDraw = true;
123
        private boolean                                         mustTilePrint = true;
124
        private final int                                         maxTileDrawWidth = 1023;
125
        private final int                                         maxTileDrawHeight = 1023;
126
        private final int                                         maxTilePrintWidth = 1023;
127
        private final int                                         maxTilePrintHeight = 1023;
128
        private final int                                        minTilePrintWidth = 12;
129
        private final int                                        minTilePrintHeight = 12;
130

    
131
    public URL                                                         host;
132
    public String                                                 m_Format;
133

    
134
        private String                                                 m_SRS;
135
        private String                                                 layerQuery;
136
        private String                                                 infoLayerQuery;
137
        private FMapWMSDriver                                 wms;
138
        private WMSStatus                                         wmsStatus = new WMSStatus();
139
        private Rectangle2D                                 fullExtent;
140
        private boolean                                                wmsTransparency;
141
    private Vector                                                 styles;
142
    private Vector                                                 dimensions;
143
        private StatusRasterInterface                status = null;
144
        private int                                                 posX = 0, posY = 0;
145
        private double                                                 posXWC = 0, posYWC = 0;
146
        private int                                                 r = 0, g = 0, b = 0;
147
        private GeoRasterFile                                 rasterFile = null;
148
        private PxRaster                                         raster = null;
149
        private RasterFilterStack                         filterStack = null;
150
        private boolean                                                firstLoad = false;
151
        private int                                                 transparency = -1;
152
        private int                                                 rband = 0, gband = 1, bband = 2;
153
        private RasterFilterStackManager        stackManager = null;
154
        private Hashtable                                         onlineResources = new Hashtable();
155
        private Dimension                                         fixedSize;
156
        private boolean                                         queryable = true;
157
        private VisualStatusWMS                                visualStatus = new VisualStatusWMS();
158
        private Grid                                                grid = null;
159

    
160

    
161
        private class MyCancellable implements ICancellable
162
        {
163
                private Cancellable original;
164
                public MyCancellable(Cancellable cancelOriginal)
165
                {
166
                        this.original = cancelOriginal;
167
                }
168
                public boolean isCanceled() {
169
                        if (original == null) return false;
170
                        return original.isCanceled();
171
                }
172

    
173
        }
174

    
175
        public FLyrWMS(){
176
                super();
177
        }
178

    
179
        public FLyrWMS(Map args) throws DriverIOException{
180
                FMapWMSDriver drv = null;
181
                String host = (String)args.get("host");
182
                String sLayer = (String)args.get("layer");
183
                Rectangle2D fullExtent = (Rectangle2D)args.get("FullExtent");
184
                String sSRS = (String)args.get("SRS");
185
                String sFormat = (String)args.get("Format");
186
                String[] sLayers = sLayer.split(",");
187

    
188
                try {
189
                        this.setHost(new URL(host));
190
                } catch (MalformedURLException e) {
191
                        //e.printStackTrace();
192
                        throw new DriverIOException("Malformed host URL, '" + host + "' (" + e.toString() + ").");
193
                }
194
                try {
195
                        drv = this.getDriver();                        
196
                } catch (Exception e) {
197
                        // e.printStackTrace();
198
                        throw new DriverIOException("Can't get driver to host '" + host + "' (" + e.toString() + ").");
199
                }
200
                if( sFormat == null || sSRS == null || fullExtent == null ) {
201
                        if (!drv.connect(null))
202
                                throw new DriverIOException("Can't connect to host '" + host + "'.");
203

    
204
                        WMSLayerNode wmsNode = drv.getLayer(sLayer);
205
                        
206
                        if (wmsNode == null){
207
                                throw new DriverIOException("The server '" + host + "' doesn't has the layer '" + sLayer + "'.");
208
                        }
209
                        if( sFormat == null ) {
210
                                sFormat = this.getGreatFormat(drv.getFormats());
211
                        }
212
                        
213
                        //SRS
214
                        Vector allSrs = wmsNode.getAllSrs();
215
                        boolean isSRSSupported = false;
216
                        if( sSRS != null ) {
217
                                for (int i=0; i<allSrs.size() ; i++){
218
                                     if (((String)allSrs.get(i)).compareTo(sSRS) == 0){
219
                                             isSRSSupported = true;
220
                                     }                                     
221
                             }
222
                        }
223
                        
224
                     if(!isSRSSupported) {
225
                             for (int i=0; i<allSrs.size() ; i++){
226
                                     if (((String)wmsNode.getAllSrs().get(i)).compareTo("EPSG:4326") == 0){
227
                                             sSRS = (String)wmsNode.getAllSrs().get(i);
228
                                     }                                     
229
                             }
230
                             if (sSRS==null){
231
                                     sSRS = (String)wmsNode.getAllSrs().get(0);
232
                             }
233
                     }
234
                        if( fullExtent == null ) {
235
                                fullExtent = drv.getLayersExtent(sLayers,sSRS);
236
                        }
237
                }
238

    
239

    
240
                this.setFullExtent(fullExtent);
241
                this.setFormat(sFormat);
242
                this.setLayerQuery(sLayer);
243
                this.setInfoLayerQuery("");
244
                this.setSRS(sSRS);
245
                this.setName(sLayer);
246
                this.setOnlineResources(drv.getOnlineResources());
247
                load();
248
        }
249

    
250
        /**
251
         * It choose the best format to load different maps if the server
252
         * supports it. This format could be png, because it supports
253
         * transparency.
254
         * @param formats
255
         * Arraywith all the formats supported by the server
256
         * @return
257
         */
258
        private String getGreatFormat(Vector formats){
259
            for (int i=0 ; i<formats.size() ; i++){
260
                String format = (String) formats.get(i);
261
                    if (format.equals("image/jpg")){
262
                    return format;
263
                    }
264
                    if (format.equals("image/jpeg")){
265
                    return format;
266
                    }
267
            }
268

    
269
            return (String)formats.get(0);
270
        }
271

    
272
        /**
273
         * Clase que contiene los datos de visualizaci?n de WMS. Tiene datos que representan al
274
         * raster en la vista. Este raster puede estar compuesto por tiles por lo que valores 
275
         * como el ancho total o el m?nimo o m?ximo deben ser calculados a partir de todos los
276
         * tiles visualizados.
277
         * @author Nacho Brodin (brodin_ign@gva.es)
278
         */
279
        private class VisualStatusWMS{
280
                /**
281
                 * Ancho y alto de la imagen o del conjunto de tiles si los tiene. Coincide con
282
                 * el ancho y alto del viewPort
283
                 */
284
                private        int                                                        width = 0, height = 0;
285
                private double                                                minX = 0D, minY = 0D, maxX = 0D, maxY = 0D;
286
                private int                                                 bandCount = 0;
287
                private int                                                        dataType = DataBuffer.TYPE_UNDEFINED;
288

    
289
                /**
290
                 * Ancho y alto total del raster que ser? la suma de todos los tiles.
291
                 */
292
                private        int                                                        rasterWidth = 0, rasterHeight = 0;
293
                private        double                                                rasterMinX = Double.MAX_VALUE, rasterMinY = Double.MAX_VALUE;
294
                private        double                                                rasterMaxX = 0, rasterMaxY = 0;
295
                /**
296
                 * Lista de nombre de fichero que componen toda la visualizaci?n.
297
                 */
298
                private String[]                                        fileNames = null;
299
        }
300

    
301

    
302
        /**
303
         * Devuelve el XMLEntity con la informaci?n necesaria para reproducir la
304
         * capa.
305
         *
306
         * @return XMLEntity.
307
         * @throws XMLException
308
         */
309
        public XMLEntity getXMLEntity() throws XMLException {
310
                XMLEntity xml = super.getXMLEntity();
311

    
312
                // Full extent
313
                xml.putProperty("fullExtent", StringUtilities.rect2String(fullExtent));
314

    
315
                // Host
316
                xml.putProperty("host", host.toExternalForm());
317

    
318
                // Part of the query that is not the host, or the
319
                // layer names, or other not listed bellow
320
                xml.putProperty("infoLayerQuery", infoLayerQuery);
321

    
322
                // Part of the query containing the layer names
323
                xml.putProperty("layerQuery", layerQuery);
324

    
325
                // Format
326
                xml.putProperty("format", m_Format);
327

    
328
                // SRS
329
                xml.putProperty("srs", m_SRS);
330
                if (status!=null)
331
                        status.getXMLEntity(xml, true, this);
332
                else{
333
                        status = new StatusLayerRaster();
334
                        status.getXMLEntity(xml, true, this);
335
                }
336

    
337
        // Transparency
338
        xml.putProperty("wms_transparency", wmsTransparency);
339

    
340
        // Styles
341
        if (styles!=null){
342
            String stylePr = "";
343
            for (int i = 0; i < styles.size(); i++) {
344
                stylePr += (String) styles.get(i);
345
                if (i<styles.size()-1)
346
                    stylePr += ",";
347
            }
348
            if (stylePr.endsWith(","))
349
                    stylePr += " ";
350
            xml.putProperty("styles", stylePr);
351
        }
352

    
353
        // Dimensions
354
        if (dimensions!=null){
355
            String dim = "";
356
            for (int i = 0; i < dimensions.size(); i++) {
357
                dim += (String) dimensions.get(i);
358
                if (i<dimensions.size()-1)
359
                    dim += ",";
360
            }
361
            if (dim.endsWith(","))
362
                    dim += " ";
363
            xml.putProperty("dimensions", dim);
364
        }
365

    
366
        // OnlineResources
367
        Iterator it = onlineResources.keySet().iterator();
368
        String strOnlines = "";
369
        while (it.hasNext()) {
370
                String key = (String) it.next();
371
                String value = (String) onlineResources.get(key);
372
                strOnlines = key+"~##SEP2##~"+value;
373
                if (it.hasNext())
374
                        strOnlines += "~##SEP1##~";
375
        }
376
        xml.putProperty("onlineResources", strOnlines);
377

    
378
        // Queryable
379
        xml.putProperty("queryable", queryable);
380

    
381
        // fixedSize
382
        if (isSizeFixed()) {
383
                xml.putProperty("fixedSize", true);
384
                xml.putProperty("fixedWidth", fixedSize.width);
385
                xml.putProperty("fixedHeight", fixedSize.height);
386
        }
387
        return xml;
388
        }
389

    
390
        /**
391
         * A partir del XMLEntity reproduce la capa.
392
         *
393
         * @param xml XMLEntity
394
         *
395
         * @throws XMLException
396
         * @throws DriverException
397
         * @throws DriverIOException
398
         */
399
        public void setXMLEntity03(XMLEntity xml)
400
                throws XMLException {
401
                super.setXMLEntity(xml);
402
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty(
403
                                        "fullExtent"));
404

    
405
                try {
406
                        host = new URL(xml.getStringProperty("host"));
407
                } catch (MalformedURLException e) {
408
                        throw new XMLException(e);
409
                }
410

    
411
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
412
                layerQuery = xml.getStringProperty("layerQuery");
413
                m_Format = xml.getStringProperty("format");
414
                m_SRS = xml.getStringProperty("srs");
415
        }
416

    
417
        /**
418
         * A partir del XMLEntity reproduce la capa.
419
         *
420
         * @param xml XMLEntity
421
         *
422
         * @throws XMLException
423
         * @throws DriverException
424
         * @throws DriverIOException
425
         */
426
        public void setXMLEntity(XMLEntity xml)
427
                throws XMLException {
428
                super.setXMLEntity(xml);
429
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty(
430
                                        "fullExtent"));
431

    
432
                // Host
433
                try {
434
                        host = new URL(xml.getStringProperty("host"));
435
                } catch (MalformedURLException e) {
436
                        throw new XMLException(e);
437
                }
438

    
439
                // Part of the query that is not the host, or the
440
                // layer names, or other not listed bellow
441
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
442

    
443
                // Part of the query containing the layer names
444
                layerQuery = xml.getStringProperty("layerQuery");
445

    
446
                // Format
447
                m_Format = xml.getStringProperty("format");
448

    
449
                // SRS
450
                m_SRS = xml.getStringProperty("srs");
451

    
452
                String claseStr = StatusLayerRaster.defaultClass;
453
                if (xml.contains("raster.class")) {
454
                        claseStr = xml.getStringProperty("raster.class");
455
                }
456

    
457
                // Transparency
458
        if (xml.contains("wms_transparency"))
459
            wmsTransparency = xml.getBooleanProperty("wms_transparency");
460

    
461
        // Styles
462
        if (xml.contains("styles")){
463
            styles = new Vector();
464
            String[] stl = xml.getStringProperty("styles").split(",");
465

    
466
            for (int i = 0; i < stl.length; i++) {
467
                    if (stl[i].equals(" "))
468
                            stl[i]="";
469
                styles.add(stl[i]);
470
            }
471
        }
472

    
473
        // Dimensions
474
        if (xml.contains("dimensions")){
475
            dimensions = new Vector();
476
            String[] dims = xml.getStringProperty("dimensions").split(",");
477
            for (int i = 0; i < dims.length; i++){
478
                    if (dims[i].equals(" "))
479
                            dims[i]="";
480

    
481
                dimensions.add(dims[i]);
482
            }
483
        }
484

    
485
        // OnlineResources
486
        if (xml.contains("onlineResources")) {
487
                String[] operations = xml.getStringProperty("onlineResources").split("~##SEP1##~");
488
                for (int i = 0; i < operations.length; i++) {
489
                                String[] resources = operations[i].split("~##SEP2##~");
490
                                if (resources.length==2 && resources[1]!="")
491
                                        onlineResources.put(resources[0], resources[1]);
492
                        }
493
        }
494

    
495
        // Queryable
496
        queryable = true; // let's assume that the layer is queryable by default
497
        if (xml.contains("queryable"))
498
                queryable = xml.getBooleanProperty("queryable");
499

    
500
        // fixedSize
501
        if (xml.contains("fixedSize")) {
502
                fixedSize = new Dimension(xml.getIntProperty("fixedWidth"),
503
                                                  xml.getIntProperty("fixedHeight"));
504
        }
505

    
506
                if(status!=null)
507
                        status.setXMLEntity(xml, this);
508
                else{
509
                        if(claseStr!=null && !claseStr.equals("")){
510
                                try{
511
                                        Class clase = Class.forName(claseStr);
512
                                        Constructor constr = clase.getConstructor(null);
513
                                        status = (StatusRasterInterface)constr.newInstance(null);
514
                                        if(status!=null)
515
                                                status.setXMLEntity(xml, this);
516
                                }catch(ClassNotFoundException exc){
517
                                        exc.printStackTrace();
518
                                }catch(InstantiationException exc){
519
                                        exc.printStackTrace();
520
                                }catch(IllegalAccessException exc){
521
                                        exc.printStackTrace();
522
                                }catch(NoSuchMethodException exc){
523
                                        exc.printStackTrace();
524
                                }catch(InvocationTargetException exc){
525
                                        exc.printStackTrace();
526
                                }
527
                        }
528
                }
529
                firstLoad = true;
530
        }
531

    
532
        /**
533
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(com.iver.cit.gvsig.fmap.operations.QueriedPoint)
534
         */
535
        public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancellable) throws DriverException {
536
                XMLItem[] item =  new XMLItem[1];
537
                try {
538
                        if (queryable)
539
                        {
540
                                //TODO
541
                                // check if there are layers which are not queryable
542
                                ViewPort viewPort = getMapContext().getViewPort();
543

    
544
                                Point tiledPoint = new Point((int) p.getX() % maxTilePrintWidth, (int) p.getY() % maxTilePrintHeight);
545
                                Rectangle rect = new Rectangle(0, 0, viewPort.getImageWidth() - 1, viewPort.getImageHeight() - 1);
546
                                Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, rect);
547
                                tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
548
                                int nCols = tiles.getNumCols();
549

    
550
                                int col = (int) p.getX() / maxTilePrintWidth;
551
                                int row = (int) p.getY() / maxTilePrintHeight;
552
                                int tileIndex = (row*nCols) + col;
553

    
554
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileIndex);
555
                                wmsStatus.setExtent(vp.getAdjustedExtent());
556
                                wmsStatus.setHeight(vp.getImageHeight());
557
                                wmsStatus.setWidth(vp.getImageWidth());
558
                                wmsStatus.setOnlineResource((String) onlineResources.get("GetFeatureInfo"));
559
                                MyCancellable c = new MyCancellable(cancellable);
560
                                item[0] = new StringXMLItem(new String(getDriver()
561
                                                .getFeatureInfo(wmsStatus, (int) tiledPoint.getX(), (int) tiledPoint.getY(), Integer.MAX_VALUE, c)),this);
562
                                return item;
563
                        }
564
                        else
565
                        {
566
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),this.getName() + " " +
567
                                                PluginServices.getText(this,"layer_not_queryable"));
568
                                item[0] =  new StringXMLItem("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><info></info>",this);
569
                                return item;
570
                                //return null;
571
                        }
572
                } catch (WMSException  e) {
573
                        item[0] = new StringXMLItem("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><exception>" +
574
                        e.getMessage() + "</exception>", this);
575
                        return item;
576
                }
577
                /*azabala
578
                catch (ValidationException e) {
579
                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
580
                } catch (UnsupportedVersionException e) {
581
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
582
                } catch (IOException e) {
583
                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
584
                }
585
                */
586
                catch (ValidationException e) {
587
                        UnknownResponseFormatExceptionType type =
588
                                new UnknownResponseFormatExceptionType();
589
                        type.setLayerName(getName());
590
                        try {
591
                                type.setDriverName("WMS Driver");
592
                        } catch (Exception e1) {
593
                                e1.printStackTrace();
594
                        }
595
                        type.setFormat(m_Format);
596
                        type.setHost(host);
597
                        type.setProtocol("WMS");
598
                        DriverException exception = new DriverException("unknown_response_format", type);
599
                        throw exception;
600

    
601
                } catch (UnsupportedVersionException e) {
602
                        UnsuportedProtocolVersionExceptionType type =
603
                                new UnsuportedProtocolVersionExceptionType();
604
                        type.setLayerName(getName());
605
                        try {
606
                                type.setDriverName("WMS Driver");
607
                        } catch (Exception ex){
608
                        }
609
                        type.setUrl(host);
610
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e, type);
611

    
612
                } catch (IOException e) {
613
                        ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
614
                        type.setLayerName(getName());
615
                        try {
616
                                type.setDriverName("WMS Driver");
617
                        } catch (Exception e1) {
618
                        }
619
                        type.setHost(host);
620
                        throw new DriverException(PluginServices.
621
                                        getText(this, "connect_error"), e, type);
622
                }
623
                catch (NoninvertibleTransformException e) {
624
                        NotificationManager.addError("NotinvertibleTransform", e);
625
                }
626
                return null;
627
        }
628

    
629
        /**
630
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent()
631
         */
632
        public Rectangle2D getFullExtent() {
633
                return fullExtent;
634
        }
635

    
636
        /**
637
         *
638
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#draw(java.awt.image.BufferedImage,
639
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
640
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
641
         */
642
        private int callCount; // mess code, represents the amount of times the methods drawFixedSize or drawTile where tried for an extent
643
        private static final int MAX_RETRY_TIMES = 5; // mess code, represents the max amount of retries allowed.
644
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
645
                        Cancellable cancel,double scale) throws DriverException {
646
                callCount = 0; // mess code
647
                if (isWithinScale(scale)){
648
                        Point2D p = viewPort.getOffset();
649
                        // p will be (0, 0) when drawing a view or other when painting onto
650
                        // the Layout.
651
                        visualStatus.width =  viewPort.getImageWidth();
652
                        visualStatus.height =  viewPort.getImageHeight();
653
                        visualStatus.minX = viewPort.getAdjustedExtent().getMinX();
654
                        visualStatus.minY = viewPort.getAdjustedExtent().getMinY();
655
                        visualStatus.maxX = viewPort.getAdjustedExtent().getMaxX();
656
                        visualStatus.maxY = viewPort.getAdjustedExtent().getMaxY();
657

    
658

    
659
                        if (isSizeFixed()) {
660
                                // This condition handles those situations in which the server can
661
                                // only give static extent and resolution maps despite we need
662
                                // a specific BBOX and pixel WIDTH and HEIGHT
663
                                drawFixedSize(g, viewPort, cancel);
664

    
665
                        } else {
666
                                if(mustTileDraw){
667
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), viewPort.getImageWidth(), viewPort.getImageHeight());
668
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
669
                                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
670
                                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
671
                                                // drawing part
672
                                                try {
673
                                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
674
                                                        drawTile(g, vp, cancel);
675
                                                } catch (NoninvertibleTransformException e) {
676
                                                        e.printStackTrace();
677
                                                }
678
                                        }
679
                                }else
680
                                        drawTile(g, viewPort, cancel);
681
                        }
682
                }
683
//                Runtime r = Runtime.getRuntime();
684
//                long mem = r.totalMemory() - r.freeMemory();
685
//                System.err.println("Memoria total: " + (mem / 1024) +"KB");
686
        }
687

    
688
        private void drawFixedSize(Graphics2D g, ViewPort vp, Cancellable cancel) throws DriverException {
689
                callCount++; // mess code, it is not unusual a wms server to response an error which is completely
690
                                         // temporal and the response is available if we retry requesting.
691
                                         //
692

    
693

    
694
                // This is the extent that will be requested
695
                Rectangle2D bBox = getFullExtent();
696
                MyCancellable c = new MyCancellable(cancel);
697

    
698
                try {
699
                        wmsStatus.setExtent( bBox );
700
                        wmsStatus.setFormat( m_Format );
701
                        wmsStatus.setHeight( fixedSize.height );
702
                        wmsStatus.setWidth( fixedSize.width );
703
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
704
                        wmsStatus.setSrs(m_SRS);
705
                        wmsStatus.setStyles(styles);
706
                        wmsStatus.setDimensions(dimensions);
707
                        wmsStatus.setTransparency(wmsTransparency);
708
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
709
                        File f = getDriver().getMap(wmsStatus, c);
710
                        if (f == null)
711
                                return;
712
                        String nameWorldFile = f.getPath() + getExtensionWorldFile();
713
                        com.iver.andami.Utilities.createTemp(nameWorldFile, this.getDataWorldFile(bBox, fixedSize));
714

    
715
                        if(status!=null && firstLoad){
716
                                status.applyStatus(this);
717
                                firstLoad = false;
718
                        }
719

    
720
                        // And finally, obtain the extent intersecting the view and the BBox
721
                        // to draw to.
722
                        Rectangle2D extent = new Rectangle2D.Double();
723
                        Rectangle2D.intersect(vp.getAdjustedExtent(), bBox, extent);
724

    
725
                        ViewPortData vpData = new ViewPortData(
726
                                vp.getProjection(), new Extent(extent), fixedSize );
727
                        vpData.setMat(vp.getAffineTransform());
728

    
729
                        rasterProcess(g, vpData, f);
730

    
731
                } catch (ValidationException e) {
732
                        if (!c.isCanceled())
733
                        {
734
                                UnknownResponseFormatExceptionType type =
735
                                        new UnknownResponseFormatExceptionType();
736
                                type.setLayerName(getName());
737
                                try {
738
                                        type.setDriverName("WMS Driver");
739
                                } catch (Exception e1) {
740
                                        e1.printStackTrace();
741
                                }
742
                                type.setFormat(m_Format);
743
                                type.setHost(host);
744
                                type.setProtocol("WMS");
745
                                DriverException exception = new DriverException("unknown_response_format", type);
746
                                throw exception;
747
                        }
748
//        azabala                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
749
                } catch (UnsupportedVersionException e) {
750
                        if (!c.isCanceled()){
751
                                UnsuportedProtocolVersionExceptionType type =
752
                                        new UnsuportedProtocolVersionExceptionType();
753
                                type.setLayerName(getName());
754
                                try {
755
                                        type.setDriverName("WMS Driver");
756
                                } catch (Exception ex){
757
                                }
758
                                type.setUrl(host);
759
                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e, type);
760
                        }
761
//        azabala                throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
762
                } catch (IOException e) {
763
                        if (!c.isCanceled())
764
                                if (callCount<MAX_RETRY_TIMES) { // mess code
765
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
766
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
767
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
768
                                        drawFixedSize(g, vp, cancel); // mess code
769
                                } // mess code
770

    
771
                                if (callCount == 1) { // mess code
772
                                        ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
773
                                        type.setLayerName(getName());
774
                                        try {
775
                                                type.setDriverName("WMS Driver");
776
                                        } catch (Exception e1) {
777
                                        }
778
                                        type.setHost(host);
779
                                        throw new DriverException(PluginServices.
780
                                                        getText(this, "connect_error"), e, type);
781
//        azabala        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
782
                                } // mess code
783

    
784

    
785
                } catch (WMSException e) {
786
                        if (!c.isCanceled()) {
787
                                if (callCount<MAX_RETRY_TIMES) { // mess code
788
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
789
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
790
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
791
                                        drawFixedSize(g, vp, cancel); // mess code
792
                                } // mess code
793
                                if (callCount == 1) { // mess code
794
//                azabala                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
795
                                        WMSDriverExceptionType type = new WMSDriverExceptionType();
796
                                        type.setLayerName(getName());
797
                                        try {
798
                                                type.setDriverName("WMS Driver");
799
                                        } catch (Exception e1) {
800
                                        }
801
                                        type.setWcsStatus(this.wmsStatus);
802
                                        if (!isPrinting)
803
                                                this.setVisible(false);
804
                                        throw new DriverException("Error WMS", e,  type);
805

    
806

    
807
                                } // mess code
808
                        }
809
                }
810
                callCount--; // mess code
811
        }
812

    
813
        /**
814
         * This is the method used to draw a tile in a WMS mosaic layer.
815
         */
816
        private void drawTile(Graphics2D g, ViewPort vp, Cancellable cancel) throws DriverException {
817
                callCount++;
818
                // Compute the query geometry
819
                // 1. Check if it is within borders
820
                Rectangle2D extent = getFullExtent();
821
        if ((vp.getAdjustedExtent().getMinX() > extent.getMaxX()) ||
822
                (vp.getAdjustedExtent().getMinY() > extent.getMaxY()) ||
823
                (vp.getAdjustedExtent().getMaxX() < extent.getMinX()) ||
824
                (vp.getAdjustedExtent().getMaxY() < extent.getMinY())) {
825
            return;
826
        }
827

    
828
        // 2. Compute extent to be requested.
829
        Rectangle2D bBox = new Rectangle2D.Double();
830
        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
831

    
832
        // 3. Compute size in pixels
833
        double scalex = vp.getAffineTransform().getScaleX();
834
        double scaley = vp.getAffineTransform().getScaleY();
835
        int wImg = (int) Math.ceil(Math.abs(bBox.getWidth() * scalex) + 1);
836
        int hImg = (int) Math.ceil(Math.abs(bBox.getHeight() * scaley) + 1);
837

    
838
        Dimension sz = new Dimension(wImg, hImg);
839

    
840
        if ((wImg <= 0) || (hImg <= 0)) {
841
            return;
842
        }
843
        MyCancellable c = new MyCancellable(cancel);
844

    
845
                try {
846
//                        wImg = vp.getImageWidth();
847
//                        hImg = vp.getImageHeight();
848
                        sz = new Dimension(wImg, hImg);
849
                        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
850

    
851

    
852
                        wmsStatus.setExtent( bBox );
853
                        wmsStatus.setFormat(m_Format);
854
                        wmsStatus.setHeight( hImg );
855
                        wmsStatus.setWidth( wImg );
856
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
857
                        wmsStatus.setSrs(m_SRS);
858
                        wmsStatus.setStyles(styles);
859
                        wmsStatus.setDimensions(dimensions);
860
                        wmsStatus.setTransparency(wmsTransparency);
861
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
862

    
863
                        // begin patch; Avoid to request too small tiles.
864
                        // This generally occurs when printing
865

    
866
                        if (wImg < minTilePrintWidth) {
867
                                double wScale = (double) minTilePrintWidth / wImg;
868
                                wmsStatus.setWidth(minTilePrintWidth);
869
                                Rectangle2D sExtent = wmsStatus.getExtent();
870
                                Point2D initialPoint = new Point2D.Double(sExtent.getX(), sExtent.getY());
871
                                sExtent.setRect(sExtent.getX()*wScale, sExtent.getY(), sExtent.getWidth()*wScale, sExtent.getHeight());
872
                                if (!bBox.contains(initialPoint)) {
873
                                        sExtent.setRect(sExtent.getX() - initialPoint.getX(), sExtent.getY(), sExtent.getWidth(), sExtent.getHeight());
874
                                }
875
                        }
876

    
877
                        if (hImg < minTilePrintHeight) {
878
                                double hScale = (double) minTilePrintHeight / hImg;
879
                                wmsStatus.setHeight(minTilePrintHeight);
880
                                Rectangle2D sExtent = wmsStatus.getExtent();
881
                                Point2D initialPoint = new Point2D.Double(sExtent.getX(), sExtent.getY());
882
                                sExtent.setRect(sExtent.getX(), sExtent.getY()*hScale, sExtent.getWidth(), sExtent.getHeight()*hScale);
883
                                if (!bBox.contains(initialPoint)) {
884
                                        sExtent.setRect(sExtent.getX(), sExtent.getY() - initialPoint.getY(), sExtent.getWidth(), sExtent.getHeight());
885
                                }
886
                        }
887

    
888
                        // end patch
889
                        File f = getDriver().getMap(wmsStatus, c);
890
                        if (f == null)
891
                                return;
892
                        String nameWordFile = f.getPath() + getExtensionWorldFile();
893
                        com.iver.andami.Utilities.createTemp(nameWordFile, this.getDataWorldFile(bBox, sz));
894

    
895
                        ViewPortData vpData = new ViewPortData(
896
                                vp.getProjection(), new Extent(bBox), sz );
897
                        vpData.setMat(vp.getAffineTransform());
898

    
899
                        rasterProcess(g, vpData, f);
900

    
901
                } catch (ValidationException e) {
902
                //azabala
903
//                        if (!c.isCanceled())
904
//                                throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
905

    
906
                        if (!c.isCanceled())
907
                        {
908
                                UnknownResponseFormatExceptionType type =
909
                                        new UnknownResponseFormatExceptionType();
910
                                type.setLayerName(getName());
911
                                try {
912
                                        type.setDriverName("WMS Driver");
913
                                } catch (Exception e1) {
914
                                        e1.printStackTrace();
915
                                }
916
                                type.setFormat(m_Format);
917
                                type.setHost(host);
918
                                type.setProtocol("WMS");
919
                                DriverException exception = new DriverException("unknown_response_format", type);
920
                                throw exception;
921
                        }
922
                } catch (UnsupportedVersionException e) {
923

    
924
//                        if (!c.isCanceled())
925
//                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
926

    
927
                        if (!c.isCanceled()){
928
                                UnsuportedProtocolVersionExceptionType type =
929
                                        new UnsuportedProtocolVersionExceptionType();
930
                                type.setLayerName(getName());
931
                                try {
932
                                        type.setDriverName("WMS Driver");
933
                                } catch (Exception ex){
934
                                }
935
                                type.setUrl(host);
936
                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e, type);
937
                        }
938

    
939
                } catch (IOException e) {
940
                        /*azabala
941
                        if (!c.isCanceled())
942
                                if (callCount<MAX_RETRY_TIMES) {
943
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null);
944
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error
945
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0)
946
                                        drawTile(g, vp, cancel);
947
                                }
948
                                if (callCount == 1) {
949
                                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
950
                                }
951
                        */
952
                        if (!c.isCanceled()){
953
                                if (callCount<MAX_RETRY_TIMES) { // mess code
954
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
955
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
956
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
957

    
958
                                        //FIXME Aqu? deberiamos llamar a drawTile o a drawFixedSize????
959
                                        drawFixedSize(g, vp, cancel); // mess code
960
                                } // mess code
961
                        }
962
                        if (callCount == 1) { // mess code
963
                                ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
964
                                type.setLayerName(getName());
965
                                try {
966
                                        type.setDriverName("WMS Driver");
967
                                } catch (Exception e1) {}
968
                                type.setHost(host);
969
                                throw new DriverException(PluginServices.
970
                                                        getText(this, "connect_error"), e, type);
971
                        }//if
972
                } catch (WMSException e) {
973
                        /*azabala
974
                        if (!c.isCanceled()) {
975
                                if (callCount<MAX_RETRY_TIMES) {
976
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawTile() ] Failed in trying " + callCount + "/" + MAX_RETRY_TIMES +" \n", null);
977
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error
978
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0)
979
                                        drawTile(g, vp, cancel);
980
                                }
981
                                if (callCount == 1) {
982
                                        if (!isPrinting) {
983
                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
984
                                                this.setVisible(false);
985
                                        }
986
                                }
987
                        }
988
                        */
989
                        if (!c.isCanceled()) {
990
                                if (callCount<MAX_RETRY_TIMES) { // mess code
991
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
992
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
993
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
994
                                        drawTile(g, vp, cancel);
995
                                } // mess code
996
                                if (callCount == 1) { // mess code
997
//                azabala                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
998
                                        WMSDriverExceptionType type = new WMSDriverExceptionType();
999
                                        type.setLayerName(getName());
1000
                                        try {
1001
                                                type.setDriverName("WMS Driver");
1002
                                        } catch (Exception e1) {
1003
                                        }
1004
                                        type.setWcsStatus(this.wmsStatus);
1005
                                        if (!isPrinting)
1006
                                                this.setVisible(false);
1007
                                        throw new DriverException("Error WMS", e,  type);
1008

    
1009

    
1010
                                } //if
1011
                        }//if
1012
                }//catch
1013
                callCount--;
1014
        }
1015

    
1016
        /**
1017
         * Obtiene la extensi?n del fichero de georreferenciaci?n
1018
         * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
1019
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
1020
         */
1021
        private String getExtensionWorldFile(){
1022
                String extWorldFile = ".wld";
1023
            if(m_Format.equals("image/tif") || m_Format.equals("image/tiff"))
1024
                    extWorldFile = ".tfw";
1025
            if(m_Format.equals("image/jpeg"))
1026
                    extWorldFile = ".jpgw";
1027
            return extWorldFile;
1028
        }
1029

    
1030
        /**
1031
         * Calcula el contenido del fichero de georreferenciaci?n de una imagen.
1032
         * @param bBox Tama?o y posici?n de la imagen (en coordenadas de usuario)
1033
         * @param sz Tama?o de la imagen en pixeles.
1034
         * @return el 'WorldFile', como String.
1035
         * @throws IOException
1036
         */
1037
        public String getDataWorldFile(Rectangle2D bBox, Dimension sz) throws IOException {
1038
                StringBuffer data = new StringBuffer();
1039
            data.append((bBox.getMaxX() - bBox.getMinX())/(sz.getWidth() - 1)+"\n");
1040
            data.append("0.0\n");
1041
            data.append("0.0\n");
1042
            data.append("-"+(bBox.getMaxY() - bBox.getMinY())/(sz.getHeight() - 1)+"\n");
1043
            data.append(""+bBox.getMinX()+"\n");
1044
            data.append(""+bBox.getMaxY()+"\n");
1045
            return data.toString();
1046
        }
1047

    
1048
        /**
1049
         * Dibuja una imagen usando PxRaster
1050
         * @param g        Graphics2D en el que hay que dibujar.
1051
         * @param vpData Par?metros de visualizaci?n
1052
         * @param file La imagen en cuesti?n.
1053
         */
1054
        private void rasterProcess(Graphics2D g, ViewPortData vpData, File file) throws DriverException {
1055

    
1056
                //Creamos el PxRaster
1057
                try {
1058
                        rasterFile = new GdalFile(vpData.getProjection(), file.getAbsolutePath());
1059
                } catch (NotSupportedExtensionException e) {
1060
                        throw new DriverException("Open File Error");
1061
                }
1062
                raster = new PxRaster(rasterFile, null, rasterFile.getExtent());
1063
                grid = new Grid(rasterFile);
1064
                grid.addRenderizer(raster);
1065
                
1066
                if(status != null && firstLoad){
1067
                        status.applyStatus(this);
1068
                        firstLoad = false;
1069
                }
1070

    
1071
                //Recuperamos la pila de filtros si ya hubiese sido cargado antes
1072
                if(this.filterStack!=null)
1073
                        raster.filterStack = this.filterStack;
1074

    
1075
                raster.setTransparency(false);
1076

    
1077
                //Asignamos transparencia y orden de bandas
1078
                if(this.transparency == -1 && !firstLoad);
1079
                else
1080
                        raster.setTransparency(this.transparency);
1081

    
1082
                raster.setBand(GeoRasterFile.RED_BAND,rband);
1083
                raster.setBand(GeoRasterFile.GREEN_BAND, gband);
1084
                raster.setBand(GeoRasterFile.BLUE_BAND, bband);
1085

    
1086
                //Despues del primer pxRaster asignamos el stackManager guardado para los siguientes.
1087
                //Con esto conseguimos asignar los cambios que se hayan producido desde el cuadro de
1088
                //propiedades cuando creamos un nuevo pxRaster
1089
                if(this.stackManager != null)
1090
                        raster.setStackManager(this.stackManager);
1091

    
1092
                if(visualStatus != null){
1093
                        visualStatus.bandCount = raster.getBandCount();
1094
                        visualStatus.dataType = raster.getDataType();
1095
                }
1096

    
1097
                raster.draw(g, vpData);
1098

    
1099
                //En el primer pxRaster de una imagen obtenemos el Stack Manager para poder modificarlo
1100
                //si queremos desde las propiedades
1101

    
1102
                if(this.stackManager == null)
1103
                        this.stackManager = raster.getStackManager();
1104

    
1105
                if(this.filterStack == null)
1106
                        this.filterStack = raster.filterStack;
1107

    
1108
                //rasterFile.close();
1109
        }
1110

    
1111
        /**
1112
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D,
1113
         *                 com.iver.cit.gvsig.fmap.ViewPort,
1114
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
1115
         */
1116
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet properties)
1117
                throws DriverException {
1118
                if (isVisible() && isWithinScale(scale)){
1119
                isPrinting = true;
1120
                if (!mustTilePrint) {
1121
                        draw(null, g, viewPort, cancel,scale);
1122
                } else {
1123
                // Para no pedir imagenes demasiado grandes, vamos
1124
                // a hacer lo mismo que hace EcwFile: chunkear.
1125
                // Llamamos a drawView con cuadraditos m?s peque?os
1126
                // del BufferedImage ni caso, cuando se imprime viene con null
1127

    
1128
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
1129
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
1130
                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
1131
                            // Parte que dibuja
1132
                            try {
1133
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
1134
                                drawTile(g, vp, cancel);
1135
                                } catch (NoninvertibleTransformException e) {
1136
                                        e.printStackTrace();
1137
                                }
1138
                }
1139
                }
1140
            isPrinting = false;
1141
                }
1142
        }
1143

    
1144
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale)
1145
                throws DriverException {
1146
                draw(null, g, viewPort, cancel,scale);
1147
        }
1148

    
1149
        /**
1150
         * Devuelve el FMapWMSDriver.
1151
         *
1152
         * @return FMapWMSDriver
1153
         *
1154
         * @throws IllegalStateException
1155
         * @throws ValidationException
1156
         * @throws UnsupportedVersionException
1157
         * @throws IOException
1158
         */
1159
        private FMapWMSDriver getDriver()
1160
                throws IllegalStateException, ValidationException,
1161
                        UnsupportedVersionException, IOException {
1162
                return FMapWMSDriverFactory.getFMapDriverForURL(host);
1163
        }
1164

    
1165
        /**
1166
         * Devuelve el FMapWMSDriver.
1167
         *
1168
         * @return FMapWMSDriver
1169
         *
1170
         * @throws IllegalStateException
1171
         * @throws ValidationException
1172
         * @throws UnsupportedVersionException
1173
         * @throws IOException
1174
         */
1175
        public void setDriver(FMapWMSDriver drv) {
1176
                wms = drv;
1177
        }
1178

    
1179
        /**
1180
         * Devuelve el URL.
1181
         *
1182
         * @return URL.
1183
         */
1184
        public URL getHost() {
1185
                return host;
1186
        }
1187

    
1188
        /**
1189
         * Inserta el URL.
1190
         *
1191
         * @param host URL.
1192
         */
1193
        public void setHost(URL host) {
1194
                this.host = host;
1195
        }
1196

    
1197
        /**
1198
         * Devuelve la informaci?n de la consulta.
1199
         *
1200
         * @return String.
1201
         */
1202
        public String getInfoLayerQuery() {
1203
                return infoLayerQuery;
1204
        }
1205

    
1206
        /**
1207
         * Inserta la informaci?n de la consulta.
1208
         *
1209
         * @param infoLayerQuery String.
1210
         */
1211
        public void setInfoLayerQuery(String infoLayerQuery) {
1212
                this.infoLayerQuery = infoLayerQuery;
1213
        }
1214

    
1215
        /**
1216
         * Devuelve la consulta.
1217
         *
1218
         * @return String.
1219
         */
1220
        public String getLayerQuery() {
1221
                return layerQuery;
1222
        }
1223

    
1224
        /**
1225
         * Inserta la consulta.
1226
         *
1227
         * @param layerQuery consulta.
1228
         */
1229
        public void setLayerQuery(String layerQuery) {
1230
                this.layerQuery = layerQuery;
1231
        }
1232

    
1233
        /**
1234
         * Devuelve el formato.
1235
         *
1236
         * @return Formato.
1237
         */
1238
        public String getFormat() {
1239
                return m_Format;
1240
        }
1241

    
1242
        /**
1243
         * Inserta el formato.
1244
         *
1245
         * @param format Formato.
1246
         */
1247
        public void setFormat(String format) {
1248
                m_Format = format;
1249
        }
1250

    
1251
        /**
1252
         * Devuelve el SRS.
1253
         *
1254
         * @return SRS.
1255
         */
1256
        public String getSRS() {
1257
                return m_SRS;
1258
        }
1259

    
1260
        /**
1261
         * Inserta el SRS.
1262
         *
1263
         * @param m_srs SRS.
1264
         */
1265
        public void setSRS(String m_srs) {
1266
                m_SRS = m_srs;
1267
        }
1268

    
1269
        /**
1270
         * Inserta la extensi?n total de la capa.
1271
         *
1272
         * @param fullExtent Rect?ngulo.
1273
         */
1274
        public void setFullExtent(Rectangle2D fullExtent) {
1275
                this.fullExtent = fullExtent;
1276
        }
1277

    
1278
        public HashMap getProperties() {
1279
                HashMap info = new HashMap();
1280
        String[] layerNames = getLayerQuery().split(",");
1281
        Vector layers = new Vector(layerNames.length);
1282
        try {
1283
            if(getDriver().connect(null)){
1284
                for (int i = 0; i < layerNames.length; i++) {
1285
                    layers.add(i, getDriver().getLayer(layerNames[i]));
1286
                }
1287
                info.put("name", getName());
1288
                info.put("selectedLayers", layers);
1289
                info.put("host", getHost());
1290
                info.put("srs", getSRS());
1291
                info.put("format", getFormat());
1292
                info.put("wmsTransparency", new Boolean(wmsTransparency));
1293
                info.put("styles", styles);
1294
                info.put("dimensions", dimensions);
1295
                info.put("fixedSize", fixedSize);
1296
                return info;
1297
            }
1298
        } catch (Exception e) {
1299
            e.printStackTrace();
1300
        }
1301
        return null;
1302
        }
1303

    
1304
        /**
1305
         * Asignar el estado del raster
1306
         * @param status
1307
         */
1308
        public void setStatus(StatusRasterInterface status){
1309
                this.status = status;
1310
        }
1311

    
1312
        /**
1313
         * Obtiene el estado del raster
1314
         * @return
1315
         */
1316
        public StatusRasterInterface getStatus(){
1317
                return this.status;
1318
        }
1319

    
1320
        /* (non-Javadoc)
1321
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getAttributes()
1322
         */
1323
        public ArrayList getAttributes() {
1324
                if(rasterFile != null){
1325
                        ArrayList attr = new ArrayList();
1326
                        String dataType = "Byte";
1327
                        if (rasterFile.getDataType() == DataBuffer.TYPE_BYTE) dataType = "Byte";
1328
                        else if (visualStatus.dataType == DataBuffer.TYPE_SHORT)
1329
                                dataType = "Short";
1330
                        else if (visualStatus.dataType == DataBuffer.TYPE_USHORT)
1331
                                dataType = "Unsigned Short";
1332
                        else if (visualStatus.dataType == DataBuffer.TYPE_INT)
1333
                                dataType = "Integer";
1334
                        else if (visualStatus.dataType == DataBuffer.TYPE_FLOAT)
1335
                                dataType = "Float";
1336
                        else if (visualStatus.dataType == DataBuffer.TYPE_DOUBLE)
1337
                                dataType = "Double";
1338
                        else
1339
                                dataType = "Unknown";
1340

    
1341
                        Object [][] a = {
1342
                                {"Filename",rasterFile.getName().substring(rasterFile.getName().lastIndexOf("/")+1, rasterFile.getName().length())},
1343
                                {"Filesize",new Long(0)},
1344
                                {"Width",new Integer((int)this.getWidth())},
1345
                                {"Height", new Integer((int)this.getHeight())},
1346
                                {"Bands", new Integer(visualStatus.bandCount)},
1347
                                {"BandDataType", dataType}
1348
                        };
1349
                        for (int i=0; i<a.length; i++)
1350
                                attr.add(a[i]);
1351

    
1352
                        return attr;
1353
                }
1354
                return  null;
1355
        }
1356

    
1357
        /* (non-Javadoc)
1358
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getFilterStack()
1359
         */
1360
        public RasterFilterStack getFilterStack() {
1361
                if(raster!=null)
1362
                        return raster.filterStack;
1363
                return null;
1364
        }
1365
        /* (non-Javadoc)
1366
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getHeight()
1367
         */
1368
        public double getHeight() {
1369
                return visualStatus.height;
1370
        }
1371

    
1372
        /* (non-Javadoc)
1373
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxX()
1374
         */
1375
        public double getMaxX() {
1376
                return visualStatus.maxX;
1377
        }
1378

    
1379
        /* (non-Javadoc)
1380
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxY()
1381
         */
1382
        public double getMaxY() {
1383
                return visualStatus.maxY;
1384
        }
1385

    
1386
        /* (non-Javadoc)
1387
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinX()
1388
         */
1389
        public double getMinX() {
1390
                return visualStatus.minX;
1391
        }
1392

    
1393
        /* (non-Javadoc)
1394
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinY()
1395
         */
1396
        public double getMinY() {
1397
                return visualStatus.minY;
1398
        }
1399
        /* (non-Javadoc)
1400
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getPixel(double, double)
1401
         */
1402
        public int[] getPixel(double wcx, double wcy) {
1403
                if(getPxRaster() != null)
1404
                        return getPxRaster().getPixel(wcx, wcy);
1405
        return null;
1406
        }
1407
        /* (non-Javadoc)
1408
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getSource()
1409
         */
1410
        public RasterAdapter getSource() {
1411
                return null;
1412
        }
1413
        /* (non-Javadoc)
1414
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getWidth()
1415
         */
1416
        public double getWidth() {
1417
                return visualStatus.width;
1418
        }
1419
        /* (non-Javadoc)
1420
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setBand(int, int)
1421
         */
1422
        public void setBand(int flag, int nBand) {
1423
                switch(flag){
1424
                case GeoRasterFile.RED_BAND:setBandR(nBand);break;
1425
                case GeoRasterFile.GREEN_BAND:setBandG(nBand);break;
1426
                case GeoRasterFile.BLUE_BAND:setBandB(nBand);break;
1427
                }
1428
        }
1429
        /* (non-Javadoc)
1430
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setFilterStack(org.cresques.io.raster.RasterFilterStack)
1431
         */
1432
        public void setFilterStack(RasterFilterStack stack) {
1433
                this.filterStack = stack;
1434
        }
1435
        /* (non-Javadoc)
1436
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPos(int, int)
1437
         */
1438
        public void setPos(int x, int y) {
1439
                this.posX = x;
1440
                this.posY = y;
1441
        }
1442

    
1443
        /* (non-Javadoc)
1444
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPosWC(double, double)
1445
         */
1446
        public void setPosWC(double x, double y) {
1447
                this.posXWC = x;
1448
                this.posYWC = y;
1449
        }
1450

    
1451
        /* (non-Javadoc)
1452
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setRGB(int, int, int)
1453
         */
1454
        public void setRGB(int r, int g, int b) {
1455
                this.r = r;
1456
                this.g = g;
1457
                this.b = b;
1458
        }
1459
        /* (non-Javadoc)
1460
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setSource(com.iver.cit.gvsig.fmap.layers.RasterAdapter)
1461
         */
1462
        public void setSource(RasterAdapter ra) {
1463
        }
1464
        /**
1465
         * @return Returns the raster.
1466
         */
1467
        public PxRaster getPxRaster() {
1468
                return raster;
1469
        }
1470
        /**
1471
         * @return Returns the rasterFile.
1472
         */
1473
        public GeoRasterFile getGeoRasterFile() {
1474
                return rasterFile;
1475
        }
1476

    
1477
        public void setTransparency(int trans) {
1478
                this.transparency = trans;
1479
        }
1480

    
1481
        /**
1482
         * Sets the R-band.
1483
         *
1484
         * Asigna la banda R.
1485
         * @param r
1486
         */
1487
        public void setBandR(int r){
1488
                this.rband = r;
1489
        }
1490

    
1491
        /**
1492
         * Sets the G-band.
1493
         *
1494
         * Asigna la banda G
1495
         * @param g
1496
         */
1497
        public void setBandG(int g){
1498
                this.gband = g;
1499
        }
1500

    
1501
        /**
1502
         * Sets the B-band.
1503
         *
1504
         * Asigna la banda B
1505
         * @param b
1506
         */
1507
        public void setBandB(int b){
1508
                this.bband = b;
1509
        }
1510

    
1511
    /**
1512
     * @return Returns the wmsTransparency.
1513
     */
1514
    public boolean isWmsTransparent() {
1515
        return wmsTransparency;
1516
    }
1517

    
1518
    /**
1519
     * @param wmsTransparency The wmsTransparency to set.
1520
     */
1521
    public void setWmsTransparency(boolean wmsTransparency) {
1522
        this.wmsTransparency = wmsTransparency;
1523
    }
1524

    
1525
     /**
1526
     * @param styles
1527
     */
1528
    public void setStyles(Vector styles) {
1529
            //laura:
1530
            //layer query is built with the layer in reverse order
1531
            // so here we build the styles upside-down.
1532
            if (styles != null)
1533
            {
1534
                    this.styles = new Vector();
1535
                    for(int i = styles.size()-1; i>=0; i--)
1536
                    {
1537
                            this.styles.add(styles.elementAt(i));
1538
                    }
1539
            }
1540
    }
1541

    
1542
    /**
1543
     * Sets the dimension vector that is a list of key-value pairs containing
1544
     * the name of the dimension and the value for it
1545
     * @param dimensions
1546
     */
1547
    public void setDimensions(Vector dimensions) {
1548
        this.dimensions = dimensions;
1549
    }
1550

    
1551
    /**
1552
     * Sets the set of URLs that should be accessed for each operation performed
1553
     * to the server.
1554
     *
1555
     * @param onlineResources
1556
     */
1557
        public void setOnlineResources(Hashtable onlineResources) {
1558
                this.onlineResources = onlineResources;
1559
        }
1560

    
1561
    /**
1562
     * Gets the URL that should be accessed for an operation performed
1563
     * to the server.
1564
     *
1565
     * @param onlineResources
1566
     */
1567
        public String getOnlineResource(String operation) {
1568
                return ((String) onlineResources.get(operation));
1569
        }
1570

    
1571
        /**
1572
         * When a server is not fully featured and it only can serve constant map
1573
         * sizes this value must be set. It expresses the size in pixels (width, height)
1574
         * that the map will be requested.
1575
         * @param Dimension sz
1576
         */
1577
        public void setFixedSize(Dimension sz) {
1578
                fixedSize = sz;
1579
        }
1580

    
1581
        /**
1582
         * Tells whether if this layer must deal with the server with the constant-size
1583
         * limitations or not.
1584
         * @return boolean.
1585
         */
1586
        private boolean isSizeFixed() {
1587
                return fixedSize != null && fixedSize.getWidth() > 0 && fixedSize.getHeight() > 0;
1588
        }
1589

    
1590
        /**
1591
         * If it is true, this layer accepts GetFeatureInfo operations. This WMS operations
1592
         * maps to FMap's infoByPoint(p) operation.
1593
         * @param b
1594
         */
1595
        public void setQueryable(boolean b) {
1596
                queryable = b;
1597
        }
1598

    
1599
        /**
1600
         * Creates the part of a OGC's MapContext document that would describe this
1601
         * layer(s).
1602
         * @param version, The desired version of the resulting document. (1.1.0)
1603
         * @return String containing the xml.
1604
         * @throws UnsupportedVersionException
1605
         */
1606
        public String toMapContext(String mapContextVersion) {
1607
                XmlBuilder xml = new XmlBuilder();
1608
                FMapWMSDriver drv;
1609
                try {
1610
                        drv = getDriver();
1611
                } catch (Exception e) {
1612
                        return xml.toString();
1613
                }
1614
                String[] layerNames = getLayerQuery().split(",");
1615
                String[] styleNames = (String[]) styles.toArray(new String[0]);
1616
                for (int i = 0; i < layerNames.length; i++) {
1617
                        WMSLayerNode layer = drv.getLayer(layerNames[i]);
1618
                        HashMap xmlAttrs = new HashMap();
1619

    
1620
                        // <Layer>
1621
                        xmlAttrs.put(WebMapContextTags.HIDDEN, !isVisible()+"");
1622
                        xmlAttrs.put(WebMapContextTags.QUERYABLE, queryable+"");
1623
                        xml.openTag(WebMapContextTags.LAYER, xmlAttrs);
1624
                        xmlAttrs.clear();
1625
                        if (mapContextVersion.equals("1.1.0") || mapContextVersion.equals("1.0.0")) {
1626
                                // <Server>
1627
                                xmlAttrs.put(WebMapContextTags.SERVICE, WebMapContextTags.WMS);
1628
                                xmlAttrs.put(WebMapContextTags.VERSION, drv.getVersion());
1629
                                xmlAttrs.put(WebMapContextTags.SERVER_TITLE, drv.getServiceTitle());
1630
                                xml.openTag(WebMapContextTags.SERVER, xmlAttrs);
1631
                                xmlAttrs.clear();
1632

    
1633
                                        // <OnlineResource>
1634
                                        xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1635
                                        xmlAttrs.put(WebMapContextTags.XLINK_HREF, getHost().toString());
1636
                                        xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1637
                                        xmlAttrs.clear();
1638
                                        // </OnlineResource>
1639

    
1640
                                xml.closeTag();
1641
                                // </Server>
1642

    
1643
                                // <Name>
1644
                                xml.writeTag(WebMapContextTags.NAME, layer.getName().trim());
1645
                                // </Name>
1646

    
1647
                                // <Title>
1648
                                xml.writeTag(WebMapContextTags.TITLE, layer.getTitle().trim());
1649
                                //?xml.writeTag(WebMapContextTags.TITLE, getName().trim());
1650
                                // </Title>
1651

    
1652
                                // <Abstract>
1653
                                if (layer.getAbstract() != null)
1654
                                        xml.writeTag(WebMapContextTags.ABSTRACT, layer.getAbstract());
1655
                                // </Abstract>
1656

    
1657
                                // <SRS> (a list of available SRS for the enclosing layer)
1658
                                String[] strings = (String[]) layer.getAllSrs().toArray(new String[0]);
1659
                                String mySRS = strings[0];
1660
                                for (int j = 1; j < strings.length; j++) {
1661
                                        mySRS += ","+strings[j];
1662
                                }
1663
                                xml.writeTag(WebMapContextTags.SRS, mySRS);
1664
                                // </SRS>
1665

    
1666
                                // <FormatList>
1667
                                xml.openTag(WebMapContextTags.FORMAT_LIST);
1668
                                        strings = (String[]) drv.getFormats().toArray(new String[0]);
1669
                                        for (int j = 0; j < strings.length; j++) {
1670
                    // <Format>
1671
                                                String str = strings[j].trim();
1672
                                                if (str.equals(getFormat()))
1673
                                                        xml.writeTag(WebMapContextTags.FORMAT, str, WebMapContextTags.CURRENT, "1");
1674
                                                else
1675
                                                        xml.writeTag(WebMapContextTags.FORMAT, str);
1676
                    // </Format>
1677
                                        }
1678
                                xml.closeTag();
1679
                                // </FormatList>
1680

    
1681
                                // <StyleList>
1682
                                xml.openTag(WebMapContextTags.STYLE_LIST);
1683

    
1684
                                        if (layer.getStyles().size()>0) {
1685
                                                for (int j = 0; j < layer.getStyles().size(); j++) {
1686
                                                        // <Style>
1687
                                                        FMapWMSStyle st = (FMapWMSStyle) layer.getStyles().get(j);
1688
                                                        if (st.name.equals(styleNames[i]))
1689
                                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1690
                                                        xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1691
                                                        xmlAttrs.clear();
1692

    
1693
                                                                // <Name>
1694
                                                                xml.writeTag(WebMapContextTags.NAME, st.name);
1695
                                                                // </Name>
1696

    
1697
                                                                // <Title>
1698
                                                                xml.writeTag(WebMapContextTags.TITLE, st.title);
1699
                                                                // </Title>
1700

    
1701
                                                                // <LegendURL width="180" format="image/gif" height="50">
1702
                                                                        // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1703
                                                                        // </OnlineResource>
1704
                                                                // </LegendURL>
1705
                                                        xml.closeTag();
1706
                                                        // </Style>
1707

    
1708
                                                }
1709

    
1710
                                        } else {
1711
                                                // Create fake style (for compatibility issues)
1712
                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1713
                                                // <Style>
1714
                                                xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1715
                                                        xmlAttrs.clear();
1716
                                                        // <Name>
1717
                                                        xml.writeTag(WebMapContextTags.NAME, "default");
1718
                                                        // </Name>
1719

    
1720
                                                        // <Title>
1721
                                                        xml.writeTag(WebMapContextTags.TITLE, "default");
1722
                                                        // </Title>
1723

    
1724
//                                                        // <LegendURL width="180" format="image/gif" height="50">
1725
//                                                        xmlAttrs.put(WebMapContextTags.WIDTH, "0");
1726
//                                                        xmlAttrs.put(WebMapContextTags.HEIGHT, "0");
1727
//                                                        xmlAttrs.put(WebMapContextTags.FORMAT.toLowerCase(), "image/gif");
1728
//                                                        xml.openTag(WebMapContextTags.LEGEND_URL, xmlAttrs);
1729
//                                                        xmlAttrs.clear();
1730
//                                                                // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1731
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1732
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_HREF, "http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif");
1733
//                                                                xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1734
//                                                                // </OnlineResource>
1735
//                                                    // </LegendURL>
1736
//                                                        xml.closeTag();
1737
                                                // </Style>
1738
                                                xml.closeTag();
1739
                                        }
1740
                                // </StyleList>
1741
                                xml.closeTag();
1742
                                if (mapContextVersion.compareTo("1.0.0") > 0) {
1743
                                // <DimensionList>
1744
                                        xml.openTag(WebMapContextTags.DIMENSION_LIST);
1745
                                        // <Dimension>
1746
                                        // </Dimension>
1747
                                        xml.closeTag();
1748
                                // </DimensionList>
1749
                                }
1750
                        } else {
1751
                                xml.writeTag("ERROR", PluginServices.getText(this, "unsupported_map_context_version"));
1752
                        }
1753
                        // </Layer>
1754
                        xml.closeTag();
1755
                }
1756
                return xml.getXML();
1757
        }
1758

    
1759
        public ImageIcon getTocImageIcon() {
1760
                return new ImageIcon(PluginServices.getPluginServices("com.iver.cit.gvsig.wms").getClassLoader().getResource("images/icoLayer.png"));
1761
        }
1762

    
1763
        /*
1764
         *  (non-Javadoc)
1765
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1766
         */
1767
        public int[] getTileSize() {
1768
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1769
                return size;
1770
        }
1771

    
1772
        /*
1773
         *  (non-Javadoc)
1774
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1775
         */
1776
        public boolean isTiled() {
1777
                return mustTileDraw;
1778
        }
1779

    
1780
        public Image getImageLegend() {
1781
                try {
1782
                        if (wms.hasLegendGraphic() ){
1783
                                wmsStatus.setOnlineResource((String) onlineResources.get("GetLegendGraphic"));
1784
                                File legend = getDriver().getLegendGraphic(wmsStatus, layerQuery, null);
1785
                                Image img = null;
1786
                                if ((legend!= null) && (legend.length() > 0))
1787
                                        img = ImageIO.read(legend);
1788
                                return img;
1789
                        }else{
1790
                                return null;
1791
                        }
1792
                }catch(Exception e){
1793
                        //e.printStackTrace();
1794
                        return null;
1795
                }
1796
        }
1797

    
1798
        /**
1799
         * Obtiene el grid asociado al raster que hay cargado en ese momento
1800
         * @return grid
1801
         */
1802
        public Grid getGrid(){
1803
                return grid;
1804
        }
1805
        
1806
        /**
1807
         * Obtiene el tipo de dato de la capa raster
1808
         * @return Entero que representa el tipo de dato de la capa raster.
1809
         */
1810
        public int getDataType() {
1811
                return rasterFile.getDataType();
1812
        }
1813
        public boolean isQueryable(){
1814
                return queryable;
1815
        }
1816
}