Statistics
| Revision:

root / trunk / extensions / extWMS / src / com / iver / cit / gvsig / fmap / layers / FLyrWMS.java @ 10701

History | View | Annotate | Download (55.4 KB)

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

    
43
import java.awt.Component;
44
import java.awt.Dimension;
45
import java.awt.Graphics2D;
46
import java.awt.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.px.Extent;
79
import org.cresques.px.PxRaster;
80
import org.exolab.castor.xml.ValidationException;
81
import org.gvsig.remoteClient.utils.Utilities;
82
import org.gvsig.remoteClient.wms.ICancellable;
83
import org.gvsig.remoteClient.wms.WMSStatus;
84

    
85
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
86
import com.iver.andami.PluginServices;
87
import com.iver.andami.messages.NotificationManager;
88
import com.iver.cit.gvsig.exceptions.layers.ConnectionErrorLayerException;
89
import com.iver.cit.gvsig.exceptions.layers.LoadLayerException;
90
import com.iver.cit.gvsig.exceptions.layers.URLLayerException;
91
import com.iver.cit.gvsig.exceptions.layers.UnsupportedVersionLayerException;
92
import com.iver.cit.gvsig.exceptions.visitors.VisitorException;
93
import com.iver.cit.gvsig.fmap.ConnectionErrorExceptionType;
94
import com.iver.cit.gvsig.fmap.UnknownResponseFormatExceptionType;
95
import com.iver.cit.gvsig.fmap.UnsuportedProtocolVersionExceptionType;
96
import com.iver.cit.gvsig.fmap.ViewPort;
97
import com.iver.cit.gvsig.fmap.WMSDriverExceptionType;
98
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
99
import com.iver.cit.gvsig.fmap.drivers.wms.FMapWMSDriver;
100
import com.iver.cit.gvsig.fmap.drivers.wms.FMapWMSDriverFactory;
101
import com.iver.cit.gvsig.fmap.drivers.wms.WMSException;
102
import com.iver.cit.gvsig.fmap.layers.WMSLayerNode.FMapWMSStyle;
103
import com.iver.cit.gvsig.fmap.layers.layerOperations.IHasImageLegend;
104
import com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint;
105
import com.iver.cit.gvsig.fmap.layers.layerOperations.StringXMLItem;
106
import com.iver.cit.gvsig.fmap.layers.layerOperations.XMLItem;
107
import com.iver.cit.gvsig.fmap.rendering.XmlBuilder;
108
import com.iver.cit.gvsig.wmc.WebMapContextTags;
109
import com.iver.utiles.StringUtilities;
110
import com.iver.utiles.XMLEntity;
111
import com.iver.utiles.swing.threads.Cancellable;
112

    
113

    
114

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

    
133
    public URL                                                         host;
134
    public String                                                 m_Format;
135

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

    
161

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

    
174
        }
175

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

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

    
189
                try {
190
                        this.setHost(new URL(host));
191
                } catch (MalformedURLException e) {
192
                        //e.printStackTrace();
193
                        throw new URLLayerException(getName(),e);
194
                }
195
                        try {
196
                                drv = this.getDriver();
197
                        } catch (IllegalStateException e) {
198
                                throw new LoadLayerException(getName(),e);
199
                        } catch (ValidationException e) {
200
                                throw new LoadLayerException(getName(),e);
201
                        } catch (IOException e) {
202
                                throw new ConnectionErrorLayerException(getName(),e);
203
                        }
204
                if( sFormat == null || sSRS == null || fullExtent == null ) {
205
                        if (!drv.connect(null))
206
                                throw new ConnectionErrorLayerException(getName(),null);
207

    
208
                        WMSLayerNode wmsNode = drv.getLayer(sLayer);
209

    
210
                        if (wmsNode == null){
211
                                throw new LoadLayerException(getName(),null);
212
                        }
213
                        if( sFormat == null ) {
214
                                sFormat = this.getGreatFormat(drv.getFormats());
215
                        }
216
//                        SRS
217
                        Vector allSrs = wmsNode.getAllSrs();
218
                        boolean isSRSSupported = false;
219
                        if( sSRS != null ) {
220
                                for (int i=0; i<allSrs.size() ; i++){
221
                                     if (((String)allSrs.get(i)).compareTo(sSRS) == 0){
222
                                             isSRSSupported = true;
223
                                     }
224
                             }
225
                        }
226

    
227
                     if(!isSRSSupported) {
228
                             for (int i=0; i<allSrs.size() ; i++){
229
                                     if (((String)wmsNode.getAllSrs().get(i)).compareTo("EPSG:4326") == 0){
230
                                             sSRS = (String)wmsNode.getAllSrs().get(i);
231
                                     }
232
                             }
233
                             if (sSRS==null){
234
                                     sSRS = (String)wmsNode.getAllSrs().get(0);
235
                             }
236
                     }
237
                        if( fullExtent == null ) {
238
                                fullExtent = drv.getLayersExtent(sLayers,sSRS);
239
                        }
240
                }
241

    
242

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

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

    
272
            return (String)formats.get(0);
273
        }
274

    
275
        /**
276
         * Clase que contiene los datos de visualizaci?n de WMS.
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

    
291
        /**
292
         * Devuelve el XMLEntity con la informaci?n necesaria para reproducir la
293
         * capa.
294
         *
295
         * @return XMLEntity.
296
         * @throws XMLException
297
         */
298
        public XMLEntity getXMLEntity() throws XMLException {
299
                XMLEntity xml = super.getXMLEntity();
300

    
301
                // Full extent
302
                xml.putProperty("fullExtent", StringUtilities.rect2String(fullExtent));
303

    
304
                // Host
305
                xml.putProperty("host", host.toExternalForm());
306

    
307
                // Part of the query that is not the host, or the
308
                // layer names, or other not listed bellow
309
                xml.putProperty("infoLayerQuery", infoLayerQuery);
310

    
311
                // Part of the query containing the layer names
312
                xml.putProperty("layerQuery", layerQuery);
313

    
314
                // Format
315
                xml.putProperty("format", m_Format);
316

    
317
                // SRS
318
                xml.putProperty("srs", m_SRS);
319
                if (status!=null)
320
                        status.getXMLEntity(xml, true, this);
321
                else{
322
                        status = new StatusLayerRaster();
323
                        status.getXMLEntity(xml, true, this);
324
                }
325

    
326
        // Transparency
327
        xml.putProperty("wms_transparency", wmsTransparency);
328

    
329
        // Styles
330
        if (styles!=null){
331
            String stylePr = "";
332
            for (int i = 0; i < styles.size(); i++) {
333
                stylePr += (String) styles.get(i);
334
                if (i<styles.size()-1)
335
                    stylePr += ",";
336
            }
337
            if (stylePr.endsWith(","))
338
                    stylePr += " ";
339
            xml.putProperty("styles", stylePr);
340
        }
341

    
342
        // Dimensions
343
        if (dimensions!=null){
344
            String dim = "";
345
            for (int i = 0; i < dimensions.size(); i++) {
346
                dim += (String) dimensions.get(i);
347
                if (i<dimensions.size()-1)
348
                    dim += ",";
349
            }
350
            if (dim.endsWith(","))
351
                    dim += " ";
352
            xml.putProperty("dimensions", dim);
353
        }
354

    
355
        // OnlineResources
356
        Iterator it = onlineResources.keySet().iterator();
357
        String strOnlines = "";
358
        while (it.hasNext()) {
359
                String key = (String) it.next();
360
                String value = (String) onlineResources.get(key);
361
                strOnlines += key+"~##SEP2##~"+value;
362
                if (it.hasNext())
363
                        strOnlines += "~##SEP1##~";
364
        }
365
        xml.putProperty("onlineResources", strOnlines);
366

    
367
        // Queryable
368
        xml.putProperty("queryable", queryable);
369

    
370
        // fixedSize
371
        if (isSizeFixed()) {
372
                xml.putProperty("fixedSize", true);
373
                xml.putProperty("fixedWidth", fixedSize.width);
374
                xml.putProperty("fixedHeight", fixedSize.height);
375
        }
376
        return xml;
377
        }
378

    
379
        /**
380
         * A partir del XMLEntity reproduce la capa.
381
         *
382
         * @param xml XMLEntity
383
         *
384
         * @throws XMLException
385
         * @throws DriverException
386
         * @throws DriverIOException
387
         */
388
        public void setXMLEntity03(XMLEntity xml)
389
                throws XMLException {
390
                super.setXMLEntity(xml);
391
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty(
392
                                        "fullExtent"));
393

    
394
                try {
395
                        host = new URL(xml.getStringProperty("host"));
396
                } catch (MalformedURLException e) {
397
                        throw new XMLException(e);
398
                }
399

    
400
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
401
                layerQuery = xml.getStringProperty("layerQuery");
402
                m_Format = xml.getStringProperty("format");
403
                m_SRS = xml.getStringProperty("srs");
404
        }
405

    
406
        /**
407
         * A partir del XMLEntity reproduce la capa.
408
         *
409
         * @param xml XMLEntity
410
         *
411
         * @throws XMLException
412
         * @throws DriverException
413
         * @throws DriverIOException
414
         */
415
        public void setXMLEntity(XMLEntity xml)
416
                throws XMLException {
417
                super.setXMLEntity(xml);
418
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty(
419
                                        "fullExtent"));
420

    
421
                // Host
422
                try {
423
                        host = new URL(xml.getStringProperty("host"));
424
                } catch (MalformedURLException e) {
425
                        throw new XMLException(e);
426
                }
427

    
428
                // Part of the query that is not the host, or the
429
                // layer names, or other not listed bellow
430
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
431

    
432
                // Part of the query containing the layer names
433
                layerQuery = xml.getStringProperty("layerQuery");
434

    
435
                // Format
436
                m_Format = xml.getStringProperty("format");
437

    
438
                // SRS
439
                m_SRS = xml.getStringProperty("srs");
440

    
441
                String claseStr = StatusLayerRaster.defaultClass;
442
                if (xml.contains("raster.class")) {
443
                        claseStr = xml.getStringProperty("raster.class");
444
                }
445

    
446
                // Transparency
447
        if (xml.contains("wms_transparency"))
448
            wmsTransparency = xml.getBooleanProperty("wms_transparency");
449

    
450
        // Styles
451
        if (xml.contains("styles")){
452
            styles = new Vector();
453
            String[] stl = xml.getStringProperty("styles").split(",");
454

    
455
            for (int i = 0; i < stl.length; i++) {
456
                    if (stl[i].equals(" "))
457
                            stl[i]="";
458
                styles.add(stl[i]);
459
            }
460
        }
461

    
462
        // Dimensions
463
        if (xml.contains("dimensions")){
464
            dimensions = new Vector();
465
            String[] dims = xml.getStringProperty("dimensions").split(",");
466
            for (int i = 0; i < dims.length; i++){
467
                    if (dims[i].equals(" "))
468
                            dims[i]="";
469

    
470
                dimensions.add(dims[i]);
471
            }
472
        }
473

    
474
        // OnlineResources
475
        if (xml.contains("onlineResources")) {
476
                String[] operations = xml.getStringProperty("onlineResources").split("~##SEP1##~");
477
                for (int i = 0; i < operations.length; i++) {
478
                                String[] resources = operations[i].split("~##SEP2##~");
479
                                if (resources.length==2 && resources[1]!="")
480
                                        onlineResources.put(resources[0], resources[1]);
481
                        }
482
        }
483

    
484
        // Queryable
485
        queryable = true; // let's assume that the layer is queryable by default
486
        if (xml.contains("queryable"))
487
                queryable = xml.getBooleanProperty("queryable");
488

    
489
        // fixedSize
490
        if (xml.contains("fixedSize")) {
491
                fixedSize = new Dimension(xml.getIntProperty("fixedWidth"),
492
                                                  xml.getIntProperty("fixedHeight"));
493
        }
494

    
495
                if(status!=null)
496
                        status.setXMLEntity(xml, this);
497
                else{
498
                        if(claseStr!=null && !claseStr.equals("")){
499
                                try{
500
                                        Class clase = Class.forName(claseStr);
501
                                        Constructor constr = clase.getConstructor(null);
502
                                        status = (StatusRasterInterface)constr.newInstance(null);
503
                                        if(status!=null)
504
                                                status.setXMLEntity(xml, this);
505
                                }catch(ClassNotFoundException exc){
506
                                        exc.printStackTrace();
507
                                }catch(InstantiationException exc){
508
                                        exc.printStackTrace();
509
                                }catch(IllegalAccessException exc){
510
                                        exc.printStackTrace();
511
                                }catch(NoSuchMethodException exc){
512
                                        exc.printStackTrace();
513
                                }catch(InvocationTargetException exc){
514
                                        exc.printStackTrace();
515
                                }
516
                        }
517
                }
518
                firstLoad = true;
519
        }
520

    
521
        /**
522
         * @throws ReadDriverException
523
         * @throws LoadLayerException
524
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(com.iver.cit.gvsig.fmap.operations.QueriedPoint)
525
         */
526
        public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancellable) throws VisitorException, ReadDriverException, LoadLayerException {
527
                XMLItem[] item =  new XMLItem[1];
528
                try {
529
                        if (queryable)         {
530
                                //TODO
531
                                // check if there are layers which are not queryable
532
                                ViewPort viewPort = getMapContext().getViewPort();
533

    
534
                                Point tiledPoint = new Point((int) p.getX() % maxTilePrintWidth, (int) p.getY() % maxTilePrintHeight);
535
                                Rectangle rect = new Rectangle(0, 0, viewPort.getImageWidth() - 1, viewPort.getImageHeight() - 1);
536
                                Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, rect);
537
                                tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
538
                                int nCols = tiles.getNumCols();
539

    
540
                                int col = (int) p.getX() / maxTilePrintWidth;
541
                                int row = (int) p.getY() / maxTilePrintHeight;
542
                                int tileIndex = (row*nCols) + col;
543

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

    
591
                } //catch (UnsupportedVersionLayerException e) {
592
//                        UnsuportedProtocolVersionExceptionType type =
593
//                                new UnsuportedProtocolVersionExceptionType();
594
//                        type.setLayerName(getName());
595
//                        try {
596
//                                type.setDriverName("WMS Driver");
597
//                        } catch (Exception ex){
598
//                        }
599
//                        type.setUrl(host);
600
//                        throw new ReadDriverException(PluginServices.getText(this, "version_conflict"));
601

    
602
//                }
603
                catch (IOException e) {
604
//                        ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
605
//                        type.setLayerName(getName());
606
//                        try {
607
//                                type.setDriverName("WMS Driver");
608
//                        } catch (Exception e1) {
609
//                        }
610
//                        type.setHost(host);
611
                        throw new ConnectionErrorLayerException(getName(),e);
612
                }
613
                catch (NoninvertibleTransformException e) {
614
                        NotificationManager.addError("NotinvertibleTransform", e);
615
                }
616
                return null;
617
        }
618

    
619
        /**
620
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent()
621
         */
622
        public Rectangle2D getFullExtent() {
623
                return fullExtent;
624
        }
625

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

    
648

    
649
                        if (isSizeFixed()) {
650
                                // This condition handles those situations in which the server can
651
                                // only give static extent and resolution maps despite we need
652
                                // a specific BBOX and pixel WIDTH and HEIGHT
653
                                try {
654
                                        drawFixedSize(g, viewPort, cancel);
655
                                } catch (LoadLayerException e) {
656
                                        // TODO Auto-generated catch block
657
                                        e.printStackTrace();
658
                                }
659

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

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

    
696

    
697
                // This is the extent that will be requested
698
                Rectangle2D bBox = getFullExtent();
699
                MyCancellable c = new MyCancellable(cancel);
700

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

    
718
                        if(status!=null && firstLoad){
719
                                status.applyStatus(this);
720
                                firstLoad = false;
721
                        }
722

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

    
728
                        ViewPortData vpData = new ViewPortData(
729
                                vp.getProjection(), new Extent(extent), fixedSize );
730
                        vpData.setMat(vp.getAffineTransform());
731

    
732
                        rasterProcess(g, vpData, f);
733

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

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

    
786

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

    
808

    
809
                                } // mess code
810
                        }
811
                }
812
                callCount--; // mess code
813
        }
814

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

    
832
        // 2. Compute extent to be requested.
833
        Rectangle2D bBox = new Rectangle2D.Double();
834
        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
835

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

    
842
        Dimension sz = new Dimension(wImg, hImg);
843

    
844
        if ((wImg <= 0) || (hImg <= 0)) {
845
            return;
846
        }
847
        MyCancellable c = new MyCancellable(cancel);
848

    
849
                try {
850
//                        wImg = vp.getImageWidth();
851
//                        hImg = vp.getImageHeight();
852
                        sz = new Dimension(wImg, hImg);
853
                        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
854

    
855

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

    
867
                        // begin patch; Avoid to request too small tiles.
868
                        // This generally occurs when printing
869

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

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

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

    
899
                        ViewPortData vpData = new ViewPortData(
900
                                vp.getProjection(), new Extent(bBox), sz );
901
                        vpData.setMat(vp.getAffineTransform());
902

    
903
                        rasterProcess(g, vpData, f);
904

    
905
                } catch (ValidationException e) {
906
                //azabala
907
//                        if (!c.isCanceled())
908
//                                throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
909

    
910
                        if (!c.isCanceled())
911
                        {
912
//                                UnknownResponseFormatExceptionType type =
913
//                                        new UnknownResponseFormatExceptionType();
914
//                                type.setLayerName(getName());
915
//                                try {
916
//                                        type.setDriverName("WMS Driver");
917
//                                } catch (Exception e1) {
918
//                                        e1.printStackTrace();
919
//                                }
920
//                                type.setFormat(m_Format);
921
//                                type.setHost(host);
922
//                                type.setProtocol("WMS");
923
                                LoadLayerException exception = new LoadLayerException(getName(),e);
924
                                throw exception;
925
                        }
926
//                } catch (UnsupportedVersionLayerException e) {
927
//
928
////                        if (!c.isCanceled())
929
////                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
930
//
931
//                        if (!c.isCanceled()){
932
//                                UnsuportedProtocolVersionExceptionType type =
933
//                                        new UnsuportedProtocolVersionExceptionType();
934
//                                type.setLayerName(getName());
935
//                                try {
936
//                                        type.setDriverName("WMS Driver");
937
//                                } catch (Exception ex){
938
//                                }
939
//                                type.setUrl(host);
940
//                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e, type);
941
//                        }
942
//
943
                } catch (IOException e) {
944
                        /*azabala
945
                        if (!c.isCanceled())
946
                                if (callCount<MAX_RETRY_TIMES) {
947
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null);
948
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error
949
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0)
950
                                        drawTile(g, vp, cancel);
951
                                }
952
                                if (callCount == 1) {
953
                                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
954
                                }
955
                        */
956
                        if (!c.isCanceled()){
957
                                if (callCount<MAX_RETRY_TIMES) { // mess code
958
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
959
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
960
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
961

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

    
1012

    
1013
                                } //if
1014
                        }//if
1015
                }//catch
1016
                callCount--;
1017
        }
1018

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

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

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

    
1059
                //Creamos el PxRaster
1060
                rasterFile = new GdalFile(vpData.getProjection(), file.getAbsolutePath());
1061
                raster = new PxRaster(rasterFile, null, rasterFile.getExtent());
1062

    
1063
                if(status!=null && firstLoad){
1064
                        status.applyStatus(this);
1065
                        firstLoad = false;
1066
                }
1067

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

    
1072
                raster.setTransparency(false);
1073

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

    
1079
                raster.setBand(GeoRasterFile.RED_BAND,rband);
1080
                raster.setBand(GeoRasterFile.GREEN_BAND, gband);
1081
                raster.setBand(GeoRasterFile.BLUE_BAND, bband);
1082

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

    
1089
                if(visualStatus != null){
1090
                        visualStatus.bandCount = raster.getBandCount();
1091
                        visualStatus.dataType = raster.getDataType();
1092
                }
1093

    
1094
                raster.draw(g, vpData);
1095

    
1096
                //En el primer pxRaster de una imagen obtenemos el Stack Manager para poder modificarlo
1097
                //si queremos desde las propiedades
1098

    
1099
                if(this.stackManager == null)
1100
                        this.stackManager = raster.getStackManager();
1101

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

    
1105
                //rasterFile.close();
1106
        }
1107

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

    
1125
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
1126
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
1127
                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
1128
                            // Parte que dibuja
1129
                            try {
1130
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
1131
                                drawTile(g, vp, cancel);
1132
                                } catch (NoninvertibleTransformException e) {
1133
                                        e.printStackTrace();
1134
                                } catch (LoadLayerException e) {
1135
                                        // TODO Auto-generated catch block
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 ReadDriverException {
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 UnsupportedVersionLayerException
1157
         * @throws IOException
1158
         */
1159
        private FMapWMSDriver getDriver()
1160
                throws IllegalStateException, ValidationException,
1161
                        UnsupportedVersionLayerException, 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 UnsupportedVersionLayerException
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 UnsupportedVersionLayerException
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 == null)
1783
                                wms = getDriver();
1784
                        if (wms.hasLegendGraphic()) {
1785
                                wmsStatus.setOnlineResource((String) onlineResources
1786
                                                .get("GetLegendGraphic"));
1787
                                String path = getPathImage();// File legend =
1788
                                                                                                // getDriver().getLegendGraphic(wmsStatus,
1789
                                                                                                // layerQuery, null);
1790
                                Image img = null;
1791
                                if ((path != null) && (path.length() > 0))
1792
                                        img = new ImageIcon(path).getImage();
1793
                                return img;
1794
                        }
1795
                } catch (Exception e) {
1796
                }
1797
                return null;
1798
        }
1799

    
1800
        public String getPathImage() {
1801
                try {
1802
                        File legend = getDriver().getLegendGraphic(wmsStatus, layerQuery, null);
1803
                        return legend.getAbsolutePath();
1804
                }catch(Exception e){
1805
                        e.printStackTrace();
1806
                        return null;
1807
                }
1808
        }
1809

    
1810

    
1811
}