Statistics
| Revision:

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

History | View | Annotate | Download (58.9 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
import java.util.prefs.Preferences;
68

    
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.ComposedLayer;
102
import com.iver.cit.gvsig.fmap.layers.layerOperations.IHasImageLegend;
103
import com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint;
104
import com.iver.cit.gvsig.fmap.layers.layerOperations.StringXMLItem;
105
import com.iver.cit.gvsig.fmap.layers.layerOperations.XMLItem;
106
import com.iver.cit.gvsig.fmap.rendering.XmlBuilder;
107
import com.iver.cit.gvsig.wmc.WebMapContextTags;
108
import com.iver.utiles.StringUtilities;
109
import com.iver.utiles.XMLEntity;
110
import com.iver.utiles.swing.threads.Cancellable;
111

    
112

    
113

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

    
132
    public URL                                                         host;
133
    public String                                                 m_Format;
134

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

    
161

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

    
178
        public FLyrWMS(){
179
                super();
180
        }
181

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

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

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

    
209
                        if (wmsNode == null){
210
                                throw new DriverIOException("The server '" + host + "' doesn't has the layer '" + sLayer + "'.");
211
                        }
212
                        if( sFormat == null ) {
213
                                sFormat = this.getGreatFormat(drv.getFormats());
214
                        }
215

    
216
                        //SRS
217
                        Vector allSrs = wmsNode.getAllSrs();
218
                        boolean isSRSSupported = false;
219
                        if( sSRS != null ) {
220
                                for (int i=0; i<allSrs.size() ; i++){
221
                                     if (((String)allSrs.get(i)).compareTo(sSRS) == 0){
222
                                             isSRSSupported = true;
223
                                     }
224
                             }
225
                        }
226

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

    
242

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

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

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

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

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

    
304

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

    
315
                // Full extent
316
                xml.putProperty("fullExtent", StringUtilities.rect2String(fullExtent));
317

    
318
                // Host
319
                xml.putProperty("host", host.toExternalForm());
320

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

    
325
                // Part of the query containing the layer names
326
                xml.putProperty("layerQuery", layerQuery);
327

    
328
                // Format
329
                xml.putProperty("format", m_Format);
330

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

    
340
        // Transparency
341
        xml.putProperty("wms_transparency", wmsTransparency);
342

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

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

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

    
381
        // Queryable
382
        xml.putProperty("queryable", queryable);
383

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

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

    
408
                try {
409
                        host = new URL(xml.getStringProperty("host"));
410
                } catch (MalformedURLException e) {
411
                        throw new XMLException(e);
412
                }
413

    
414
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
415
                layerQuery = xml.getStringProperty("layerQuery");
416
                m_Format = xml.getStringProperty("format");
417
                m_SRS = xml.getStringProperty("srs");
418
        }
419

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

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

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

    
446
                // Part of the query containing the layer names
447
                layerQuery = xml.getStringProperty("layerQuery");
448

    
449
                // Format
450
                m_Format = xml.getStringProperty("format");
451

    
452
                // SRS
453
                m_SRS = xml.getStringProperty("srs");
454

    
455
                String claseStr = StatusLayerRaster.defaultClass;
456
                if (xml.contains("raster.class")) {
457
                        claseStr = xml.getStringProperty("raster.class");
458
                }
459

    
460
                // Transparency
461
        if (xml.contains("wms_transparency"))
462
            wmsTransparency = xml.getBooleanProperty("wms_transparency");
463

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

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

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

    
484
                dimensions.add(dims[i]);
485
            }
486
        }
487

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

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

    
503
        // fixedSize
504
        if (xml.contains("fixedSize")) {
505
                fixedSize = new Dimension(xml.getIntProperty("fixedWidth"),
506
                                                  xml.getIntProperty("fixedHeight"));
507
        }
508

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

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

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

    
553
                                int col = (int) p.getX() / maxTilePrintWidth;
554
                                int row = (int) p.getY() / maxTilePrintHeight;
555
                                int tileIndex = (row*nCols) + col;
556

    
557
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileIndex);
558
                                wmsStatus.setExtent(vp.getAdjustedExtent());
559
                                wmsStatus.setHeight(vp.getImageHeight());
560
                                wmsStatus.setWidth(vp.getImageWidth());
561
                                wmsStatus.setOnlineResource((String) onlineResources.get("GetFeatureInfo"));
562

    
563
                                //This is in the case we call layer.getInfo outside the info tool.
564
                                if (wmsStatus.getSrs() == null){
565
                                        wmsStatus.setSrs(this.m_SRS);
566
                                }
567
                                if(wmsStatus.getFormat() == null){
568
                                        wmsStatus.setFormat(this.m_Format);
569
                                }
570
                                if(wmsStatus.getLayerNames().isEmpty()){
571
                                        wmsStatus.addLayerName(this.getLayerQuery());
572
                                }
573

    
574
                                MyCancellable c = new MyCancellable(cancellable);
575
                                item[0] = new StringXMLItem(new String(getDriver()
576
                                                .getFeatureInfo(wmsStatus, (int) tiledPoint.getX(), (int) tiledPoint.getY(), Integer.MAX_VALUE, c)),this);
577
                                return item;
578
                        }
579
                        else
580
                        {
581
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),this.getName() + " " +
582
                                                PluginServices.getText(this,"layer_not_queryable"));
583
                                item[0] =  new StringXMLItem("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><info></info>",this);
584
                                return item;
585
                                //return null;
586
                        }
587
                } catch (WMSException  e) {
588
                        item[0] = new StringXMLItem("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><exception>" +
589
                        e.getMessage() + "</exception>", this);
590
                        return item;
591
                }
592
                /*azabala
593
                catch (ValidationException e) {
594
                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
595
                } catch (UnsupportedVersionException e) {
596
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
597
                } catch (IOException e) {
598
                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
599
                }
600
                */
601
                catch (ValidationException e) {
602
                        UnknownResponseFormatExceptionType type =
603
                                new UnknownResponseFormatExceptionType();
604
                        type.setLayerName(getName());
605
                        try {
606
                                type.setDriverName("WMS Driver");
607
                        } catch (Exception e1) {
608
                                e1.printStackTrace();
609
                        }
610
                        type.setFormat(m_Format);
611
                        type.setHost(host);
612
                        type.setProtocol("WMS");
613
                        DriverException exception = new DriverException("unknown_response_format", type);
614
                        throw exception;
615

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

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

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

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

    
673

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

    
680
                        } else {
681
                                if(mustTileDraw){
682
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), viewPort.getImageWidth(), viewPort.getImageHeight());
683
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
684
                                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
685
                                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
686
                                                // drawing part
687
                                                try {
688
                                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
689
                                                        drawTile(g, vp, cancel);
690
                                                } catch (NoninvertibleTransformException e) {
691
                                                        e.printStackTrace();
692
                                                }
693
                                        }
694
                                }else
695
                                        drawTile(g, viewPort, cancel);
696
                        }
697
                }
698
        }
699

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

    
705

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

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

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

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

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

    
741
                        rasterProcess(g, vpData, f);
742

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

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

    
796

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

    
818

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

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

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

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

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

    
871
        Dimension sz = new Dimension(wImg, hImg);
872

    
873
        if ((wImg <= 0) || (hImg <= 0)) {
874
            return;
875
        }
876
        MyCancellable c = new MyCancellable(cancel);
877

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

    
884

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

    
896
                        // begin patch; Avoid to request too small tiles.
897
                        // This generally occurs when printing
898

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

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

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

    
928
                        ViewPortData vpData = new ViewPortData(
929
                                vp.getProjection(), new Extent(bBox), sz );
930
                        vpData.setMat(vp.getAffineTransform());
931

    
932
                        rasterProcess(g, vpData, f);
933

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

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

    
957
//                        if (!c.isCanceled())
958
//                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
959

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

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

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

    
1042

    
1043
                                } //if
1044
                        }//if
1045
                }//catch
1046
                callCount--;
1047
        }
1048

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

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

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

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

    
1099
                if(status != null && firstLoad){
1100
                        status.applyStatus(this);
1101
                        firstLoad = false;
1102
                }
1103

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

    
1108
                raster.setTransparency(false);
1109

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

    
1115
                raster.setBand(GeoRasterFile.RED_BAND,rband);
1116
                raster.setBand(GeoRasterFile.GREEN_BAND, gband);
1117
                raster.setBand(GeoRasterFile.BLUE_BAND, bband);
1118

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

    
1125
                if(visualStatus != null){
1126
                        visualStatus.bandCount = raster.getBandCount();
1127
                        visualStatus.dataType = raster.getDataType();
1128
                }
1129

    
1130
                raster.draw(g, vpData);
1131

    
1132
                //En el primer pxRaster de una imagen obtenemos el Stack Manager para poder modificarlo
1133
                //si queremos desde las propiedades
1134

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

    
1138
                if(this.filterStack == null)
1139
                        this.filterStack = raster.filterStack;
1140

    
1141
                //rasterFile.close();
1142
        }
1143

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

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

    
1177
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale)
1178
                throws DriverException {
1179
                draw(null, g, viewPort, cancel,scale);
1180
        }
1181

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

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

    
1212
        /**
1213
         * Devuelve el URL.
1214
         *
1215
         * @return URL.
1216
         */
1217
        public URL getHost() {
1218
                return host;
1219
        }
1220

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

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

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

    
1248
        /**
1249
         * Devuelve la consulta.
1250
         *
1251
         * @return String.
1252
         */
1253
        public String getLayerQuery() {
1254
                return layerQuery;
1255
        }
1256

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

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

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

    
1284
        /**
1285
         * Devuelve el SRS.
1286
         *
1287
         * @return SRS.
1288
         */
1289
        public String getSRS() {
1290
                return m_SRS;
1291
        }
1292

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

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

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

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

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

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

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

    
1385
                        return attr;
1386
                }
1387
                return  null;
1388
        }
1389

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

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

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

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

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

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

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

    
1510
        public void setTransparency(int trans) {
1511
                this.transparency = trans;
1512
        }
1513

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

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

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

    
1544
    /**
1545
     * @return Returns the wmsTransparency.
1546
     */
1547
    public boolean isWmsTransparent() {
1548
        return wmsTransparency;
1549
    }
1550

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

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

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

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

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

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

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

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

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

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

    
1667
                                        // <OnlineResource>
1668
                                        xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1669
                                        xmlAttrs.put(WebMapContextTags.XLINK_HREF, getHost().toString());
1670
                                        xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1671
                                        xmlAttrs.clear();
1672
                                        // </OnlineResource>
1673

    
1674
                                xml.closeTag();
1675
                                // </Server>
1676

    
1677
                                // <Name>
1678
                                xml.writeTag(WebMapContextTags.NAME, layer.getName().trim());
1679
                                // </Name>
1680

    
1681
                                // <Title>
1682
                                xml.writeTag(WebMapContextTags.TITLE, layer.getTitle().trim());
1683
                                //?xml.writeTag(WebMapContextTags.TITLE, getName().trim());
1684
                                // </Title>
1685

    
1686
                                // <Abstract>
1687
                                if (layer.getAbstract() != null)
1688
                                        xml.writeTag(WebMapContextTags.ABSTRACT, layer.getAbstract());
1689
                                // </Abstract>
1690

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

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

    
1715
                                // <StyleList>
1716
                                xml.openTag(WebMapContextTags.STYLE_LIST);
1717

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

    
1727
                                                                // <Name>
1728
                                                                xml.writeTag(WebMapContextTags.NAME, st.name);
1729
                                                                // </Name>
1730

    
1731
                                                                // <Title>
1732
                                                                xml.writeTag(WebMapContextTags.TITLE, st.title);
1733
                                                                // </Title>
1734

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

    
1742
                                                }
1743

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

    
1754
                                                        // <Title>
1755
                                                        xml.writeTag(WebMapContextTags.TITLE, "default");
1756
                                                        // </Title>
1757

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

    
1793
        public ImageIcon getTocImageIcon() {
1794
                return new ImageIcon(PluginServices.getPluginServices("com.iver.cit.gvsig.wms").getClassLoader().getResource("images/icoLayer.png"));
1795
        }
1796

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

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

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

    
1843
        /**
1844
         * Obtiene el grid asociado al raster que hay cargado en ese momento
1845
         * @return grid
1846
         */
1847
        public Grid getGrid(){
1848
                return grid;
1849
        }
1850

    
1851
        /**
1852
         * Obtiene el tipo de dato de la capa raster
1853
         * @return Entero que representa el tipo de dato de la capa raster.
1854
         */
1855
        public int getDataType() {
1856
                return rasterFile.getDataType();
1857
        }
1858
        public boolean isQueryable(){
1859
                return queryable;
1860
        }
1861
        public ComposedLayer newComposedLayer() {
1862
                Preferences prefs = Preferences.userRoot().node("gvsig.wms");
1863
                 
1864
                String str = prefs.get("useComposedLayer","false");
1865
                Boolean useComposedLayer = Boolean.FALSE;
1866
                try {
1867
                        useComposedLayer = Boolean.valueOf(str);
1868
                } catch (Exception e) {
1869
                        
1870
                }
1871
                if (useComposedLayer.booleanValue()) {
1872
                        return new ComposedLayerWMS();
1873
                } else {
1874
                        return null;
1875
                }
1876
        }
1877
        
1878
    /**
1879
     * @param styles
1880
     */
1881
    public Vector getStyles() {
1882
            return this.styles;
1883
    }
1884
        
1885
        
1886
        /* Checks if can make a single petition for
1887
         * the two layers to the server
1888
         *   
1889
         * @see com.iver.cit.gvsig.fmap.layers.ComposedLayerWMS#canAdd(com.iver.cit.gvsig.fmap.layers.FLayer)
1890
         */
1891
    boolean isComposedLayerCompatible(FLayer layer) {
1892
                FLyrWMS aLayer;
1893
                
1894
                if (!(layer instanceof FLyrWMS)) {
1895
                        return false;
1896
                }
1897
                aLayer = (FLyrWMS)layer;
1898
                if (!this.getHost().equals(aLayer.getHost())) {
1899
                        return false;
1900
                }
1901
                if (!this.getFormat().equals(aLayer.getFormat())) {
1902
                        return false;
1903
                }
1904
                if (!this.getSRS().equals(aLayer.getSRS())) {
1905
                        return false;
1906
                }
1907
                if (this.getInfoLayerQuery() != null) {
1908
                        if (!this.getInfoLayerQuery().equals(aLayer.getInfoLayerQuery())) {
1909
                                return false;
1910
                        }
1911
                }else if (aLayer.getInfoLayerQuery() != null) {
1912
                        return false;
1913
                }
1914
                
1915
                
1916
                // isFixedSize es privado                
1917
                if ((this.fixedSize != null) && 
1918
                                (aLayer.fixedSize!= null)) {
1919
                        if (this.fixedSize.equals(aLayer.fixedSize)) {
1920
                                return false;
1921
                        }
1922
                } else if ((this.fixedSize != null) != (aLayer.fixedSize != null)) {
1923
                        return false;
1924
                }
1925
                
1926
                // time elevation (dimensions)
1927
                if ((this.dimensions != null) && 
1928
                                (aLayer.dimensions != null)) {
1929
                        if (this.dimensions.size() != aLayer.dimensions.size()) {
1930
                                return false;
1931
                        } else {
1932
                                Iterator iter = this.dimensions.iterator();
1933
                                while (iter.hasNext()) {
1934
                                        if (!aLayer.dimensions.contains(iter.next())) {
1935
                                                return false;
1936
                                        }
1937
                                }
1938
                        }
1939

    
1940
                } else if ((this.dimensions != null) != (aLayer.dimensions != null)) {
1941
                        return false;
1942
                }
1943
                
1944
                
1945
                return true;
1946

    
1947
        }
1948
    
1949
}