Statistics
| Revision:

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

History | View | Annotate | Download (56.1 KB)

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

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

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

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

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

    
111

    
112

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

    
131
    public URL                                                         host;
132
    public String                                                 m_Format;
133

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

    
160

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

    
173
        }
174

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

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

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

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

    
239

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

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

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

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

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

    
301

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
613
                } catch (UnsupportedVersionException e) {
614
                        UnsuportedProtocolVersionExceptionType type =
615
                                new UnsuportedProtocolVersionExceptionType();
616
                        type.setLayerName(getName());
617
                        try {
618
                                type.setDriverName("WMS Driver");
619
                        } catch (Exception ex){
620
                        }
621
                        type.setUrl(host);
622
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e, type);
623

    
624
                } catch (IOException e) {
625
                        ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
626
                        type.setLayerName(getName());
627
                        try {
628
                                type.setDriverName("WMS Driver");
629
                        } catch (Exception e1) {
630
                        }
631
                        type.setHost(host);
632
                        throw new DriverException(PluginServices.
633
                                        getText(this, "connect_error"), e, type);
634
                }
635
                catch (NoninvertibleTransformException e) {
636
                        NotificationManager.addError("NotinvertibleTransform", e);
637
                }
638
                return null;
639
        }
640

    
641
        /**
642
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent()
643
         */
644
        public Rectangle2D getFullExtent() {
645
                return fullExtent;
646
        }
647

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

    
670

    
671
                        if (isSizeFixed()) {
672
                                // This condition handles those situations in which the server can
673
                                // only give static extent and resolution maps despite we need
674
                                // a specific BBOX and pixel WIDTH and HEIGHT
675
                                drawFixedSize(g, viewPort, cancel);
676

    
677
                        } else {
678
                                if(mustTileDraw){
679
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), viewPort.getImageWidth(), viewPort.getImageHeight());
680
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
681
                                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
682
                                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
683
                                                // drawing part
684
                                                try {
685
                                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
686
                                                        drawTile(g, vp, cancel);
687
                                                } catch (NoninvertibleTransformException e) {
688
                                                        e.printStackTrace();
689
                                                }
690
                                        }
691
                                }else
692
                                        drawTile(g, viewPort, cancel);
693
                        }
694
                }
695
//                Runtime r = Runtime.getRuntime();
696
//                long mem = r.totalMemory() - r.freeMemory();
697
//                System.err.println("Memoria total: " + (mem / 1024) +"KB");
698
        }
699

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

    
705

    
706
                // This is the extent that will be requested
707
                Rectangle2D bBox = getFullExtent();
708
                MyCancellable c = new MyCancellable(cancel);
709

    
710
                try {
711
                        wmsStatus.setExtent( bBox );
712
                        wmsStatus.setFormat( m_Format );
713
                        wmsStatus.setHeight( fixedSize.height );
714
                        wmsStatus.setWidth( fixedSize.width );
715
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
716
                        wmsStatus.setSrs(m_SRS);
717
                        wmsStatus.setStyles(styles);
718
                        wmsStatus.setDimensions(dimensions);
719
                        wmsStatus.setTransparency(wmsTransparency);
720
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
721
                        File f = getDriver().getMap(wmsStatus, c);
722
                        if (f == null)
723
                                return;
724
                        String nameWorldFile = f.getPath() + getExtensionWorldFile();
725
                        com.iver.andami.Utilities.createTemp(nameWorldFile, this.getDataWorldFile(bBox, fixedSize));
726

    
727
                        if(status!=null && firstLoad){
728
                                status.applyStatus(this);
729
                                firstLoad = false;
730
                        }
731

    
732
                        // And finally, obtain the extent intersecting the view and the BBox
733
                        // to draw to.
734
                        Rectangle2D extent = new Rectangle2D.Double();
735
                        Rectangle2D.intersect(vp.getAdjustedExtent(), bBox, extent);
736

    
737
                        ViewPortData vpData = new ViewPortData(
738
                                vp.getProjection(), new Extent(extent), fixedSize );
739
                        vpData.setMat(vp.getAffineTransform());
740

    
741
                        rasterProcess(g, vpData, f);
742

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

    
783
                                if (callCount == 1) { // mess code
784
                                        ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
785
                                        type.setLayerName(getName());
786
                                        try {
787
                                                type.setDriverName("WMS Driver");
788
                                        } catch (Exception e1) {
789
                                        }
790
                                        type.setHost(host);
791
                                        throw new DriverException(PluginServices.
792
                                                        getText(this, "connect_error"), e, type);
793
//        azabala        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
794
                                } // mess code
795

    
796

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

    
818

    
819
                                } // mess code
820
                        }
821
                }
822
                callCount--; // mess code
823
        }
824

    
825
        /**
826
         * This is the method used to draw a tile in a WMS mosaic layer.
827
         */
828
        private void drawTile(Graphics2D g, ViewPort vp, Cancellable cancel) throws DriverException {
829
                callCount++;
830
                // Compute the query geometry
831
                // 1. Check if it is within borders
832
                Rectangle2D extent = getFullExtent();
833
        if ((vp.getAdjustedExtent().getMinX() > extent.getMaxX()) ||
834
                (vp.getAdjustedExtent().getMinY() > extent.getMaxY()) ||
835
                (vp.getAdjustedExtent().getMaxX() < extent.getMinX()) ||
836
                (vp.getAdjustedExtent().getMaxY() < extent.getMinY())) {
837
            return;
838
        }
839

    
840
        // 2. Compute extent to be requested.
841
        Rectangle2D bBox = new Rectangle2D.Double();
842
        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
843

    
844
        // 3. Compute size in pixels
845
        double scalex = vp.getAffineTransform().getScaleX();
846
        double scaley = vp.getAffineTransform().getScaleY();
847
        int wImg = (int) Math.ceil(Math.abs(bBox.getWidth() * scalex) + 1);
848
        int hImg = (int) Math.ceil(Math.abs(bBox.getHeight() * scaley) + 1);
849

    
850
        Dimension sz = new Dimension(wImg, hImg);
851

    
852
        if ((wImg <= 0) || (hImg <= 0)) {
853
            return;
854
        }
855
        MyCancellable c = new MyCancellable(cancel);
856

    
857
                try {
858
//                        wImg = vp.getImageWidth();
859
//                        hImg = vp.getImageHeight();
860
                        sz = new Dimension(wImg, hImg);
861
                        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
862

    
863

    
864
                        wmsStatus.setExtent( bBox );
865
                        wmsStatus.setFormat(m_Format);
866
                        wmsStatus.setHeight( hImg );
867
                        wmsStatus.setWidth( wImg );
868
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
869
                        wmsStatus.setSrs(m_SRS);
870
                        wmsStatus.setStyles(styles);
871
                        wmsStatus.setDimensions(dimensions);
872
                        wmsStatus.setTransparency(wmsTransparency);
873
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
874

    
875
                        // begin patch; Avoid to request too small tiles.
876
                        // This generally occurs when printing
877

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

    
889
                        if (hImg < minTilePrintHeight) {
890
                                double hScale = (double) minTilePrintHeight / hImg;
891
                                wmsStatus.setHeight(minTilePrintHeight);
892
                                Rectangle2D sExtent = wmsStatus.getExtent();
893
                                Point2D initialPoint = new Point2D.Double(sExtent.getX(), sExtent.getY());
894
                                sExtent.setRect(sExtent.getX(), sExtent.getY()*hScale, sExtent.getWidth(), sExtent.getHeight()*hScale);
895
                                if (!bBox.contains(initialPoint)) {
896
                                        sExtent.setRect(sExtent.getX(), sExtent.getY() - initialPoint.getY(), sExtent.getWidth(), sExtent.getHeight());
897
                                }
898
                        }
899

    
900
                        // end patch
901
                        File f = getDriver().getMap(wmsStatus, c);
902
                        if (f == null)
903
                                return;
904
                        String nameWordFile = f.getPath() + getExtensionWorldFile();
905
                        com.iver.andami.Utilities.createTemp(nameWordFile, this.getDataWorldFile(bBox, sz));
906

    
907
                        ViewPortData vpData = new ViewPortData(
908
                                vp.getProjection(), new Extent(bBox), sz );
909
                        vpData.setMat(vp.getAffineTransform());
910

    
911
                        rasterProcess(g, vpData, f);
912

    
913
                } catch (ValidationException e) {
914
                //azabala
915
//                        if (!c.isCanceled())
916
//                                throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
917

    
918
                        if (!c.isCanceled())
919
                        {
920
                                UnknownResponseFormatExceptionType type =
921
                                        new UnknownResponseFormatExceptionType();
922
                                type.setLayerName(getName());
923
                                try {
924
                                        type.setDriverName("WMS Driver");
925
                                } catch (Exception e1) {
926
                                        e1.printStackTrace();
927
                                }
928
                                type.setFormat(m_Format);
929
                                type.setHost(host);
930
                                type.setProtocol("WMS");
931
                                DriverException exception = new DriverException("unknown_response_format", type);
932
                                throw exception;
933
                        }
934
                } catch (UnsupportedVersionException e) {
935

    
936
//                        if (!c.isCanceled())
937
//                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
938

    
939
                        if (!c.isCanceled()){
940
                                UnsuportedProtocolVersionExceptionType type =
941
                                        new UnsuportedProtocolVersionExceptionType();
942
                                type.setLayerName(getName());
943
                                try {
944
                                        type.setDriverName("WMS Driver");
945
                                } catch (Exception ex){
946
                                }
947
                                type.setUrl(host);
948
                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e, type);
949
                        }
950

    
951
                } catch (IOException e) {
952
                        /*azabala
953
                        if (!c.isCanceled())
954
                                if (callCount<MAX_RETRY_TIMES) {
955
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null);
956
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error
957
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0)
958
                                        drawTile(g, vp, cancel);
959
                                }
960
                                if (callCount == 1) {
961
                                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
962
                                }
963
                        */
964
                        if (!c.isCanceled()){
965
                                if (callCount<MAX_RETRY_TIMES) { // mess code
966
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
967
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
968
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
969

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

    
1021

    
1022
                                } //if
1023
                        }//if
1024
                }//catch
1025
                callCount--;
1026
        }
1027

    
1028
        /**
1029
         * Obtiene la extensi?n del fichero de georreferenciaci?n
1030
         * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
1031
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
1032
         */
1033
        private String getExtensionWorldFile(){
1034
                String extWorldFile = ".wld";
1035
            if(m_Format.equals("image/tif") || m_Format.equals("image/tiff"))
1036
                    extWorldFile = ".tfw";
1037
            if(m_Format.equals("image/jpeg"))
1038
                    extWorldFile = ".jpgw";
1039
            return extWorldFile;
1040
        }
1041

    
1042
        /**
1043
         * Calcula el contenido del fichero de georreferenciaci?n de una imagen.
1044
         * @param bBox Tama?o y posici?n de la imagen (en coordenadas de usuario)
1045
         * @param sz Tama?o de la imagen en pixeles.
1046
         * @return el 'WorldFile', como String.
1047
         * @throws IOException
1048
         */
1049
        public String getDataWorldFile(Rectangle2D bBox, Dimension sz) throws IOException {
1050
                StringBuffer data = new StringBuffer();
1051
            data.append((bBox.getMaxX() - bBox.getMinX())/(sz.getWidth() - 1)+"\n");
1052
            data.append("0.0\n");
1053
            data.append("0.0\n");
1054
            data.append("-"+(bBox.getMaxY() - bBox.getMinY())/(sz.getHeight() - 1)+"\n");
1055
            data.append(""+bBox.getMinX()+"\n");
1056
            data.append(""+bBox.getMaxY()+"\n");
1057
            return data.toString();
1058
        }
1059

    
1060
        /**
1061
         * Dibuja una imagen usando PxRaster
1062
         * @param g        Graphics2D en el que hay que dibujar.
1063
         * @param vpData Par?metros de visualizaci?n
1064
         * @param file La imagen en cuesti?n.
1065
         */
1066
        private void rasterProcess(Graphics2D g, ViewPortData vpData, File file) throws DriverException {
1067

    
1068
                //Creamos el PxRaster
1069
                try {
1070
                        rasterFile = new GdalFile(vpData.getProjection(), file.getAbsolutePath());
1071
                } catch (NotSupportedExtensionException e) {
1072
                        throw new DriverException("Open File Error");
1073
                }
1074
                raster = new PxRaster(rasterFile, null, rasterFile.getExtent());
1075
                grid = new Grid(rasterFile);
1076
                grid.addRenderizer(raster);
1077
                
1078
                if(status != null && firstLoad){
1079
                        status.applyStatus(this);
1080
                        firstLoad = false;
1081
                }
1082

    
1083
                //Recuperamos la pila de filtros si ya hubiese sido cargado antes
1084
                if(this.filterStack!=null)
1085
                        raster.filterStack = this.filterStack;
1086

    
1087
                raster.setTransparency(false);
1088

    
1089
                //Asignamos transparencia y orden de bandas
1090
                if(this.transparency == -1 && !firstLoad);
1091
                else
1092
                        raster.setTransparency(this.transparency);
1093

    
1094
                raster.setBand(GeoRasterFile.RED_BAND,rband);
1095
                raster.setBand(GeoRasterFile.GREEN_BAND, gband);
1096
                raster.setBand(GeoRasterFile.BLUE_BAND, bband);
1097

    
1098
                //Despues del primer pxRaster asignamos el stackManager guardado para los siguientes.
1099
                //Con esto conseguimos asignar los cambios que se hayan producido desde el cuadro de
1100
                //propiedades cuando creamos un nuevo pxRaster
1101
                if(this.stackManager != null)
1102
                        raster.setStackManager(this.stackManager);
1103

    
1104
                if(visualStatus != null){
1105
                        visualStatus.bandCount = raster.getBandCount();
1106
                        visualStatus.dataType = raster.getDataType();
1107
                }
1108

    
1109
                raster.draw(g, vpData);
1110

    
1111
                //En el primer pxRaster de una imagen obtenemos el Stack Manager para poder modificarlo
1112
                //si queremos desde las propiedades
1113

    
1114
                if(this.stackManager == null)
1115
                        this.stackManager = raster.getStackManager();
1116

    
1117
                if(this.filterStack == null)
1118
                        this.filterStack = raster.filterStack;
1119

    
1120
                //rasterFile.close();
1121
        }
1122

    
1123
        /**
1124
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D,
1125
         *                 com.iver.cit.gvsig.fmap.ViewPort,
1126
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
1127
         */
1128
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet properties)
1129
                throws DriverException {
1130
                if (isVisible() && isWithinScale(scale)){
1131
                isPrinting = true;
1132
                if (!mustTilePrint) {
1133
                        draw(null, g, viewPort, cancel,scale);
1134
                } else {
1135
                // Para no pedir imagenes demasiado grandes, vamos
1136
                // a hacer lo mismo que hace EcwFile: chunkear.
1137
                // Llamamos a drawView con cuadraditos m?s peque?os
1138
                // del BufferedImage ni caso, cuando se imprime viene con null
1139

    
1140
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
1141
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
1142
                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
1143
                            // Parte que dibuja
1144
                            try {
1145
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
1146
                                drawTile(g, vp, cancel);
1147
                                } catch (NoninvertibleTransformException e) {
1148
                                        e.printStackTrace();
1149
                                }
1150
                }
1151
                }
1152
            isPrinting = false;
1153
                }
1154
        }
1155

    
1156
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale)
1157
                throws DriverException {
1158
                draw(null, g, viewPort, cancel,scale);
1159
        }
1160

    
1161
        /**
1162
         * Devuelve el FMapWMSDriver.
1163
         *
1164
         * @return FMapWMSDriver
1165
         *
1166
         * @throws IllegalStateException
1167
         * @throws ValidationException
1168
         * @throws UnsupportedVersionException
1169
         * @throws IOException
1170
         */
1171
        private FMapWMSDriver getDriver()
1172
                throws IllegalStateException, ValidationException,
1173
                        UnsupportedVersionException, IOException {
1174
                return FMapWMSDriverFactory.getFMapDriverForURL(host);
1175
        }
1176

    
1177
        /**
1178
         * Devuelve el FMapWMSDriver.
1179
         *
1180
         * @return FMapWMSDriver
1181
         *
1182
         * @throws IllegalStateException
1183
         * @throws ValidationException
1184
         * @throws UnsupportedVersionException
1185
         * @throws IOException
1186
         */
1187
        public void setDriver(FMapWMSDriver drv) {
1188
                wms = drv;
1189
        }
1190

    
1191
        /**
1192
         * Devuelve el URL.
1193
         *
1194
         * @return URL.
1195
         */
1196
        public URL getHost() {
1197
                return host;
1198
        }
1199

    
1200
        /**
1201
         * Inserta el URL.
1202
         *
1203
         * @param host URL.
1204
         */
1205
        public void setHost(URL host) {
1206
                this.host = host;
1207
        }
1208

    
1209
        /**
1210
         * Devuelve la informaci?n de la consulta.
1211
         *
1212
         * @return String.
1213
         */
1214
        public String getInfoLayerQuery() {
1215
                return infoLayerQuery;
1216
        }
1217

    
1218
        /**
1219
         * Inserta la informaci?n de la consulta.
1220
         *
1221
         * @param infoLayerQuery String.
1222
         */
1223
        public void setInfoLayerQuery(String infoLayerQuery) {
1224
                this.infoLayerQuery = infoLayerQuery;
1225
        }
1226

    
1227
        /**
1228
         * Devuelve la consulta.
1229
         *
1230
         * @return String.
1231
         */
1232
        public String getLayerQuery() {
1233
                return layerQuery;
1234
        }
1235

    
1236
        /**
1237
         * Inserta la consulta.
1238
         *
1239
         * @param layerQuery consulta.
1240
         */
1241
        public void setLayerQuery(String layerQuery) {
1242
                this.layerQuery = layerQuery;
1243
        }
1244

    
1245
        /**
1246
         * Devuelve el formato.
1247
         *
1248
         * @return Formato.
1249
         */
1250
        public String getFormat() {
1251
                return m_Format;
1252
        }
1253

    
1254
        /**
1255
         * Inserta el formato.
1256
         *
1257
         * @param format Formato.
1258
         */
1259
        public void setFormat(String format) {
1260
                m_Format = format;
1261
        }
1262

    
1263
        /**
1264
         * Devuelve el SRS.
1265
         *
1266
         * @return SRS.
1267
         */
1268
        public String getSRS() {
1269
                return m_SRS;
1270
        }
1271

    
1272
        /**
1273
         * Inserta el SRS.
1274
         *
1275
         * @param m_srs SRS.
1276
         */
1277
        public void setSRS(String m_srs) {
1278
                m_SRS = m_srs;
1279
        }
1280

    
1281
        /**
1282
         * Inserta la extensi?n total de la capa.
1283
         *
1284
         * @param fullExtent Rect?ngulo.
1285
         */
1286
        public void setFullExtent(Rectangle2D fullExtent) {
1287
                this.fullExtent = fullExtent;
1288
        }
1289

    
1290
        public HashMap getProperties() {
1291
                HashMap info = new HashMap();
1292
        String[] layerNames = getLayerQuery().split(",");
1293
        Vector layers = new Vector(layerNames.length);
1294
        try {
1295
            if(getDriver().connect(null)){
1296
                for (int i = 0; i < layerNames.length; i++) {
1297
                    layers.add(i, getDriver().getLayer(layerNames[i]));
1298
                }
1299
                info.put("name", getName());
1300
                info.put("selectedLayers", layers);
1301
                info.put("host", getHost());
1302
                info.put("srs", getSRS());
1303
                info.put("format", getFormat());
1304
                info.put("wmsTransparency", new Boolean(wmsTransparency));
1305
                info.put("styles", styles);
1306
                info.put("dimensions", dimensions);
1307
                info.put("fixedSize", fixedSize);
1308
                return info;
1309
            }
1310
        } catch (Exception e) {
1311
            e.printStackTrace();
1312
        }
1313
        return null;
1314
        }
1315

    
1316
        /**
1317
         * Asignar el estado del raster
1318
         * @param status
1319
         */
1320
        public void setStatus(StatusRasterInterface status){
1321
                this.status = status;
1322
        }
1323

    
1324
        /**
1325
         * Obtiene el estado del raster
1326
         * @return
1327
         */
1328
        public StatusRasterInterface getStatus(){
1329
                return this.status;
1330
        }
1331

    
1332
        /* (non-Javadoc)
1333
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getAttributes()
1334
         */
1335
        public ArrayList getAttributes() {
1336
                if(rasterFile != null){
1337
                        ArrayList attr = new ArrayList();
1338
                        String dataType = "Byte";
1339
                        if (rasterFile.getDataType() == DataBuffer.TYPE_BYTE) dataType = "Byte";
1340
                        else if (visualStatus.dataType == DataBuffer.TYPE_SHORT)
1341
                                dataType = "Short";
1342
                        else if (visualStatus.dataType == DataBuffer.TYPE_USHORT)
1343
                                dataType = "Unsigned Short";
1344
                        else if (visualStatus.dataType == DataBuffer.TYPE_INT)
1345
                                dataType = "Integer";
1346
                        else if (visualStatus.dataType == DataBuffer.TYPE_FLOAT)
1347
                                dataType = "Float";
1348
                        else if (visualStatus.dataType == DataBuffer.TYPE_DOUBLE)
1349
                                dataType = "Double";
1350
                        else
1351
                                dataType = "Unknown";
1352

    
1353
                        Object [][] a = {
1354
                                {"Filename",rasterFile.getName().substring(rasterFile.getName().lastIndexOf("/")+1, rasterFile.getName().length())},
1355
                                {"Filesize",new Long(0)},
1356
                                {"Width",new Integer((int)this.getWidth())},
1357
                                {"Height", new Integer((int)this.getHeight())},
1358
                                {"Bands", new Integer(visualStatus.bandCount)},
1359
                                {"BandDataType", dataType}
1360
                        };
1361
                        for (int i=0; i<a.length; i++)
1362
                                attr.add(a[i]);
1363

    
1364
                        return attr;
1365
                }
1366
                return  null;
1367
        }
1368

    
1369
        /* (non-Javadoc)
1370
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getFilterStack()
1371
         */
1372
        public RasterFilterStack getFilterStack() {
1373
                if(raster!=null)
1374
                        return raster.filterStack;
1375
                return null;
1376
        }
1377
        /* (non-Javadoc)
1378
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getHeight()
1379
         */
1380
        public double getHeight() {
1381
                return visualStatus.height;
1382
        }
1383

    
1384
        /* (non-Javadoc)
1385
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxX()
1386
         */
1387
        public double getMaxX() {
1388
                return visualStatus.maxX;
1389
        }
1390

    
1391
        /* (non-Javadoc)
1392
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxY()
1393
         */
1394
        public double getMaxY() {
1395
                return visualStatus.maxY;
1396
        }
1397

    
1398
        /* (non-Javadoc)
1399
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinX()
1400
         */
1401
        public double getMinX() {
1402
                return visualStatus.minX;
1403
        }
1404

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

    
1455
        /* (non-Javadoc)
1456
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPosWC(double, double)
1457
         */
1458
        public void setPosWC(double x, double y) {
1459
                this.posXWC = x;
1460
                this.posYWC = y;
1461
        }
1462

    
1463
        /* (non-Javadoc)
1464
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setRGB(int, int, int)
1465
         */
1466
        public void setRGB(int r, int g, int b) {
1467
                this.r = r;
1468
                this.g = g;
1469
                this.b = b;
1470
        }
1471
        /* (non-Javadoc)
1472
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setSource(com.iver.cit.gvsig.fmap.layers.RasterAdapter)
1473
         */
1474
        public void setSource(RasterAdapter ra) {
1475
        }
1476
        /**
1477
         * @return Returns the raster.
1478
         */
1479
        public PxRaster getPxRaster() {
1480
                return raster;
1481
        }
1482
        /**
1483
         * @return Returns the rasterFile.
1484
         */
1485
        public GeoRasterFile getGeoRasterFile() {
1486
                return rasterFile;
1487
        }
1488

    
1489
        public void setTransparency(int trans) {
1490
                this.transparency = trans;
1491
        }
1492

    
1493
        /**
1494
         * Sets the R-band.
1495
         *
1496
         * Asigna la banda R.
1497
         * @param r
1498
         */
1499
        public void setBandR(int r){
1500
                this.rband = r;
1501
        }
1502

    
1503
        /**
1504
         * Sets the G-band.
1505
         *
1506
         * Asigna la banda G
1507
         * @param g
1508
         */
1509
        public void setBandG(int g){
1510
                this.gband = g;
1511
        }
1512

    
1513
        /**
1514
         * Sets the B-band.
1515
         *
1516
         * Asigna la banda B
1517
         * @param b
1518
         */
1519
        public void setBandB(int b){
1520
                this.bband = b;
1521
        }
1522

    
1523
    /**
1524
     * @return Returns the wmsTransparency.
1525
     */
1526
    public boolean isWmsTransparent() {
1527
        return wmsTransparency;
1528
    }
1529

    
1530
    /**
1531
     * @param wmsTransparency The wmsTransparency to set.
1532
     */
1533
    public void setWmsTransparency(boolean wmsTransparency) {
1534
        this.wmsTransparency = wmsTransparency;
1535
    }
1536

    
1537
     /**
1538
     * @param styles
1539
     */
1540
    public void setStyles(Vector styles) {
1541
            //laura:
1542
            //layer query is built with the layer in reverse order
1543
            // so here we build the styles upside-down.
1544
            if (styles != null)
1545
            {
1546
                    this.styles = new Vector();
1547
                    for(int i = styles.size()-1; i>=0; i--)
1548
                    {
1549
                            this.styles.add(styles.elementAt(i));
1550
                    }
1551
            }
1552
    }
1553

    
1554
    /**
1555
     * Sets the dimension vector that is a list of key-value pairs containing
1556
     * the name of the dimension and the value for it
1557
     * @param dimensions
1558
     */
1559
    public void setDimensions(Vector dimensions) {
1560
        this.dimensions = dimensions;
1561
    }
1562

    
1563
    /**
1564
     * Sets the set of URLs that should be accessed for each operation performed
1565
     * to the server.
1566
     *
1567
     * @param onlineResources
1568
     */
1569
        public void setOnlineResources(Hashtable onlineResources) {
1570
                this.onlineResources = onlineResources;
1571
        }
1572

    
1573
    /**
1574
     * Gets the URL that should be accessed for an operation performed
1575
     * to the server.
1576
     *
1577
     * @param onlineResources
1578
     */
1579
        public String getOnlineResource(String operation) {
1580
                return ((String) onlineResources.get(operation));
1581
        }
1582

    
1583
        /**
1584
         * When a server is not fully featured and it only can serve constant map
1585
         * sizes this value must be set. It expresses the size in pixels (width, height)
1586
         * that the map will be requested.
1587
         * @param Dimension sz
1588
         */
1589
        public void setFixedSize(Dimension sz) {
1590
                fixedSize = sz;
1591
        }
1592

    
1593
        /**
1594
         * Tells whether if this layer must deal with the server with the constant-size
1595
         * limitations or not.
1596
         * @return boolean.
1597
         */
1598
        private boolean isSizeFixed() {
1599
                return fixedSize != null && fixedSize.getWidth() > 0 && fixedSize.getHeight() > 0;
1600
        }
1601

    
1602
        /**
1603
         * If it is true, this layer accepts GetFeatureInfo operations. This WMS operations
1604
         * maps to FMap's infoByPoint(p) operation.
1605
         * @param b
1606
         */
1607
        public void setQueryable(boolean b) {
1608
                queryable = b;
1609
        }
1610

    
1611
        /**
1612
         * Creates the part of a OGC's MapContext document that would describe this
1613
         * layer(s).
1614
         * @param version, The desired version of the resulting document. (1.1.0)
1615
         * @return String containing the xml.
1616
         * @throws UnsupportedVersionException
1617
         */
1618
        public String toMapContext(String mapContextVersion) {
1619
                XmlBuilder xml = new XmlBuilder();
1620
                FMapWMSDriver drv;
1621
                try {
1622
                        drv = getDriver();
1623
                } catch (Exception e) {
1624
                        return xml.toString();
1625
                }
1626
                String[] layerNames = getLayerQuery().split(",");
1627
                String[] styleNames = (String[]) styles.toArray(new String[0]);
1628
                for (int i = 0; i < layerNames.length; i++) {
1629
                        WMSLayerNode layer = drv.getLayer(layerNames[i]);
1630
                        HashMap xmlAttrs = new HashMap();
1631

    
1632
                        // <Layer>
1633
                        xmlAttrs.put(WebMapContextTags.HIDDEN, !isVisible()+"");
1634
                        xmlAttrs.put(WebMapContextTags.QUERYABLE, queryable+"");
1635
                        xml.openTag(WebMapContextTags.LAYER, xmlAttrs);
1636
                        xmlAttrs.clear();
1637
                        if (mapContextVersion.equals("1.1.0") || mapContextVersion.equals("1.0.0")) {
1638
                                // <Server>
1639
                                xmlAttrs.put(WebMapContextTags.SERVICE, WebMapContextTags.WMS);
1640
                                xmlAttrs.put(WebMapContextTags.VERSION, drv.getVersion());
1641
                                xmlAttrs.put(WebMapContextTags.SERVER_TITLE, drv.getServiceTitle());
1642
                                xml.openTag(WebMapContextTags.SERVER, xmlAttrs);
1643
                                xmlAttrs.clear();
1644

    
1645
                                        // <OnlineResource>
1646
                                        xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1647
                                        xmlAttrs.put(WebMapContextTags.XLINK_HREF, getHost().toString());
1648
                                        xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1649
                                        xmlAttrs.clear();
1650
                                        // </OnlineResource>
1651

    
1652
                                xml.closeTag();
1653
                                // </Server>
1654

    
1655
                                // <Name>
1656
                                xml.writeTag(WebMapContextTags.NAME, layer.getName().trim());
1657
                                // </Name>
1658

    
1659
                                // <Title>
1660
                                xml.writeTag(WebMapContextTags.TITLE, layer.getTitle().trim());
1661
                                //?xml.writeTag(WebMapContextTags.TITLE, getName().trim());
1662
                                // </Title>
1663

    
1664
                                // <Abstract>
1665
                                if (layer.getAbstract() != null)
1666
                                        xml.writeTag(WebMapContextTags.ABSTRACT, layer.getAbstract());
1667
                                // </Abstract>
1668

    
1669
                                // <SRS> (a list of available SRS for the enclosing layer)
1670
                                String[] strings = (String[]) layer.getAllSrs().toArray(new String[0]);
1671
                                String mySRS = strings[0];
1672
                                for (int j = 1; j < strings.length; j++) {
1673
                                        mySRS += ","+strings[j];
1674
                                }
1675
                                xml.writeTag(WebMapContextTags.SRS, mySRS);
1676
                                // </SRS>
1677

    
1678
                                // <FormatList>
1679
                                xml.openTag(WebMapContextTags.FORMAT_LIST);
1680
                                        strings = (String[]) drv.getFormats().toArray(new String[0]);
1681
                                        for (int j = 0; j < strings.length; j++) {
1682
                    // <Format>
1683
                                                String str = strings[j].trim();
1684
                                                if (str.equals(getFormat()))
1685
                                                        xml.writeTag(WebMapContextTags.FORMAT, str, WebMapContextTags.CURRENT, "1");
1686
                                                else
1687
                                                        xml.writeTag(WebMapContextTags.FORMAT, str);
1688
                    // </Format>
1689
                                        }
1690
                                xml.closeTag();
1691
                                // </FormatList>
1692

    
1693
                                // <StyleList>
1694
                                xml.openTag(WebMapContextTags.STYLE_LIST);
1695

    
1696
                                        if (layer.getStyles().size()>0) {
1697
                                                for (int j = 0; j < layer.getStyles().size(); j++) {
1698
                                                        // <Style>
1699
                                                        FMapWMSStyle st = (FMapWMSStyle) layer.getStyles().get(j);
1700
                                                        if (st.name.equals(styleNames[i]))
1701
                                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1702
                                                        xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1703
                                                        xmlAttrs.clear();
1704

    
1705
                                                                // <Name>
1706
                                                                xml.writeTag(WebMapContextTags.NAME, st.name);
1707
                                                                // </Name>
1708

    
1709
                                                                // <Title>
1710
                                                                xml.writeTag(WebMapContextTags.TITLE, st.title);
1711
                                                                // </Title>
1712

    
1713
                                                                // <LegendURL width="180" format="image/gif" height="50">
1714
                                                                        // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1715
                                                                        // </OnlineResource>
1716
                                                                // </LegendURL>
1717
                                                        xml.closeTag();
1718
                                                        // </Style>
1719

    
1720
                                                }
1721

    
1722
                                        } else {
1723
                                                // Create fake style (for compatibility issues)
1724
                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1725
                                                // <Style>
1726
                                                xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1727
                                                        xmlAttrs.clear();
1728
                                                        // <Name>
1729
                                                        xml.writeTag(WebMapContextTags.NAME, "default");
1730
                                                        // </Name>
1731

    
1732
                                                        // <Title>
1733
                                                        xml.writeTag(WebMapContextTags.TITLE, "default");
1734
                                                        // </Title>
1735

    
1736
//                                                        // <LegendURL width="180" format="image/gif" height="50">
1737
//                                                        xmlAttrs.put(WebMapContextTags.WIDTH, "0");
1738
//                                                        xmlAttrs.put(WebMapContextTags.HEIGHT, "0");
1739
//                                                        xmlAttrs.put(WebMapContextTags.FORMAT.toLowerCase(), "image/gif");
1740
//                                                        xml.openTag(WebMapContextTags.LEGEND_URL, xmlAttrs);
1741
//                                                        xmlAttrs.clear();
1742
//                                                                // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1743
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1744
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_HREF, "http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif");
1745
//                                                                xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1746
//                                                                // </OnlineResource>
1747
//                                                    // </LegendURL>
1748
//                                                        xml.closeTag();
1749
                                                // </Style>
1750
                                                xml.closeTag();
1751
                                        }
1752
                                // </StyleList>
1753
                                xml.closeTag();
1754
                                if (mapContextVersion.compareTo("1.0.0") > 0) {
1755
                                // <DimensionList>
1756
                                        xml.openTag(WebMapContextTags.DIMENSION_LIST);
1757
                                        // <Dimension>
1758
                                        // </Dimension>
1759
                                        xml.closeTag();
1760
                                // </DimensionList>
1761
                                }
1762
                        } else {
1763
                                xml.writeTag("ERROR", PluginServices.getText(this, "unsupported_map_context_version"));
1764
                        }
1765
                        // </Layer>
1766
                        xml.closeTag();
1767
                }
1768
                return xml.getXML();
1769
        }
1770

    
1771
        public ImageIcon getTocImageIcon() {
1772
                return new ImageIcon(PluginServices.getPluginServices("com.iver.cit.gvsig.wms").getClassLoader().getResource("images/icoLayer.png"));
1773
        }
1774

    
1775
        /*
1776
         *  (non-Javadoc)
1777
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1778
         */
1779
        public int[] getTileSize() {
1780
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1781
                return size;
1782
        }
1783
        /*
1784
         *  (non-Javadoc)
1785
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1786
         */
1787
        public boolean isTiled() {
1788
                return mustTileDraw;
1789
        }
1790

    
1791
        public Image getImageLegend() {
1792
                try {
1793
                        if (wms == null)
1794
                                wms = getDriver();
1795
                        if (wms.hasLegendGraphic()) {
1796
                                wmsStatus.setOnlineResource((String) onlineResources
1797
                                                .get("GetLegendGraphic"));
1798
                                String path = getPathImage();// File legend =
1799
                                                                                                // getDriver().getLegendGraphic(wmsStatus,
1800
                                                                                                // layerQuery, null);
1801
                                Image img = null;
1802
                                if ((path != null) && (path.length() > 0))
1803
                                        img = new ImageIcon(path).getImage();
1804
                                return img;
1805
                        }
1806
                } catch (Exception e) {
1807
                }
1808
                return null;
1809
        }
1810

    
1811
        public String getPathImage() {
1812
                try {
1813
                        File legend = getDriver().getLegendGraphic(wmsStatus, layerQuery, null);
1814
                        return legend.getAbsolutePath();
1815
                }catch(Exception e){
1816
                        //e.printStackTrace();
1817
                        return null;
1818
                }
1819
        }
1820

    
1821
        /**
1822
         * Obtiene el grid asociado al raster que hay cargado en ese momento
1823
         * @return grid
1824
         */
1825
        public Grid getGrid(){
1826
                return grid;
1827
        }
1828
        
1829
        /**
1830
         * Obtiene el tipo de dato de la capa raster
1831
         * @return Entero que representa el tipo de dato de la capa raster.
1832
         */
1833
        public int getDataType() {
1834
                return rasterFile.getDataType();
1835
        }
1836
        public boolean isQueryable(){
1837
                return queryable;
1838
        }
1839
}