Statistics
| Revision:

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

History | View | Annotate | Download (55.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

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

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

    
84
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
85
import com.hardcode.gdbms.engine.data.driver.DriverException;
86
import com.iver.andami.PluginServices;
87
import com.iver.andami.messages.NotificationManager;
88
import com.iver.cit.gvsig.exceptions.layers.ConnectionErrorLayerException;
89
import com.iver.cit.gvsig.exceptions.layers.LoadLayerException;
90
import com.iver.cit.gvsig.exceptions.layers.URLLayerException;
91
import com.iver.cit.gvsig.exceptions.layers.UnsupportedVersionLayerException;
92
import com.iver.cit.gvsig.exceptions.visitors.VisitorException;
93
import com.iver.cit.gvsig.fmap.ConnectionErrorExceptionType;
94
import com.iver.cit.gvsig.fmap.ViewPort;
95
import com.iver.cit.gvsig.fmap.WMSDriverExceptionType;
96
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
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

    
160

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

    
173
        }
174

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

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

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

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

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

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

    
241

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

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

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

    
274
        /**
275
         * Clase que contiene los datos de visualizaci?n de WMS.
276
         * @author Nacho Brodin (brodin_ign@gva.es)
277
         */
278
        private class VisualStatusWMS{
279
                /**
280
                 * Ancho y alto de la imagen o del conjunto de tiles si los tiene. Coincide con
281
                 * el ancho y alto del viewPort
282
                 */
283
                private        int                                                        width = 0, height = 0;
284
                private double                                                minX = 0D, minY = 0D, maxX = 0D, maxY = 0D;
285
                private int                                                 bandCount = 0;
286
                private int                                                        dataType = DataBuffer.TYPE_UNDEFINED;
287
        }
288

    
289

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
656

    
657
                        if (isSizeFixed()) {
658
                                // This condition handles those situations in which the server can
659
                                // only give static extent and resolution maps despite we need
660
                                // a specific BBOX and pixel WIDTH and HEIGHT
661
                                try {
662
                                        drawFixedSize(g, viewPort, cancel);
663
                                } catch (LoadLayerException e) {
664
                                        // TODO Auto-generated catch block
665
                                        e.printStackTrace();
666
                                }
667

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

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

    
704

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

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

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

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

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

    
740
                        rasterProcess(g, vpData, f);
741

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

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

    
794

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

    
816

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

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

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

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

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

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

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

    
863

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

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

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

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

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

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

    
911
                        rasterProcess(g, vpData, f);
912

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

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

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

    
1020

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

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

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

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

    
1067
                //Creamos el PxRaster
1068
                rasterFile = new GdalFile(vpData.getProjection(), file.getAbsolutePath());
1069
                raster = new PxRaster(rasterFile, null, rasterFile.getExtent());
1070

    
1071
                if(status!=null && firstLoad){
1072
                        status.applyStatus(this);
1073
                        firstLoad = false;
1074
                }
1075

    
1076
                //Recuperamos la pila de filtros si ya hubiese sido cargado antes
1077
                if(this.filterStack!=null)
1078
                        raster.filterStack = this.filterStack;
1079

    
1080
                raster.setTransparency(false);
1081

    
1082
                //Asignamos transparencia y orden de bandas
1083
                if(this.transparency==-1 && !firstLoad);
1084
                else
1085
                        raster.setTransparency(this.transparency);
1086

    
1087
                raster.setBand(GeoRasterFile.RED_BAND,rband);
1088
                raster.setBand(GeoRasterFile.GREEN_BAND, gband);
1089
                raster.setBand(GeoRasterFile.BLUE_BAND, bband);
1090

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

    
1097
                if(visualStatus != null){
1098
                        visualStatus.bandCount = raster.getBandCount();
1099
                        visualStatus.dataType = raster.getDataType();
1100
                }
1101

    
1102
                raster.draw(g, vpData);
1103

    
1104
                //En el primer pxRaster de una imagen obtenemos el Stack Manager para poder modificarlo
1105
                //si queremos desde las propiedades
1106

    
1107
                if(this.stackManager == null)
1108
                        this.stackManager = raster.getStackManager();
1109

    
1110
                if(this.filterStack == null)
1111
                        this.filterStack = raster.filterStack;
1112

    
1113
                //rasterFile.close();
1114
        }
1115

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

    
1133
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
1134
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
1135
                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
1136
                            // Parte que dibuja
1137
                            try {
1138
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
1139
                                drawTile(g, vp, cancel);
1140
                                } catch (NoninvertibleTransformException e) {
1141
                                        e.printStackTrace();
1142
                                } catch (LoadLayerException e) {
1143
                                        // TODO Auto-generated catch block
1144
                                        e.printStackTrace();
1145
                                }
1146
                }
1147
                }
1148
            isPrinting = false;
1149
                }
1150
        }
1151

    
1152
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale)
1153
                throws ReadDriverException {
1154
                draw(null, g, viewPort, cancel,scale);
1155
        }
1156

    
1157
        /**
1158
         * Devuelve el FMapWMSDriver.
1159
         *
1160
         * @return FMapWMSDriver
1161
         *
1162
         * @throws IllegalStateException
1163
         * @throws ValidationException
1164
         * @throws UnsupportedVersionLayerException
1165
         * @throws IOException
1166
         */
1167
        private FMapWMSDriver getDriver()
1168
                throws IllegalStateException, ValidationException,
1169
                        UnsupportedVersionLayerException, IOException {
1170
                return FMapWMSDriverFactory.getFMapDriverForURL(host);
1171
        }
1172

    
1173
        /**
1174
         * Devuelve el FMapWMSDriver.
1175
         *
1176
         * @return FMapWMSDriver
1177
         *
1178
         * @throws IllegalStateException
1179
         * @throws ValidationException
1180
         * @throws UnsupportedVersionLayerException
1181
         * @throws IOException
1182
         */
1183
        public void setDriver(FMapWMSDriver drv) {
1184
                wms = drv;
1185
        }
1186

    
1187
        /**
1188
         * Devuelve el URL.
1189
         *
1190
         * @return URL.
1191
         */
1192
        public URL getHost() {
1193
                return host;
1194
        }
1195

    
1196
        /**
1197
         * Inserta el URL.
1198
         *
1199
         * @param host URL.
1200
         */
1201
        public void setHost(URL host) {
1202
                this.host = host;
1203
        }
1204

    
1205
        /**
1206
         * Devuelve la informaci?n de la consulta.
1207
         *
1208
         * @return String.
1209
         */
1210
        public String getInfoLayerQuery() {
1211
                return infoLayerQuery;
1212
        }
1213

    
1214
        /**
1215
         * Inserta la informaci?n de la consulta.
1216
         *
1217
         * @param infoLayerQuery String.
1218
         */
1219
        public void setInfoLayerQuery(String infoLayerQuery) {
1220
                this.infoLayerQuery = infoLayerQuery;
1221
        }
1222

    
1223
        /**
1224
         * Devuelve la consulta.
1225
         *
1226
         * @return String.
1227
         */
1228
        public String getLayerQuery() {
1229
                return layerQuery;
1230
        }
1231

    
1232
        /**
1233
         * Inserta la consulta.
1234
         *
1235
         * @param layerQuery consulta.
1236
         */
1237
        public void setLayerQuery(String layerQuery) {
1238
                this.layerQuery = layerQuery;
1239
        }
1240

    
1241
        /**
1242
         * Devuelve el formato.
1243
         *
1244
         * @return Formato.
1245
         */
1246
        public String getFormat() {
1247
                return m_Format;
1248
        }
1249

    
1250
        /**
1251
         * Inserta el formato.
1252
         *
1253
         * @param format Formato.
1254
         */
1255
        public void setFormat(String format) {
1256
                m_Format = format;
1257
        }
1258

    
1259
        /**
1260
         * Devuelve el SRS.
1261
         *
1262
         * @return SRS.
1263
         */
1264
        public String getSRS() {
1265
                return m_SRS;
1266
        }
1267

    
1268
        /**
1269
         * Inserta el SRS.
1270
         *
1271
         * @param m_srs SRS.
1272
         */
1273
        public void setSRS(String m_srs) {
1274
                m_SRS = m_srs;
1275
        }
1276

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

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

    
1312
        /**
1313
         * Asignar el estado del raster
1314
         * @param status
1315
         */
1316
        public void setStatus(StatusRasterInterface status){
1317
                this.status = status;
1318
        }
1319

    
1320
        /**
1321
         * Obtiene el estado del raster
1322
         * @return
1323
         */
1324
        public StatusRasterInterface getStatus(){
1325
                return this.status;
1326
        }
1327

    
1328
        public ArrayList getAttributes() {
1329
                if(rasterFile != null){
1330
                        ArrayList attr = new ArrayList();
1331
                        String dataType = "Byte";
1332
                        if (rasterFile.getDataType() == DataBuffer.TYPE_BYTE) dataType = "Byte";
1333
                        else if (visualStatus.dataType == DataBuffer.TYPE_SHORT)
1334
                                dataType = "Short";
1335
                        else if (visualStatus.dataType == DataBuffer.TYPE_USHORT)
1336
                                dataType = "Unsigned Short";
1337
                        else if (visualStatus.dataType == DataBuffer.TYPE_INT)
1338
                                dataType = "Integer";
1339
                        else if (visualStatus.dataType == DataBuffer.TYPE_FLOAT)
1340
                                dataType = "Float";
1341
                        else if (visualStatus.dataType == DataBuffer.TYPE_DOUBLE)
1342
                                dataType = "Double";
1343
                        else
1344
                                dataType = "Unknown";
1345

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

    
1357
                        return attr;
1358
                }
1359
                return  null;
1360
        }
1361

    
1362
        public RasterFilterStack getFilterStack() {
1363
                if(raster!=null)
1364
                        return raster.filterStack;
1365
                return null;
1366
        }
1367

    
1368
        public double getHeight() {
1369
                return visualStatus.height;
1370
        }
1371

    
1372
        public double getMaxX() {
1373
                return visualStatus.maxX;
1374
        }
1375

    
1376
        public double getMaxY() {
1377
                return visualStatus.maxY;
1378
        }
1379

    
1380
        public double getMinX() {
1381
                return visualStatus.minX;
1382
        }
1383

    
1384
        public double getMinY() {
1385
                return visualStatus.minY;
1386
        }
1387

    
1388
        public int[] getPixel(double wcx, double wcy) {
1389
                if(getPxRaster() != null)
1390
                        return getPxRaster().getPixel(wcx, wcy);
1391
        return null;
1392
        }
1393

    
1394
        public RasterAdapter getSource() {
1395
                return null;
1396
        }
1397

    
1398
        public double getWidth() {
1399
                return visualStatus.width;
1400
        }
1401

    
1402
        public void setBand(int flag, int nBand) {
1403
                switch(flag){
1404
                case GeoRasterFile.RED_BAND:setBandR(nBand);break;
1405
                case GeoRasterFile.GREEN_BAND:setBandG(nBand);break;
1406
                case GeoRasterFile.BLUE_BAND:setBandB(nBand);break;
1407
                }
1408
        }
1409

    
1410
        public void setFilterStack(RasterFilterStack stack) {
1411
                this.filterStack = stack;
1412
        }
1413

    
1414
        public void setPos(int x, int y) {
1415
                this.posX = x;
1416
                this.posY = y;
1417
        }
1418

    
1419
        public void setPosWC(double x, double y) {
1420
                this.posXWC = x;
1421
                this.posYWC = y;
1422
        }
1423

    
1424
        public void setRGB(int r, int g, int b) {
1425
                this.r = r;
1426
                this.g = g;
1427
                this.b = b;
1428
        }
1429

    
1430
        /**
1431
         * @return Returns the raster.
1432
         */
1433
        public PxRaster getPxRaster() {
1434
                return raster;
1435
        }
1436
        /**
1437
         * @return Returns the rasterFile.
1438
         */
1439
        public GeoRasterFile getGeoRasterFile() {
1440
                return rasterFile;
1441
        }
1442

    
1443
        public void setTransparency(int trans) {
1444
                this.transparency = trans;
1445
        }
1446

    
1447
        /**
1448
         * Sets the R-band.
1449
         *
1450
         * Asigna la banda R.
1451
         * @param r
1452
         */
1453
        public void setBandR(int r){
1454
                this.rband = r;
1455
        }
1456

    
1457
        /**
1458
         * Sets the G-band.
1459
         *
1460
         * Asigna la banda G
1461
         * @param g
1462
         */
1463
        public void setBandG(int g){
1464
                this.gband = g;
1465
        }
1466

    
1467
        /**
1468
         * Sets the B-band.
1469
         *
1470
         * Asigna la banda B
1471
         * @param b
1472
         */
1473
        public void setBandB(int b){
1474
                this.bband = b;
1475
        }
1476

    
1477
    /**
1478
     * @return Returns the wmsTransparency.
1479
     */
1480
    public boolean isWmsTransparent() {
1481
        return wmsTransparency;
1482
    }
1483

    
1484
    /**
1485
     * @param wmsTransparency The wmsTransparency to set.
1486
     */
1487
    public void setWmsTransparency(boolean wmsTransparency) {
1488
        this.wmsTransparency = wmsTransparency;
1489
    }
1490

    
1491
     /**
1492
     * @param styles
1493
     */
1494
    public void setStyles(Vector styles) {
1495
            this.styles = styles;
1496
            //laura:
1497
            //layer query is built with the layer in reverse order
1498
            // so here we build the styles upside-down.
1499
//            if (styles != null)
1500
//            {
1501
//                    this.styles = new Vector();
1502
//                    for(int i = styles.size()-1; i>=0; i--)
1503
//                    {
1504
//                            this.styles.add(styles.elementAt(i));
1505
//                    }
1506
//            }
1507
    }
1508

    
1509
    /**
1510
     * Sets the dimension vector that is a list of key-value pairs containing
1511
     * the name of the dimension and the value for it
1512
     * @param dimensions
1513
     */
1514
    public void setDimensions(Vector dimensions) {
1515
        this.dimensions = dimensions;
1516
    }
1517

    
1518
    /**
1519
     * Sets the set of URLs that should be accessed for each operation performed
1520
     * to the server.
1521
     *
1522
     * @param onlineResources
1523
     */
1524
        public void setOnlineResources(Hashtable onlineResources) {
1525
                this.onlineResources = onlineResources;
1526
        }
1527

    
1528
    /**
1529
     * Gets the URL that should be accessed for an operation performed
1530
     * to the server.
1531
     *
1532
     * @param onlineResources
1533
     */
1534
        public String getOnlineResource(String operation) {
1535
                return ((String) onlineResources.get(operation));
1536
        }
1537

    
1538
        /**
1539
         * When a server is not fully featured and it only can serve constant map
1540
         * sizes this value must be set. It expresses the size in pixels (width, height)
1541
         * that the map will be requested.
1542
         * @param Dimension sz
1543
         */
1544
        public void setFixedSize(Dimension sz) {
1545
                fixedSize = sz;
1546
        }
1547

    
1548
        /**
1549
         * Tells whether if this layer must deal with the server with the constant-size
1550
         * limitations or not.
1551
         * @return boolean.
1552
         */
1553
        private boolean isSizeFixed() {
1554
                return fixedSize != null && fixedSize.getWidth() > 0 && fixedSize.getHeight() > 0;
1555
        }
1556

    
1557
        /**
1558
         * If it is true, this layer accepts GetFeatureInfo operations. This WMS operations
1559
         * maps to FMap's infoByPoint(p) operation.
1560
         * @param b
1561
         */
1562
        public void setQueryable(boolean b) {
1563
                queryable = b;
1564
        }
1565

    
1566
        /**
1567
         * Creates the part of a OGC's MapContext document that would describe this
1568
         * layer(s).
1569
         * @param version, The desired version of the resulting document. (1.1.0)
1570
         * @return String containing the xml.
1571
         * @throws UnsupportedVersionLayerException
1572
         */
1573
        public String toMapContext(String mapContextVersion) {
1574
                XmlBuilder xml = new XmlBuilder();
1575
                FMapWMSDriver drv;
1576
                try {
1577
                        drv = getDriver();
1578
                } catch (Exception e) {
1579
                        return xml.toString();
1580
                }
1581
                String[] layerNames = getLayerQuery().split(",");
1582
                String[] styleNames = (String[]) styles.toArray(new String[0]);
1583
                for (int i = 0; i < layerNames.length; i++) {
1584
                        WMSLayerNode layer = drv.getLayer(layerNames[i]);
1585
                        HashMap xmlAttrs = new HashMap();
1586

    
1587
                        // <Layer>
1588
                        xmlAttrs.put(WebMapContextTags.HIDDEN, !isVisible()+"");
1589
                        xmlAttrs.put(WebMapContextTags.QUERYABLE, queryable+"");
1590
                        xml.openTag(WebMapContextTags.LAYER, xmlAttrs);
1591
                        xmlAttrs.clear();
1592
                        if (mapContextVersion.equals("1.1.0") || mapContextVersion.equals("1.0.0")) {
1593
                                // <Server>
1594
                                xmlAttrs.put(WebMapContextTags.SERVICE, WebMapContextTags.WMS);
1595
                                xmlAttrs.put(WebMapContextTags.VERSION, drv.getVersion());
1596
                                xmlAttrs.put(WebMapContextTags.SERVER_TITLE, drv.getServiceTitle());
1597
                                xml.openTag(WebMapContextTags.SERVER, xmlAttrs);
1598
                                xmlAttrs.clear();
1599

    
1600
                                        // <OnlineResource>
1601
                                        xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1602
                                        xmlAttrs.put(WebMapContextTags.XLINK_HREF, getHost().toString());
1603
                                        xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1604
                                        xmlAttrs.clear();
1605
                                        // </OnlineResource>
1606

    
1607
                                xml.closeTag();
1608
                                // </Server>
1609

    
1610
                                // <Name>
1611
                                xml.writeTag(WebMapContextTags.NAME, layer.getName().trim());
1612
                                // </Name>
1613

    
1614
                                // <Title>
1615
                                xml.writeTag(WebMapContextTags.TITLE, layer.getTitle().trim());
1616
                                //?xml.writeTag(WebMapContextTags.TITLE, getName().trim());
1617
                                // </Title>
1618

    
1619
                                // <Abstract>
1620
                                if (layer.getAbstract() != null)
1621
                                        xml.writeTag(WebMapContextTags.ABSTRACT, layer.getAbstract());
1622
                                // </Abstract>
1623

    
1624
                                // <SRS> (a list of available SRS for the enclosing layer)
1625
                                String[] strings = (String[]) layer.getAllSrs().toArray(new String[0]);
1626
                                String mySRS = strings[0];
1627
                                for (int j = 1; j < strings.length; j++) {
1628
                                        mySRS += ","+strings[j];
1629
                                }
1630
                                xml.writeTag(WebMapContextTags.SRS, mySRS);
1631
                                // </SRS>
1632

    
1633
                                // <FormatList>
1634
                                xml.openTag(WebMapContextTags.FORMAT_LIST);
1635
                                        strings = (String[]) drv.getFormats().toArray(new String[0]);
1636
                                        for (int j = 0; j < strings.length; j++) {
1637
                    // <Format>
1638
                                                String str = strings[j].trim();
1639
                                                if (str.equals(getFormat()))
1640
                                                        xml.writeTag(WebMapContextTags.FORMAT, str, WebMapContextTags.CURRENT, "1");
1641
                                                else
1642
                                                        xml.writeTag(WebMapContextTags.FORMAT, str);
1643
                    // </Format>
1644
                                        }
1645
                                xml.closeTag();
1646
                                // </FormatList>
1647

    
1648
                                // <StyleList>
1649
                                xml.openTag(WebMapContextTags.STYLE_LIST);
1650

    
1651
                                        if (layer.getStyles().size()>0) {
1652
                                                for (int j = 0; j < layer.getStyles().size(); j++) {
1653
                                                        // <Style>
1654
                                                        FMapWMSStyle st = (FMapWMSStyle) layer.getStyles().get(j);
1655
                                                        if (st.name.equals(styleNames[i]))
1656
                                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1657
                                                        xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1658
                                                        xmlAttrs.clear();
1659

    
1660
                                                                // <Name>
1661
                                                                xml.writeTag(WebMapContextTags.NAME, st.name);
1662
                                                                // </Name>
1663

    
1664
                                                                // <Title>
1665
                                                                xml.writeTag(WebMapContextTags.TITLE, st.title);
1666
                                                                // </Title>
1667

    
1668
                                                                // <LegendURL width="180" format="image/gif" height="50">
1669
                                                                        // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1670
                                                                        // </OnlineResource>
1671
                                                                // </LegendURL>
1672
                                                        xml.closeTag();
1673
                                                        // </Style>
1674

    
1675
                                                }
1676

    
1677
                                        } else {
1678
                                                // Create fake style (for compatibility issues)
1679
                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1680
                                                // <Style>
1681
                                                xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1682
                                                        xmlAttrs.clear();
1683
                                                        // <Name>
1684
                                                        xml.writeTag(WebMapContextTags.NAME, "default");
1685
                                                        // </Name>
1686

    
1687
                                                        // <Title>
1688
                                                        xml.writeTag(WebMapContextTags.TITLE, "default");
1689
                                                        // </Title>
1690

    
1691
//                                                        // <LegendURL width="180" format="image/gif" height="50">
1692
//                                                        xmlAttrs.put(WebMapContextTags.WIDTH, "0");
1693
//                                                        xmlAttrs.put(WebMapContextTags.HEIGHT, "0");
1694
//                                                        xmlAttrs.put(WebMapContextTags.FORMAT.toLowerCase(), "image/gif");
1695
//                                                        xml.openTag(WebMapContextTags.LEGEND_URL, xmlAttrs);
1696
//                                                        xmlAttrs.clear();
1697
//                                                                // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1698
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1699
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_HREF, "http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif");
1700
//                                                                xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1701
//                                                                // </OnlineResource>
1702
//                                                    // </LegendURL>
1703
//                                                        xml.closeTag();
1704
                                                // </Style>
1705
                                                xml.closeTag();
1706
                                        }
1707
                                // </StyleList>
1708
                                xml.closeTag();
1709
                                if (mapContextVersion.compareTo("1.0.0") > 0) {
1710
                                // <DimensionList>
1711
                                        xml.openTag(WebMapContextTags.DIMENSION_LIST);
1712
                                        // <Dimension>
1713
                                        // </Dimension>
1714
                                        xml.closeTag();
1715
                                // </DimensionList>
1716
                                }
1717
                        } else {
1718
                                xml.writeTag("ERROR", PluginServices.getText(this, "unsupported_map_context_version"));
1719
                        }
1720
                        // </Layer>
1721
                        xml.closeTag();
1722
                }
1723
                return xml.getXML();
1724
        }
1725

    
1726
        public ImageIcon getTocImageIcon() {
1727
                return new ImageIcon(PluginServices.getPluginServices("com.iver.cit.gvsig.wms").getClassLoader().getResource("images/icoLayer.png"));
1728
        }
1729

    
1730
        /*
1731
         *  (non-Javadoc)
1732
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1733
         */
1734
        public int[] getTileSize() {
1735
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1736
                return size;
1737
        }
1738

    
1739
        /*
1740
         *  (non-Javadoc)
1741
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1742
         */
1743
        public boolean isTiled() {
1744
                return mustTileDraw;
1745
        }
1746

    
1747
        public Image getImageLegend() {
1748
                try {
1749
                        if (wms == null)
1750
                                wms = getDriver();
1751
                        if (wms.hasLegendGraphic()) {
1752
                                wmsStatus.setOnlineResource((String) onlineResources
1753
                                                .get("GetLegendGraphic"));
1754
                                String path = getPathImage();// File legend =
1755
                                                                                                // getDriver().getLegendGraphic(wmsStatus,
1756
                                                                                                // layerQuery, null);
1757
                                Image img = null;
1758
                                if ((path != null) && (path.length() > 0))
1759
                                        img = new ImageIcon(path).getImage();
1760
                                return img;
1761
                        }
1762
                } catch (Exception e) {
1763
                }
1764
                return null;
1765
        }
1766

    
1767
        public String getPathImage() {
1768
                try {
1769
                        File legend = getDriver().getLegendGraphic(wmsStatus, layerQuery, null);
1770
                        return legend.getAbsolutePath();
1771
                }catch(Exception e){
1772
                        e.printStackTrace();
1773
                        return null;
1774
                }
1775
        }
1776

    
1777
        /* (non-Javadoc)
1778
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#newComposedLayer()
1779
         */
1780
        public ComposedLayer newComposedLayer() {                
1781
                return new ComposedLayerWMS();
1782
//                return null;
1783
        }
1784
        
1785
    /**
1786
     * @param styles
1787
     */
1788
    public Vector getStyles() {
1789
            return this.styles;
1790
    }
1791
        
1792
        
1793
        /* Checks if can make a single petition for
1794
         * the two layers to the server
1795
         *   
1796
         * @see com.iver.cit.gvsig.fmap.layers.ComposedLayerWMS#canAdd(com.iver.cit.gvsig.fmap.layers.FLayer)
1797
         */
1798
    boolean isComposedLayerCompatible(FLayer layer) {
1799
                FLyrWMS aLayer;
1800
                
1801
                if (!(layer instanceof FLyrWMS)) {
1802
                        return false;
1803
                }
1804
                aLayer = (FLyrWMS)layer;
1805
                if (!this.getHost().equals(aLayer.getHost())) {
1806
                        return false;
1807
                }
1808
                if (!this.getFormat().equals(aLayer.getFormat())) {
1809
                        return false;
1810
                }
1811
                if (!this.getSRS().equals(aLayer.getSRS())) {
1812
                        return false;
1813
                }
1814
                if (this.getInfoLayerQuery() != null) {
1815
                        if (!this.getInfoLayerQuery().equals(aLayer.getInfoLayerQuery())) {
1816
                                return false;
1817
                        }
1818
                }else if (aLayer.getInfoLayerQuery() != null) {
1819
                        return false;
1820
                }
1821
                
1822
                
1823
                // isFixedSize es privado                
1824
                if ((this.fixedSize != null) && 
1825
                                (aLayer.fixedSize!= null)) {
1826
                        if (this.fixedSize.equals(aLayer.fixedSize)) {
1827
                                return false;
1828
                        }
1829
                } else if ((this.fixedSize != null) != (aLayer.fixedSize != null)) {
1830
                        return false;
1831
                }
1832
                
1833
                // time elevation (dimensions)
1834
                if ((this.dimensions != null) && 
1835
                                (aLayer.dimensions != null)) {
1836
                        if (this.dimensions.size() != aLayer.dimensions.size()) {
1837
                                return false;
1838
                        } else {
1839
                                Iterator iter = this.dimensions.iterator();
1840
                                while (iter.hasNext()) {
1841
                                        if (!aLayer.dimensions.contains(iter.next())) {
1842
                                                return false;
1843
                                        }
1844
                                }
1845
                        }
1846

    
1847
                } else if ((this.dimensions != null) != (aLayer.dimensions != null)) {
1848
                        return false;
1849
                }
1850
                
1851
                
1852
                return true;
1853

    
1854
        }
1855
    
1856
}