Statistics
| Revision:

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

History | View | Annotate | Download (56.7 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
        }
696

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

    
702

    
703
                // This is the extent that will be requested
704
                Rectangle2D bBox = getFullExtent();
705
                MyCancellable c = new MyCancellable(cancel);
706

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

    
724
                        if(status!=null && firstLoad){
725
                                status.applyStatus(this);
726
                                firstLoad = false;
727
                        }
728

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

    
734
                        ViewPortData vpData = new ViewPortData(
735
                                vp.getProjection(), new Extent(extent), fixedSize );
736
                        vpData.setMat(vp.getAffineTransform());
737

    
738
                        rasterProcess(g, vpData, f);
739

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

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

    
793

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

    
815

    
816
                                } // mess code
817
                        }
818
                }
819
                callCount--; // mess code
820
        }
821

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

    
837
        // 2. Compute extent to be requested.
838
        Rectangle2D bBox = new Rectangle2D.Double();
839
        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
840

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

    
847
        // begin patch; Avoid request too large (these cases should be product of a bug in
848
        // Tiling) when printing
849
        if (wImg > maxTilePrintWidth +5 || hImg > maxTileDrawHeight +5) {
850
                // Copied and pasted from drawTile
851
                Point2D p = vp.getOffset();
852
                Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
853
                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
854
                        tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
855
                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
856
                                // drawing part
857
                                try {
858
                                        ViewPort myViewPort = tiles.getTileViewPort(vp, tileNr);
859
                                        drawTile(g, myViewPort, cancel);
860
                                } catch (NoninvertibleTransformException e) {
861
                                        e.printStackTrace();
862
                                }
863
                        }
864
                        return;
865
        }
866
        // end patch
867

    
868
        Dimension sz = new Dimension(wImg, hImg);
869

    
870
        if ((wImg <= 0) || (hImg <= 0)) {
871
            return;
872
        }
873
        MyCancellable c = new MyCancellable(cancel);
874

    
875
                try {
876
//                        wImg = vp.getImageWidth();
877
//                        hImg = vp.getImageHeight();
878
                        sz = new Dimension(wImg, hImg);
879
                        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
880

    
881

    
882
                        wmsStatus.setExtent( bBox );
883
                        wmsStatus.setFormat(m_Format);
884
                        wmsStatus.setHeight( hImg );
885
                        wmsStatus.setWidth( wImg );
886
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
887
                        wmsStatus.setSrs(m_SRS);
888
                        wmsStatus.setStyles(styles);
889
                        wmsStatus.setDimensions(dimensions);
890
                        wmsStatus.setTransparency(wmsTransparency);
891
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
892

    
893
                        // begin patch; Avoid to request too small tiles.
894
                        // This generally occurs when printing
895

    
896
                        if (wImg < minTilePrintWidth) {
897
                                double wScale = (double) minTilePrintWidth / wImg;
898
                                wmsStatus.setWidth(minTilePrintWidth);
899
                                Rectangle2D sExtent = wmsStatus.getExtent();
900
                                Point2D initialPoint = new Point2D.Double(sExtent.getX(), sExtent.getY());
901
                                sExtent.setRect(sExtent.getX()*wScale, sExtent.getY(), sExtent.getWidth()*wScale, sExtent.getHeight());
902
                                if (!bBox.contains(initialPoint)) {
903
                                        sExtent.setRect(sExtent.getX() - initialPoint.getX(), sExtent.getY(), sExtent.getWidth(), sExtent.getHeight());
904
                                }
905
                        }
906

    
907
                        if (hImg < minTilePrintHeight) {
908
                                double hScale = (double) minTilePrintHeight / hImg;
909
                                wmsStatus.setHeight(minTilePrintHeight);
910
                                Rectangle2D sExtent = wmsStatus.getExtent();
911
                                Point2D initialPoint = new Point2D.Double(sExtent.getX(), sExtent.getY());
912
                                sExtent.setRect(sExtent.getX(), sExtent.getY()*hScale, sExtent.getWidth(), sExtent.getHeight()*hScale);
913
                                if (!bBox.contains(initialPoint)) {
914
                                        sExtent.setRect(sExtent.getX(), sExtent.getY() - initialPoint.getY(), sExtent.getWidth(), sExtent.getHeight());
915
                                }
916
                        }
917

    
918
                        // end patch
919
                        File f = getDriver().getMap(wmsStatus, c);
920
                        if (f == null)
921
                                return;
922
                        String nameWordFile = f.getPath() + getExtensionWorldFile();
923
                        com.iver.andami.Utilities.createTemp(nameWordFile, this.getDataWorldFile(bBox, sz));
924

    
925
                        ViewPortData vpData = new ViewPortData(
926
                                vp.getProjection(), new Extent(bBox), sz );
927
                        vpData.setMat(vp.getAffineTransform());
928

    
929
                        rasterProcess(g, vpData, f);
930

    
931
                } catch (ValidationException e) {
932
                //azabala
933
//                        if (!c.isCanceled())
934
//                                throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
935

    
936
                        if (!c.isCanceled())
937
                        {
938
                                UnknownResponseFormatExceptionType type =
939
                                        new UnknownResponseFormatExceptionType();
940
                                type.setLayerName(getName());
941
                                try {
942
                                        type.setDriverName("WMS Driver");
943
                                } catch (Exception e1) {
944
                                        e1.printStackTrace();
945
                                }
946
                                type.setFormat(m_Format);
947
                                type.setHost(host);
948
                                type.setProtocol("WMS");
949
                                DriverException exception = new DriverException("unknown_response_format", type);
950
                                throw exception;
951
                        }
952
                } catch (UnsupportedVersionException e) {
953

    
954
//                        if (!c.isCanceled())
955
//                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
956

    
957
                        if (!c.isCanceled()){
958
                                UnsuportedProtocolVersionExceptionType type =
959
                                        new UnsuportedProtocolVersionExceptionType();
960
                                type.setLayerName(getName());
961
                                try {
962
                                        type.setDriverName("WMS Driver");
963
                                } catch (Exception ex){
964
                                }
965
                                type.setUrl(host);
966
                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e, type);
967
                        }
968

    
969
                } catch (IOException e) {
970
                        /*azabala
971
                        if (!c.isCanceled())
972
                                if (callCount<MAX_RETRY_TIMES) {
973
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null);
974
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error
975
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0)
976
                                        drawTile(g, vp, cancel);
977
                                }
978
                                if (callCount == 1) {
979
                                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
980
                                }
981
                        */
982
                        if (!c.isCanceled()){
983
                                if (callCount<MAX_RETRY_TIMES) { // mess code
984
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawTileSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
985
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
986
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
987

    
988
                                        //FIXME Aqu? deberiamos llamar a drawTile o a drawFixedSize????
989
                                        drawTile(g, vp, cancel); // mess code
990
                                } // mess code
991
                        }
992
                        if (callCount == 1) { // mess code
993
                                ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
994
                                type.setLayerName(getName());
995
                                try {
996
                                        type.setDriverName("WMS Driver");
997
                                } catch (Exception e1) {}
998
                                type.setHost(host);
999
                                throw new DriverException(PluginServices.
1000
                                                        getText(this, "connect_error"), e, type);
1001
                        }//if
1002
                } catch (WMSException e) {
1003
                        /*azabala
1004
                        if (!c.isCanceled()) {
1005
                                if (callCount<MAX_RETRY_TIMES) {
1006
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawTile() ] Failed in trying " + callCount + "/" + MAX_RETRY_TIMES +" \n", null);
1007
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error
1008
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0)
1009
                                        drawTile(g, vp, cancel);
1010
                                }
1011
                                if (callCount == 1) {
1012
                                        if (!isPrinting) {
1013
                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
1014
                                                this.setVisible(false);
1015
                                        }
1016
                                }
1017
                        }
1018
                        */
1019
                        if (!c.isCanceled()) {
1020
                                if (callCount<MAX_RETRY_TIMES) { // mess code
1021
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
1022
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
1023
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
1024
                                        drawTile(g, vp, cancel);
1025
                                } // mess code
1026
                                if (callCount == 1) { // mess code
1027
//                azabala                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
1028
                                        WMSDriverExceptionType type = new WMSDriverExceptionType();
1029
                                        type.setLayerName(getName());
1030
                                        try {
1031
                                                type.setDriverName("WMS Driver");
1032
                                        } catch (Exception e1) {
1033
                                        }
1034
                                        type.setWcsStatus(this.wmsStatus);
1035
                                        if (!isPrinting)
1036
                                                this.setVisible(false);
1037
                                        throw new DriverException("Error WMS", e,  type);
1038

    
1039

    
1040
                                } //if
1041
                        }//if
1042
                }//catch
1043
                callCount--;
1044
        }
1045

    
1046
        /**
1047
         * Obtiene la extensi?n del fichero de georreferenciaci?n
1048
         * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
1049
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
1050
         */
1051
        private String getExtensionWorldFile(){
1052
                String extWorldFile = ".wld";
1053
            if(m_Format.equals("image/tif") || m_Format.equals("image/tiff"))
1054
                    extWorldFile = ".tfw";
1055
            if(m_Format.equals("image/jpeg"))
1056
                    extWorldFile = ".jpgw";
1057
            return extWorldFile;
1058
        }
1059

    
1060
        /**
1061
         * Calcula el contenido del fichero de georreferenciaci?n de una imagen.
1062
         * @param bBox Tama?o y posici?n de la imagen (en coordenadas de usuario)
1063
         * @param sz Tama?o de la imagen en pixeles.
1064
         * @return el 'WorldFile', como String.
1065
         * @throws IOException
1066
         */
1067
        public String getDataWorldFile(Rectangle2D bBox, Dimension sz) throws IOException {
1068
                StringBuffer data = new StringBuffer();
1069
            data.append((bBox.getMaxX() - bBox.getMinX())/(sz.getWidth() - 1)+"\n");
1070
            data.append("0.0\n");
1071
            data.append("0.0\n");
1072
            data.append("-"+(bBox.getMaxY() - bBox.getMinY())/(sz.getHeight() - 1)+"\n");
1073
            data.append(""+bBox.getMinX()+"\n");
1074
            data.append(""+bBox.getMaxY()+"\n");
1075
            return data.toString();
1076
        }
1077

    
1078
        /**
1079
         * Dibuja una imagen usando PxRaster
1080
         * @param g        Graphics2D en el que hay que dibujar.
1081
         * @param vpData Par?metros de visualizaci?n
1082
         * @param file La imagen en cuesti?n.
1083
         */
1084
        private void rasterProcess(Graphics2D g, ViewPortData vpData, File file) throws DriverException {
1085

    
1086
                //Creamos el PxRaster
1087
                try {
1088
                        rasterFile = new GdalFile(vpData.getProjection(), file.getAbsolutePath());
1089
                } catch (NotSupportedExtensionException e) {
1090
                        throw new DriverException("Open File Error");
1091
                }
1092
                raster = new PxRaster(rasterFile, null, rasterFile.getExtent());
1093
                grid = new Grid(rasterFile);
1094
                grid.addRenderizer(raster);
1095

    
1096
                if(status != null && firstLoad){
1097
                        status.applyStatus(this);
1098
                        firstLoad = false;
1099
                }
1100

    
1101
                //Recuperamos la pila de filtros si ya hubiese sido cargado antes
1102
                if(this.filterStack!=null)
1103
                        raster.filterStack = this.filterStack;
1104

    
1105
                raster.setTransparency(false);
1106

    
1107
                //Asignamos transparencia y orden de bandas
1108
                if(this.transparency == -1 && !firstLoad);
1109
                else
1110
                        raster.setTransparency(this.transparency);
1111

    
1112
                raster.setBand(GeoRasterFile.RED_BAND,rband);
1113
                raster.setBand(GeoRasterFile.GREEN_BAND, gband);
1114
                raster.setBand(GeoRasterFile.BLUE_BAND, bband);
1115

    
1116
                //Despues del primer pxRaster asignamos el stackManager guardado para los siguientes.
1117
                //Con esto conseguimos asignar los cambios que se hayan producido desde el cuadro de
1118
                //propiedades cuando creamos un nuevo pxRaster
1119
                if(this.stackManager != null)
1120
                        raster.setStackManager(this.stackManager);
1121

    
1122
                if(visualStatus != null){
1123
                        visualStatus.bandCount = raster.getBandCount();
1124
                        visualStatus.dataType = raster.getDataType();
1125
                }
1126

    
1127
                raster.draw(g, vpData);
1128

    
1129
                //En el primer pxRaster de una imagen obtenemos el Stack Manager para poder modificarlo
1130
                //si queremos desde las propiedades
1131

    
1132
                if(this.stackManager == null)
1133
                        this.stackManager = raster.getStackManager();
1134

    
1135
                if(this.filterStack == null)
1136
                        this.filterStack = raster.filterStack;
1137

    
1138
                //rasterFile.close();
1139
        }
1140

    
1141
        /**
1142
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D,
1143
         *                 com.iver.cit.gvsig.fmap.ViewPort,
1144
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
1145
         */
1146
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet properties)
1147
                throws DriverException {
1148
                if (isVisible() && isWithinScale(scale)){
1149
                isPrinting = true;
1150
                if (!mustTilePrint) {
1151
                        draw(null, g, viewPort, cancel,scale);
1152
                } else {
1153
                // Para no pedir imagenes demasiado grandes, vamos
1154
                // a hacer lo mismo que hace EcwFile: chunkear.
1155
                // Llamamos a drawView con cuadraditos m?s peque?os
1156
                // del BufferedImage ni caso, cuando se imprime viene con null
1157

    
1158
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
1159
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
1160
                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
1161
                            // Parte que dibuja
1162
                            try {
1163
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
1164
                                drawTile(g, vp, cancel);
1165
                                } catch (NoninvertibleTransformException e) {
1166
                                        e.printStackTrace();
1167
                                }
1168
                }
1169
                }
1170
            isPrinting = false;
1171
                }
1172
        }
1173

    
1174
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale)
1175
                throws DriverException {
1176
                draw(null, g, viewPort, cancel,scale);
1177
        }
1178

    
1179
        /**
1180
         * Devuelve el FMapWMSDriver.
1181
         *
1182
         * @return FMapWMSDriver
1183
         *
1184
         * @throws IllegalStateException
1185
         * @throws ValidationException
1186
         * @throws UnsupportedVersionException
1187
         * @throws IOException
1188
         */
1189
        private FMapWMSDriver getDriver()
1190
                throws IllegalStateException, ValidationException,
1191
                        UnsupportedVersionException, IOException {
1192
                return FMapWMSDriverFactory.getFMapDriverForURL(host);
1193
        }
1194

    
1195
        /**
1196
         * Devuelve el FMapWMSDriver.
1197
         *
1198
         * @return FMapWMSDriver
1199
         *
1200
         * @throws IllegalStateException
1201
         * @throws ValidationException
1202
         * @throws UnsupportedVersionException
1203
         * @throws IOException
1204
         */
1205
        public void setDriver(FMapWMSDriver drv) {
1206
                wms = drv;
1207
        }
1208

    
1209
        /**
1210
         * Devuelve el URL.
1211
         *
1212
         * @return URL.
1213
         */
1214
        public URL getHost() {
1215
                return host;
1216
        }
1217

    
1218
        /**
1219
         * Inserta el URL.
1220
         *
1221
         * @param host URL.
1222
         */
1223
        public void setHost(URL host) {
1224
                this.host = host;
1225
        }
1226

    
1227
        /**
1228
         * Devuelve la informaci?n de la consulta.
1229
         *
1230
         * @return String.
1231
         */
1232
        public String getInfoLayerQuery() {
1233
                return infoLayerQuery;
1234
        }
1235

    
1236
        /**
1237
         * Inserta la informaci?n de la consulta.
1238
         *
1239
         * @param infoLayerQuery String.
1240
         */
1241
        public void setInfoLayerQuery(String infoLayerQuery) {
1242
                this.infoLayerQuery = infoLayerQuery;
1243
        }
1244

    
1245
        /**
1246
         * Devuelve la consulta.
1247
         *
1248
         * @return String.
1249
         */
1250
        public String getLayerQuery() {
1251
                return layerQuery;
1252
        }
1253

    
1254
        /**
1255
         * Inserta la consulta.
1256
         *
1257
         * @param layerQuery consulta.
1258
         */
1259
        public void setLayerQuery(String layerQuery) {
1260
                this.layerQuery = layerQuery;
1261
        }
1262

    
1263
        /**
1264
         * Devuelve el formato.
1265
         *
1266
         * @return Formato.
1267
         */
1268
        public String getFormat() {
1269
                return m_Format;
1270
        }
1271

    
1272
        /**
1273
         * Inserta el formato.
1274
         *
1275
         * @param format Formato.
1276
         */
1277
        public void setFormat(String format) {
1278
                m_Format = format;
1279
        }
1280

    
1281
        /**
1282
         * Devuelve el SRS.
1283
         *
1284
         * @return SRS.
1285
         */
1286
        public String getSRS() {
1287
                return m_SRS;
1288
        }
1289

    
1290
        /**
1291
         * Inserta el SRS.
1292
         *
1293
         * @param m_srs SRS.
1294
         */
1295
        public void setSRS(String m_srs) {
1296
                m_SRS = m_srs;
1297
        }
1298

    
1299
        /**
1300
         * Inserta la extensi?n total de la capa.
1301
         *
1302
         * @param fullExtent Rect?ngulo.
1303
         */
1304
        public void setFullExtent(Rectangle2D fullExtent) {
1305
                this.fullExtent = fullExtent;
1306
        }
1307

    
1308
        public HashMap getProperties() {
1309
                HashMap info = new HashMap();
1310
        String[] layerNames = getLayerQuery().split(",");
1311
        Vector layers = new Vector(layerNames.length);
1312
        try {
1313
            if(getDriver().connect(null)){
1314
                for (int i = 0; i < layerNames.length; i++) {
1315
                    layers.add(i, getDriver().getLayer(layerNames[i]));
1316
                }
1317
                info.put("name", getName());
1318
                info.put("selectedLayers", layers);
1319
                info.put("host", getHost());
1320
                info.put("srs", getSRS());
1321
                info.put("format", getFormat());
1322
                info.put("wmsTransparency", new Boolean(wmsTransparency));
1323
                info.put("styles", styles);
1324
                info.put("dimensions", dimensions);
1325
                info.put("fixedSize", fixedSize);
1326
                return info;
1327
            }
1328
        } catch (Exception e) {
1329
            e.printStackTrace();
1330
        }
1331
        return null;
1332
        }
1333

    
1334
        /**
1335
         * Asignar el estado del raster
1336
         * @param status
1337
         */
1338
        public void setStatus(StatusRasterInterface status){
1339
                this.status = status;
1340
        }
1341

    
1342
        /**
1343
         * Obtiene el estado del raster
1344
         * @return
1345
         */
1346
        public StatusRasterInterface getStatus(){
1347
                return this.status;
1348
        }
1349

    
1350
        /* (non-Javadoc)
1351
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getAttributes()
1352
         */
1353
        public ArrayList getAttributes() {
1354
                if(rasterFile != null){
1355
                        ArrayList attr = new ArrayList();
1356
                        String dataType = "Byte";
1357
                        if (rasterFile.getDataType() == DataBuffer.TYPE_BYTE) dataType = "Byte";
1358
                        else if (visualStatus.dataType == DataBuffer.TYPE_SHORT)
1359
                                dataType = "Short";
1360
                        else if (visualStatus.dataType == DataBuffer.TYPE_USHORT)
1361
                                dataType = "Unsigned Short";
1362
                        else if (visualStatus.dataType == DataBuffer.TYPE_INT)
1363
                                dataType = "Integer";
1364
                        else if (visualStatus.dataType == DataBuffer.TYPE_FLOAT)
1365
                                dataType = "Float";
1366
                        else if (visualStatus.dataType == DataBuffer.TYPE_DOUBLE)
1367
                                dataType = "Double";
1368
                        else
1369
                                dataType = "Unknown";
1370

    
1371
                        Object [][] a = {
1372
                                {"Filename",rasterFile.getName().substring(rasterFile.getName().lastIndexOf("/")+1, rasterFile.getName().length())},
1373
                                {"Filesize",new Long(0)},
1374
                                {"Width",new Integer((int)this.getWidth())},
1375
                                {"Height", new Integer((int)this.getHeight())},
1376
                                {"Bands", new Integer(visualStatus.bandCount)},
1377
                                {"BandDataType", dataType}
1378
                        };
1379
                        for (int i=0; i<a.length; i++)
1380
                                attr.add(a[i]);
1381

    
1382
                        return attr;
1383
                }
1384
                return  null;
1385
        }
1386

    
1387
        /* (non-Javadoc)
1388
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getFilterStack()
1389
         */
1390
        public RasterFilterStack getFilterStack() {
1391
                if(raster!=null)
1392
                        return raster.filterStack;
1393
                return null;
1394
        }
1395
        /* (non-Javadoc)
1396
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getHeight()
1397
         */
1398
        public double getHeight() {
1399
                return visualStatus.height;
1400
        }
1401

    
1402
        /* (non-Javadoc)
1403
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxX()
1404
         */
1405
        public double getMaxX() {
1406
                return visualStatus.maxX;
1407
        }
1408

    
1409
        /* (non-Javadoc)
1410
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxY()
1411
         */
1412
        public double getMaxY() {
1413
                return visualStatus.maxY;
1414
        }
1415

    
1416
        /* (non-Javadoc)
1417
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinX()
1418
         */
1419
        public double getMinX() {
1420
                return visualStatus.minX;
1421
        }
1422

    
1423
        /* (non-Javadoc)
1424
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinY()
1425
         */
1426
        public double getMinY() {
1427
                return visualStatus.minY;
1428
        }
1429
        /* (non-Javadoc)
1430
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getPixel(double, double)
1431
         */
1432
        public int[] getPixel(double wcx, double wcy) {
1433
                if(getPxRaster() != null)
1434
                        return getPxRaster().getPixel(wcx, wcy);
1435
        return null;
1436
        }
1437
        /* (non-Javadoc)
1438
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getSource()
1439
         */
1440
        public RasterAdapter getSource() {
1441
                return null;
1442
        }
1443
        /* (non-Javadoc)
1444
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getWidth()
1445
         */
1446
        public double getWidth() {
1447
                return visualStatus.width;
1448
        }
1449
        /* (non-Javadoc)
1450
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setBand(int, int)
1451
         */
1452
        public void setBand(int flag, int nBand) {
1453
                switch(flag){
1454
                case GeoRasterFile.RED_BAND:setBandR(nBand);break;
1455
                case GeoRasterFile.GREEN_BAND:setBandG(nBand);break;
1456
                case GeoRasterFile.BLUE_BAND:setBandB(nBand);break;
1457
                }
1458
        }
1459
        /* (non-Javadoc)
1460
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setFilterStack(org.cresques.io.raster.RasterFilterStack)
1461
         */
1462
        public void setFilterStack(RasterFilterStack stack) {
1463
                this.filterStack = stack;
1464
        }
1465
        /* (non-Javadoc)
1466
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPos(int, int)
1467
         */
1468
        public void setPos(int x, int y) {
1469
                this.posX = x;
1470
                this.posY = y;
1471
        }
1472

    
1473
        /* (non-Javadoc)
1474
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPosWC(double, double)
1475
         */
1476
        public void setPosWC(double x, double y) {
1477
                this.posXWC = x;
1478
                this.posYWC = y;
1479
        }
1480

    
1481
        /* (non-Javadoc)
1482
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setRGB(int, int, int)
1483
         */
1484
        public void setRGB(int r, int g, int b) {
1485
                this.r = r;
1486
                this.g = g;
1487
                this.b = b;
1488
        }
1489
        /* (non-Javadoc)
1490
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setSource(com.iver.cit.gvsig.fmap.layers.RasterAdapter)
1491
         */
1492
        public void setSource(RasterAdapter ra) {
1493
        }
1494
        /**
1495
         * @return Returns the raster.
1496
         */
1497
        public PxRaster getPxRaster() {
1498
                return raster;
1499
        }
1500
        /**
1501
         * @return Returns the rasterFile.
1502
         */
1503
        public GeoRasterFile getGeoRasterFile() {
1504
                return rasterFile;
1505
        }
1506

    
1507
        public void setTransparency(int trans) {
1508
                this.transparency = trans;
1509
        }
1510

    
1511
        /**
1512
         * Sets the R-band.
1513
         *
1514
         * Asigna la banda R.
1515
         * @param r
1516
         */
1517
        public void setBandR(int r){
1518
                this.rband = r;
1519
        }
1520

    
1521
        /**
1522
         * Sets the G-band.
1523
         *
1524
         * Asigna la banda G
1525
         * @param g
1526
         */
1527
        public void setBandG(int g){
1528
                this.gband = g;
1529
        }
1530

    
1531
        /**
1532
         * Sets the B-band.
1533
         *
1534
         * Asigna la banda B
1535
         * @param b
1536
         */
1537
        public void setBandB(int b){
1538
                this.bband = b;
1539
        }
1540

    
1541
    /**
1542
     * @return Returns the wmsTransparency.
1543
     */
1544
    public boolean isWmsTransparent() {
1545
        return wmsTransparency;
1546
    }
1547

    
1548
    /**
1549
     * @param wmsTransparency The wmsTransparency to set.
1550
     */
1551
    public void setWmsTransparency(boolean wmsTransparency) {
1552
        this.wmsTransparency = wmsTransparency;
1553
    }
1554

    
1555
     /**
1556
     * @param styles
1557
     */
1558
    public void setStyles(Vector styles) {
1559
            //laura:
1560
            //layer query is built with the layer in reverse order
1561
            // so here we build the styles upside-down.
1562
            if (styles != null)
1563
            {
1564
                    this.styles = new Vector();
1565
                    for(int i = styles.size()-1; i>=0; i--)
1566
                    {
1567
                            this.styles.add(styles.elementAt(i));
1568
                    }
1569
            }
1570
    }
1571

    
1572
    /**
1573
     * Sets the dimension vector that is a list of key-value pairs containing
1574
     * the name of the dimension and the value for it
1575
     * @param dimensions
1576
     */
1577
    public void setDimensions(Vector dimensions) {
1578
        this.dimensions = dimensions;
1579
    }
1580

    
1581
    /**
1582
     * Sets the set of URLs that should be accessed for each operation performed
1583
     * to the server.
1584
     *
1585
     * @param onlineResources
1586
     */
1587
        public void setOnlineResources(Hashtable onlineResources) {
1588
                this.onlineResources = onlineResources;
1589
        }
1590

    
1591
    /**
1592
     * Gets the URL that should be accessed for an operation performed
1593
     * to the server.
1594
     *
1595
     * @param onlineResources
1596
     */
1597
        public String getOnlineResource(String operation) {
1598
                return ((String) onlineResources.get(operation));
1599
        }
1600

    
1601
        /**
1602
         * When a server is not fully featured and it only can serve constant map
1603
         * sizes this value must be set. It expresses the size in pixels (width, height)
1604
         * that the map will be requested.
1605
         * @param Dimension sz
1606
         */
1607
        public void setFixedSize(Dimension sz) {
1608
                fixedSize = sz;
1609
        }
1610

    
1611
        /**
1612
         * Tells whether if this layer must deal with the server with the constant-size
1613
         * limitations or not.
1614
         * @return boolean.
1615
         */
1616
        private boolean isSizeFixed() {
1617
                return fixedSize != null && fixedSize.getWidth() > 0 && fixedSize.getHeight() > 0;
1618
        }
1619

    
1620
        /**
1621
         * If it is true, this layer accepts GetFeatureInfo operations. This WMS operations
1622
         * maps to FMap's infoByPoint(p) operation.
1623
         * @param b
1624
         */
1625
        public void setQueryable(boolean b) {
1626
                queryable = b;
1627
        }
1628

    
1629
        /**
1630
         * Creates the part of a OGC's MapContext document that would describe this
1631
         * layer(s).
1632
         * @param version, The desired version of the resulting document. (1.1.0)
1633
         * @return String containing the xml.
1634
         * @throws UnsupportedVersionException
1635
         */
1636
        public String toMapContext(String mapContextVersion) {
1637
                XmlBuilder xml = new XmlBuilder();
1638
                FMapWMSDriver drv;
1639
                try {
1640
                        drv = getDriver();
1641
                } catch (Exception e) {
1642
                        return xml.toString();
1643
                }
1644
                String[] layerNames = getLayerQuery().split(",");
1645
                String[] styleNames = (String[]) styles.toArray(new String[0]);
1646
                for (int i = 0; i < layerNames.length; i++) {
1647
                        WMSLayerNode layer = drv.getLayer(layerNames[i]);
1648
                        HashMap xmlAttrs = new HashMap();
1649

    
1650
                        // <Layer>
1651
                        xmlAttrs.put(WebMapContextTags.HIDDEN, !isVisible()+"");
1652
                        xmlAttrs.put(WebMapContextTags.QUERYABLE, queryable+"");
1653
                        xml.openTag(WebMapContextTags.LAYER, xmlAttrs);
1654
                        xmlAttrs.clear();
1655
                        if (mapContextVersion.equals("1.1.0") || mapContextVersion.equals("1.0.0")) {
1656
                                // <Server>
1657
                                xmlAttrs.put(WebMapContextTags.SERVICE, WebMapContextTags.WMS);
1658
                                xmlAttrs.put(WebMapContextTags.VERSION, drv.getVersion());
1659
                                xmlAttrs.put(WebMapContextTags.SERVER_TITLE, drv.getServiceTitle());
1660
                                xml.openTag(WebMapContextTags.SERVER, xmlAttrs);
1661
                                xmlAttrs.clear();
1662

    
1663
                                        // <OnlineResource>
1664
                                        xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1665
                                        xmlAttrs.put(WebMapContextTags.XLINK_HREF, getHost().toString());
1666
                                        xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1667
                                        xmlAttrs.clear();
1668
                                        // </OnlineResource>
1669

    
1670
                                xml.closeTag();
1671
                                // </Server>
1672

    
1673
                                // <Name>
1674
                                xml.writeTag(WebMapContextTags.NAME, layer.getName().trim());
1675
                                // </Name>
1676

    
1677
                                // <Title>
1678
                                xml.writeTag(WebMapContextTags.TITLE, layer.getTitle().trim());
1679
                                //?xml.writeTag(WebMapContextTags.TITLE, getName().trim());
1680
                                // </Title>
1681

    
1682
                                // <Abstract>
1683
                                if (layer.getAbstract() != null)
1684
                                        xml.writeTag(WebMapContextTags.ABSTRACT, layer.getAbstract());
1685
                                // </Abstract>
1686

    
1687
                                // <SRS> (a list of available SRS for the enclosing layer)
1688
                                String[] strings = (String[]) layer.getAllSrs().toArray(new String[0]);
1689
                                String mySRS = strings[0];
1690
                                for (int j = 1; j < strings.length; j++) {
1691
                                        mySRS += ","+strings[j];
1692
                                }
1693
                                xml.writeTag(WebMapContextTags.SRS, mySRS);
1694
                                // </SRS>
1695

    
1696
                                // <FormatList>
1697
                                xml.openTag(WebMapContextTags.FORMAT_LIST);
1698
                                        strings = (String[]) drv.getFormats().toArray(new String[0]);
1699
                                        for (int j = 0; j < strings.length; j++) {
1700
                    // <Format>
1701
                                                String str = strings[j].trim();
1702
                                                if (str.equals(getFormat()))
1703
                                                        xml.writeTag(WebMapContextTags.FORMAT, str, WebMapContextTags.CURRENT, "1");
1704
                                                else
1705
                                                        xml.writeTag(WebMapContextTags.FORMAT, str);
1706
                    // </Format>
1707
                                        }
1708
                                xml.closeTag();
1709
                                // </FormatList>
1710

    
1711
                                // <StyleList>
1712
                                xml.openTag(WebMapContextTags.STYLE_LIST);
1713

    
1714
                                        if (layer.getStyles().size()>0) {
1715
                                                for (int j = 0; j < layer.getStyles().size(); j++) {
1716
                                                        // <Style>
1717
                                                        FMapWMSStyle st = (FMapWMSStyle) layer.getStyles().get(j);
1718
                                                        if (st.name.equals(styleNames[i]))
1719
                                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1720
                                                        xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1721
                                                        xmlAttrs.clear();
1722

    
1723
                                                                // <Name>
1724
                                                                xml.writeTag(WebMapContextTags.NAME, st.name);
1725
                                                                // </Name>
1726

    
1727
                                                                // <Title>
1728
                                                                xml.writeTag(WebMapContextTags.TITLE, st.title);
1729
                                                                // </Title>
1730

    
1731
                                                                // <LegendURL width="180" format="image/gif" height="50">
1732
                                                                        // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1733
                                                                        // </OnlineResource>
1734
                                                                // </LegendURL>
1735
                                                        xml.closeTag();
1736
                                                        // </Style>
1737

    
1738
                                                }
1739

    
1740
                                        } else {
1741
                                                // Create fake style (for compatibility issues)
1742
                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1743
                                                // <Style>
1744
                                                xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1745
                                                        xmlAttrs.clear();
1746
                                                        // <Name>
1747
                                                        xml.writeTag(WebMapContextTags.NAME, "default");
1748
                                                        // </Name>
1749

    
1750
                                                        // <Title>
1751
                                                        xml.writeTag(WebMapContextTags.TITLE, "default");
1752
                                                        // </Title>
1753

    
1754
//                                                        // <LegendURL width="180" format="image/gif" height="50">
1755
//                                                        xmlAttrs.put(WebMapContextTags.WIDTH, "0");
1756
//                                                        xmlAttrs.put(WebMapContextTags.HEIGHT, "0");
1757
//                                                        xmlAttrs.put(WebMapContextTags.FORMAT.toLowerCase(), "image/gif");
1758
//                                                        xml.openTag(WebMapContextTags.LEGEND_URL, xmlAttrs);
1759
//                                                        xmlAttrs.clear();
1760
//                                                                // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1761
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1762
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_HREF, "http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif");
1763
//                                                                xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1764
//                                                                // </OnlineResource>
1765
//                                                    // </LegendURL>
1766
//                                                        xml.closeTag();
1767
                                                // </Style>
1768
                                                xml.closeTag();
1769
                                        }
1770
                                // </StyleList>
1771
                                xml.closeTag();
1772
                                if (mapContextVersion.compareTo("1.0.0") > 0) {
1773
                                // <DimensionList>
1774
                                        xml.openTag(WebMapContextTags.DIMENSION_LIST);
1775
                                        // <Dimension>
1776
                                        // </Dimension>
1777
                                        xml.closeTag();
1778
                                // </DimensionList>
1779
                                }
1780
                        } else {
1781
                                xml.writeTag("ERROR", PluginServices.getText(this, "unsupported_map_context_version"));
1782
                        }
1783
                        // </Layer>
1784
                        xml.closeTag();
1785
                }
1786
                return xml.getXML();
1787
        }
1788

    
1789
        public ImageIcon getTocImageIcon() {
1790
                return new ImageIcon(PluginServices.getPluginServices("com.iver.cit.gvsig.wms").getClassLoader().getResource("images/icoLayer.png"));
1791
        }
1792

    
1793
        /*
1794
         *  (non-Javadoc)
1795
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1796
         */
1797
        public int[] getTileSize() {
1798
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1799
                return size;
1800
        }
1801
        /*
1802
         *  (non-Javadoc)
1803
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1804
         */
1805
        public boolean isTiled() {
1806
                return mustTileDraw;
1807
        }
1808

    
1809
        public Image getImageLegend() {
1810
                try {
1811
                        if (wms == null)
1812
                                wms = getDriver();
1813
                        if (wms.hasLegendGraphic()) {
1814
                                wmsStatus.setOnlineResource((String) onlineResources
1815
                                                .get("GetLegendGraphic"));
1816
                                String path = getPathImage();// File legend =
1817
                                                                                                // getDriver().getLegendGraphic(wmsStatus,
1818
                                                                                                // layerQuery, null);
1819
                                Image img = null;
1820
                                if ((path != null) && (path.length() > 0))
1821
                                        img = new ImageIcon(path).getImage();
1822
                                return img;
1823
                        }
1824
                } catch (Exception e) {
1825
                }
1826
                return null;
1827
        }
1828

    
1829
        public String getPathImage() {
1830
                try {
1831
                        File legend = getDriver().getLegendGraphic(wmsStatus, layerQuery, null);
1832
                        return legend.getAbsolutePath();
1833
                }catch(Exception e){
1834
                        //e.printStackTrace();
1835
                        return null;
1836
                }
1837
        }
1838

    
1839
        /**
1840
         * Obtiene el grid asociado al raster que hay cargado en ese momento
1841
         * @return grid
1842
         */
1843
        public Grid getGrid(){
1844
                return grid;
1845
        }
1846

    
1847
        /**
1848
         * Obtiene el tipo de dato de la capa raster
1849
         * @return Entero que representa el tipo de dato de la capa raster.
1850
         */
1851
        public int getDataType() {
1852
                return rasterFile.getDataType();
1853
        }
1854
        public boolean isQueryable(){
1855
                return queryable;
1856
        }
1857
}