Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extWMS / src / com / iver / cit / gvsig / fmap / layers / FLyrWMS.java @ 15801

History | View | Annotate | Download (61.7 KB)

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

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

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

    
73
import org.cresques.geo.ViewPortData;
74
import org.cresques.px.Extent;
75
import org.exolab.castor.xml.ValidationException;
76
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
77
import org.gvsig.fmap.raster.layers.IRasterLayerActions;
78
import org.gvsig.fmap.raster.layers.IStatusRaster;
79
import org.gvsig.fmap.raster.layers.StatusLayerRaster;
80
import org.gvsig.raster.dataset.CompositeDataset;
81
import org.gvsig.raster.dataset.IBuffer;
82
import org.gvsig.raster.dataset.MosaicNotValidException;
83
import org.gvsig.raster.dataset.MultiRasterDataset;
84
import org.gvsig.raster.grid.GridPalette;
85
import org.gvsig.raster.grid.GridTransparency;
86
import org.gvsig.raster.grid.filter.RasterFilterList;
87
import org.gvsig.raster.grid.filter.RasterFilterListManager;
88
import org.gvsig.raster.grid.filter.bands.ColorTableFilter;
89
import org.gvsig.raster.grid.filter.bands.ColorTableListManager;
90
import org.gvsig.remoteClient.utils.Utilities;
91
import org.gvsig.remoteClient.wms.ICancellable;
92
import org.gvsig.remoteClient.wms.WMSStatus;
93

    
94
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
95
import com.hardcode.gdbms.engine.data.driver.DriverException;
96
import com.iver.andami.PluginServices;
97
import com.iver.andami.messages.NotificationManager;
98
import com.iver.cit.gvsig.exceptions.layers.ConnectionErrorLayerException;
99
import com.iver.cit.gvsig.exceptions.layers.LoadLayerException;
100
import com.iver.cit.gvsig.exceptions.layers.URLLayerException;
101
import com.iver.cit.gvsig.exceptions.layers.UnsupportedVersionLayerException;
102
import com.iver.cit.gvsig.fmap.ConnectionErrorExceptionType;
103
import com.iver.cit.gvsig.fmap.ViewPort;
104
import com.iver.cit.gvsig.fmap.WMSDriverExceptionType;
105
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
106
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
107
import com.iver.cit.gvsig.fmap.drivers.wms.FMapWMSDriver;
108
import com.iver.cit.gvsig.fmap.drivers.wms.FMapWMSDriverFactory;
109
import com.iver.cit.gvsig.fmap.drivers.wms.WMSException;
110
import com.iver.cit.gvsig.fmap.layers.WMSLayerNode.FMapWMSStyle;
111
import com.iver.cit.gvsig.fmap.layers.layerOperations.ComposedLayer;
112
import com.iver.cit.gvsig.fmap.layers.layerOperations.StringXMLItem;
113
import com.iver.cit.gvsig.fmap.layers.layerOperations.XMLItem;
114
import com.iver.cit.gvsig.fmap.rendering.ILegend;
115
import com.iver.cit.gvsig.fmap.rendering.XmlBuilder;
116
import com.iver.cit.gvsig.wmc.WebMapContextTags;
117
import com.iver.utiles.StringUtilities;
118
import com.iver.utiles.XMLEntity;
119
import com.iver.utiles.swing.threads.Cancellable;
120

    
121

    
122

    
123
/**
124
* FMap's WMS Layer class.
125
*
126
* Las capas WMS son tileadas para descargarlas del servidor. Esto quiere decir que
127
* est?n formadas por multiples ficheros raster. Por esto la fuente de datos raster (IRasterDatasource)
128
* de la capa FLyrWMS es un objeto de tipo CompositeDataset. Este objeto est? compuesto por un array
129
* bidimensional de MultiRasterDataset. Cada uno de los MultiRasterDataset corresponde con un tile
130
* salvado en disco. Estos MultiRasterDataset se crean cada vez que se repinta ya que en WMS a cada
131
* zoom varian los ficheros fuente. La secuencia de creaci?n de un CompositeDataset ser?a la siguiente:
132
* <UL>
133
* <LI>Se hace una petici?n de dibujado por parte del usuario llamando al m?todo draw de FLyrWMS</LI>
134
* <LI>Se tilea la petici?n</LI>
135
* <LI>Cada tile se dibuja abriendo una FLyerRaster para ese tile</LI>
136
* <LI>Si es el primer dibujado se guarda una referencia en la capa WMS a las propiedades de renderizado, orden de bandas,
137
* transparencia, filtros aplicados, ...</LI>
138
* <LI>Si no es el primer dibujado se asignan las propiedades de renderizado cuya referencia se guarda en la capa WMS</LI>
139
* <LI>Se guarda el MultiRasterDataset de cada tile</LI>
140
* <LI>Al acabar todos los tiles creamos un CompositeDataset con los MultiRasterDataset de todos los tiles</LI>
141
* <LI>Asignamos a la capa la referencia de las propiedades de renderizado que tenemos almacenadas. De esta forma si hay
142
* alguna modificaci?n desde el cuadro de propiedades ser? efectiva sobre los tiles que se dibujan.</LI>
143
* </UL>
144
*
145
*
146
* @author Jaume Dominguez Faus
147
*
148
*/
149
public class FLyrWMS extends FLyrRasterSE {
150
        private boolean                                         isPrinting = false;
151
        private boolean                                         mustTileDraw = true;
152
        private boolean                                         mustTilePrint = true;
153
        private final int                                         maxTileDrawWidth = 1023;
154
        private final int                                         maxTileDrawHeight = 1023;
155
        private final int                                         maxTilePrintWidth = 1023;
156
        private final int                                         maxTilePrintHeight = 1023;
157
        private final int                                        minTilePrintWidth = 12;
158
        private final int                                        minTilePrintHeight = 12;
159

    
160
    public URL                                                         host;
161
    public String                                                 m_Format;
162

    
163
        private String                                                 m_SRS;
164
        private String                                                 layerQuery;
165
        private String                                                 infoLayerQuery;
166
        private FMapWMSDriver                                 wms;
167
        private WMSStatus                                         wmsStatus = new WMSStatus();
168
        private Rectangle2D                                 fullExtent;
169
        private boolean                                                wmsTransparency;
170
    private Vector                                                 styles;
171
    private Vector                                                 dimensions;
172
        private boolean                                                firstLoad = false;
173
        private Hashtable                                         onlineResources = new Hashtable();
174
        private Dimension                                         fixedSize;
175
        private boolean                                         queryable = true;
176
        private VisualStatus                                visualStatus = new VisualStatus();
177
        /**
178
         * Lista de filtros aplicada en la renderizaci?n
179
         */
180
        private RasterFilterList            filterList = null;
181
        private GridTransparency                        transparency = null;
182
        private int[]                       renderBands = null;
183
        private FLyrRasterSE                                layerRaster = null;
184
        private ArrayList                   filterArguments = null;
185

    
186
        private class MyCancellable implements ICancellable
187
        {
188
                private Cancellable original;
189
                public MyCancellable(Cancellable cancelOriginal)
190
                {
191
                        this.original = cancelOriginal;
192
                }
193
                public boolean isCanceled() {
194
                        if (original == null) return false;
195
                        return original.isCanceled();
196
                }
197
                public Object getID() {
198
                        return this;
199
                }
200

    
201
        }
202

    
203
        public FLyrWMS(){
204
                super();
205
        }
206

    
207
        public FLyrWMS(Map args) throws LoadLayerException{
208
                FMapWMSDriver drv = null;
209
                String host = (String)args.get("host");
210
                String sLayer = (String)args.get("layer");
211
                Rectangle2D fullExtent = (Rectangle2D)args.get("FullExtent");
212
                String sSRS = (String)args.get("SRS");
213
                String sFormat = (String)args.get("Format");
214
                String[] sLayers = sLayer.split(",");
215

    
216
                try {
217
                        this.setHost(new URL(host));
218
                } catch (MalformedURLException e) {
219
                        //e.printStackTrace();
220
                        throw new URLLayerException(getName(),e);
221
                }
222
                        try {
223
                                drv = this.getDriver();
224
                        } catch (IllegalStateException e) {
225
                                throw new LoadLayerException(getName(),e);
226
                        } catch (ValidationException e) {
227
                                throw new LoadLayerException(getName(),e);
228
                        } catch (IOException e) {
229
                                throw new ConnectionErrorLayerException(getName(),e);
230
                        }
231
                if( sFormat == null || sSRS == null || fullExtent == null ) {
232
                        if (!drv.connect(null))
233
                                throw new ConnectionErrorLayerException(getName(),null);
234

    
235
                        WMSLayerNode wmsNode = drv.getLayer(sLayer);
236

    
237
                        if (wmsNode == null){
238
                                throw new LoadLayerException(getName(),null);
239
                        }
240
                        if( sFormat == null ) {
241
                                sFormat = this.getGreatFormat(drv.getFormats());
242
                        }
243
                        // SRS
244
                        Vector allSrs = wmsNode.getAllSrs();
245
                        boolean isSRSSupported = false;
246
                        if( sSRS != null ) {
247
                                for (int i=0; i<allSrs.size() ; i++){
248
                                     if (((String)allSrs.get(i)).compareTo(sSRS) == 0){
249
                                             isSRSSupported = true;
250
                                     }
251
                             }
252
                        }
253

    
254
                     if(!isSRSSupported) {
255
                             for (int i=0; i<allSrs.size() ; i++){
256
                                     if (((String)wmsNode.getAllSrs().get(i)).compareTo("EPSG:4326") == 0){
257
                                             sSRS = (String)wmsNode.getAllSrs().get(i);
258
                                     }
259
                             }
260
                             if (sSRS==null){
261
                                     sSRS = (String)wmsNode.getAllSrs().get(0);
262
                             }
263
                     }
264
                        if( fullExtent == null ) {
265
                                fullExtent = drv.getLayersExtent(sLayers,sSRS);
266
                        }
267
                }
268

    
269

    
270
                this.setFullExtent(fullExtent);
271
                this.setFormat(sFormat);
272
                this.setLayerQuery(sLayer);
273
                this.setInfoLayerQuery("");
274
                this.setSRS(sSRS);
275
                this.setName(sLayer);
276
                this.setOnlineResources(drv.getOnlineResources());
277
                load();
278
        }
279

    
280
        /**
281
         * It choose the best format to load different maps if the server
282
         * supports it. This format could be png, because it supports
283
         * transparency.
284
         * @param formats
285
         * Arraywith all the formats supported by the server
286
         * @return
287
         */
288
        private String getGreatFormat(Vector formats){
289
            for (int i=0 ; i<formats.size() ; i++){
290
                String format = (String) formats.get(i);
291
                    if (format.equals("image/jpg")){
292
                    return format;
293
                    }
294
                    if (format.equals("image/jpeg")){
295
                    return format;
296
                    }
297
            }
298

    
299
            return (String)formats.get(0);
300
        }
301

    
302
        /**
303
         * Clase que contiene los datos de visualizaci?n de WMS.
304
         * @author Nacho Brodin (brodin_ign@gva.es)
305
         */
306
        private class VisualStatus{
307
                /**
308
                 * Ancho y alto de la imagen o del conjunto de tiles si los tiene. Coincide con
309
                 * el ancho y alto del viewPort
310
                 */
311
                private double                                                minX = 0D;
312
                private double                                                minY = 0D;
313
                private double                                                maxX = 0D;
314
                private double                                                maxY = 0D;
315
                /**
316
                 * Lista de nombre de fichero que componen toda la visualizaci?n.
317
                 */
318
                private String[]                                        fileNames = null;
319

    
320
        }
321

    
322

    
323
        /**
324
         * Devuelve el XMLEntity con la informaci?n necesaria para reproducir la
325
         * capa.
326
         *
327
         * @return XMLEntity.
328
         * @throws XMLException
329
         */
330
        public XMLEntity getXMLEntity() throws XMLException {
331
                XMLEntity xml = super.getXMLEntity();
332

    
333
                // Full extent
334
                xml.putProperty("fullExtent", StringUtilities.rect2String(fullExtent));
335

    
336
                // Host
337
                xml.putProperty("host", host.toExternalForm());
338

    
339
                // Part of the query that is not the host, or the
340
                // layer names, or other not listed bellow
341
                xml.putProperty("infoLayerQuery", infoLayerQuery);
342

    
343
                // Part of the query containing the layer names
344
                xml.putProperty("layerQuery", layerQuery);
345

    
346
                // Format
347
                xml.putProperty("format", m_Format);
348

    
349
                // SRS
350
                xml.putProperty("srs", m_SRS);
351
                if (status!=null)
352
                        status.getXMLEntity(xml, true, this);
353
                else{
354
                        status = new StatusLayerRaster();
355
                        status.getXMLEntity(xml, true, this);
356
                }
357

    
358
        // Transparency
359
        xml.putProperty("wms_transparency", wmsTransparency);
360

    
361
        // Styles
362
        if (styles!=null){
363
            String stylePr = "";
364
            for (int i = 0; i < styles.size(); i++) {
365
                stylePr += (String) styles.get(i);
366
                if (i<styles.size()-1)
367
                    stylePr += ",";
368
            }
369
            if (stylePr.endsWith(","))
370
                    stylePr += " ";
371
            xml.putProperty("styles", stylePr);
372
        }
373

    
374
        // Dimensions
375
        if (dimensions!=null){
376
            String dim = "";
377
            for (int i = 0; i < dimensions.size(); i++) {
378
                dim += (String) dimensions.get(i);
379
                if (i<dimensions.size()-1)
380
                    dim += ",";
381
            }
382
            if (dim.endsWith(","))
383
                    dim += " ";
384
            xml.putProperty("dimensions", dim);
385
        }
386

    
387
        // OnlineResources
388
        Iterator it = onlineResources.keySet().iterator();
389
        String strOnlines = "";
390
        while (it.hasNext()) {
391
                String key = (String) it.next();
392
                String value = (String) onlineResources.get(key);
393
                strOnlines += key+"~##SEP2##~"+value;
394
                if (it.hasNext())
395
                        strOnlines += "~##SEP1##~";
396
        }
397
        xml.putProperty("onlineResources", strOnlines);
398

    
399
        // Queryable
400
        xml.putProperty("queryable", queryable);
401

    
402
        // fixedSize
403
        if (isSizeFixed()) {
404
                xml.putProperty("fixedSize", true);
405
                xml.putProperty("fixedWidth", fixedSize.width);
406
                xml.putProperty("fixedHeight", fixedSize.height);
407
        }
408
        return xml;
409
        }
410

    
411
        /**
412
         * A partir del XMLEntity reproduce la capa.
413
         *
414
         * @param xml XMLEntity
415
         *
416
         * @throws XMLException
417
         * @throws DriverException
418
         * @throws DriverIOException
419
         */
420
        public void setXMLEntity03(XMLEntity xml)
421
                throws XMLException {
422
                super.setXMLEntity(xml);
423
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty(
424
                                        "fullExtent"));
425

    
426
                try {
427
                        host = new URL(xml.getStringProperty("host"));
428
                } catch (MalformedURLException e) {
429
                        throw new XMLException(e);
430
                }
431

    
432
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
433
                layerQuery = xml.getStringProperty("layerQuery");
434
                m_Format = xml.getStringProperty("format");
435
                m_SRS = xml.getStringProperty("srs");
436
        }
437

    
438
        /**
439
         * A partir del XMLEntity reproduce la capa.
440
         *
441
         * @param xml XMLEntity
442
         *
443
         * @throws XMLException
444
         * @throws DriverException
445
         * @throws DriverIOException
446
         */
447
        public void setXMLEntity(XMLEntity xml)
448
                throws XMLException {
449
                super.setXMLEntity(xml);
450
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty(
451
                                        "fullExtent"));
452

    
453
                // Host
454
                try {
455
                        host = new URL(xml.getStringProperty("host"));
456
                } catch (MalformedURLException e) {
457
                        throw new XMLException(e);
458
                }
459

    
460
                // Part of the query that is not the host, or the
461
                // layer names, or other not listed bellow
462
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
463

    
464
                // Part of the query containing the layer names
465
                layerQuery = xml.getStringProperty("layerQuery");
466

    
467
                // Format
468
                m_Format = xml.getStringProperty("format");
469

    
470
                // SRS
471
                m_SRS = xml.getStringProperty("srs");
472

    
473
                String claseStr = StatusLayerRaster.defaultClass;
474
                if (xml.contains("raster.class")) {
475
                        claseStr = xml.getStringProperty("raster.class");
476
                }
477

    
478
                // Transparency
479
        if (xml.contains("wms_transparency"))
480
            wmsTransparency = xml.getBooleanProperty("wms_transparency");
481

    
482
        // Styles
483
        if (xml.contains("styles")){
484
            styles = new Vector();
485
            String[] stl = xml.getStringProperty("styles").split(",");
486

    
487
            for (int i = 0; i < stl.length; i++) {
488
                    if (stl[i].equals(" "))
489
                            stl[i]="";
490
                styles.add(stl[i]);
491
            }
492
        }
493

    
494
        // Dimensions
495
        if (xml.contains("dimensions")){
496
            dimensions = new Vector();
497
            String[] dims = xml.getStringProperty("dimensions").split(",");
498
            for (int i = 0; i < dims.length; i++){
499
                    if (dims[i].equals(" "))
500
                            dims[i]="";
501

    
502
                dimensions.add(dims[i]);
503
            }
504
        }
505

    
506
        // OnlineResources
507
        if (xml.contains("onlineResources")) {
508
                String[] operations = xml.getStringProperty("onlineResources").split("~##SEP1##~");
509
                for (int i = 0; i < operations.length; i++) {
510
                                String[] resources = operations[i].split("~##SEP2##~");
511
                                if (resources.length==2 && resources[1]!="")
512
                                        onlineResources.put(resources[0], resources[1]);
513
                        }
514
        }
515

    
516
        // Queryable
517
        queryable = true; // let's assume that the layer is queryable by default
518
        if (xml.contains("queryable"))
519
                queryable = xml.getBooleanProperty("queryable");
520

    
521
        // fixedSize
522
        if (xml.contains("fixedSize")) {
523
                fixedSize = new Dimension(xml.getIntProperty("fixedWidth"),
524
                                                  xml.getIntProperty("fixedHeight"));
525
        }
526

    
527
                if(status!=null)
528
                        status.setXMLEntity(xml, this);
529
                else{
530
                        if(claseStr != null && !claseStr.equals("")){
531
                                try{
532
                                        Class clase = LayerFactory.getLayerClassForLayerClassName(claseStr);
533
                                        Constructor constr = clase.getConstructor(null);
534
                                        status = (IStatusRaster)constr.newInstance(null);
535
                                        if(status != null) {
536
                                                ((StatusLayerRaster)status).setNameClass(claseStr);
537
                                                status.setXMLEntity(xml, this);
538
                                                filterArguments = status.getFilterArguments();
539
                                                transparency = status.getTransparency();
540
                                                renderBands = status.getRenderBands();
541
                                        }
542
                                }catch(ClassNotFoundException exc){
543
                                        exc.printStackTrace();
544
                                }catch(InstantiationException exc){
545
                                        exc.printStackTrace();
546
                                }catch(IllegalAccessException exc){
547
                                        exc.printStackTrace();
548
                                }catch(NoSuchMethodException exc){
549
                                        exc.printStackTrace();
550
                                }catch(InvocationTargetException exc){
551
                                        exc.printStackTrace();
552
                                }
553
                        }
554
                }
555
                firstLoad = true;
556
        }
557

    
558
        /**
559
         * @throws ReadDriverException
560
         * @throws LoadLayerException
561
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(com.iver.cit.gvsig.fmap.operations.QueriedPoint)
562
         */
563
        public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancellable) throws ReadDriverException {
564
                /*XMLItem[] superItems = getInfo(p, tolerance, cancellable);
565
                XMLItem[] item =  new XMLItem[superItems.length + 1];
566
                for (int i = 1; i < item.length; i++) {
567
                        item[i] = superItems[i-1];
568
                }*/
569
//
570
                XMLItem[] item = new XMLItem[1];
571
                try {
572
                        if (queryable)         {
573
                                //TODO
574
                                // check if there are layers which are not queryable
575
                                ViewPort viewPort = getMapContext().getViewPort();
576

    
577
                                Point tiledPoint = new Point((int) p.getX() % maxTilePrintWidth, (int) p.getY() % maxTilePrintHeight);
578
                                Rectangle rect = new Rectangle(0, 0, viewPort.getImageWidth() - 1, viewPort.getImageHeight() - 1);
579
                                Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, rect);
580
                                tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
581
                                int nCols = tiles.getNumCols();
582

    
583
                                int col = (int) p.getX() / maxTilePrintWidth;
584
                                int row = (int) p.getY() / maxTilePrintHeight;
585
                                int tileIndex = (row*nCols) + col;
586

    
587
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileIndex);
588
                                wmsStatus.setExtent(vp.getAdjustedExtent());
589
                                wmsStatus.setHeight(vp.getImageHeight());
590
                                wmsStatus.setWidth(vp.getImageWidth());
591
                                wmsStatus.setOnlineResource((String) onlineResources.get("GetFeatureInfo"));
592

    
593

    
594
                                wmsStatus.setFormat( m_Format );
595
                                wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
596
                                wmsStatus.setSrs(m_SRS);
597
                                wmsStatus.setStyles(styles);
598
                                wmsStatus.setDimensions(dimensions);
599
                                wmsStatus.setTransparency(wmsTransparency);
600
                                wmsStatus.setSrs(m_SRS);
601
                                MyCancellable c = new MyCancellable(cancellable);
602
                                try {
603
                                        item[0] = new StringXMLItem(new String(getDriver()
604
                                                        .getFeatureInfo(wmsStatus, (int) tiledPoint.getX(), (int) tiledPoint.getY(), Integer.MAX_VALUE, c)),this);
605
                                } catch (UnsupportedVersionLayerException e) {
606
                                        throw new ReadDriverException(FMapWMSDriver.class.getName()+"::"+getName()+" - UnsupportedVersionLayerException", e);
607
                                } catch (IllegalStateException e) {
608
                                        throw new ReadDriverException(FMapWMSDriver.class.getName()+"::"+getName()+" - IllegalStateException", e);
609
                                }
610
                                return item;
611
                        }
612
                        else
613
                        {
614
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),this.getName() + " " +
615
                                                PluginServices.getText(this,"layer_not_queryable"));
616
                                item[0] =  new StringXMLItem("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><info></info>",this);
617
                                return item;
618
                                //return null;
619
                        }
620
                } catch (WMSException  e) {
621
                        item[0] = new StringXMLItem("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><exception>" +
622
                        e.getMessage() + "</exception>", this);
623
                        return item;
624
                }
625
                /*azabala
626
                catch (ValidationException e) {
627
                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
628
                } catch (UnsupportedVersionException e) {
629
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
630
                } catch (IOException e) {
631
                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
632
                }
633
                */
634
                catch (ValidationException e) {
635
//                        UnknownResponseFormatExceptionType type =
636
//                                new UnknownResponseFormatExceptionType();
637
//                        type.setLayerName(getName());
638
//                        try {
639
//                                type.setDriverName("WMS Driver");
640
//                        } catch (Exception e1) {
641
//                                e1.printStackTrace();
642
//                        }
643
//                        type.setFormat(m_Format);
644
//                        type.setHost(host);
645
//                        type.setProtocol("WMS");
646
                        throw new ReadDriverException(FMapWMSDriver.class.getName()+"::"+getName()+" - ValidationException", e);
647

    
648
                } //catch (UnsupportedVersionLayerException e) {
649
//                        UnsuportedProtocolVersionExceptionType type =
650
//                                new UnsuportedProtocolVersionExceptionType();
651
//                        type.setLayerName(getName());
652
//                        try {
653
//                                type.setDriverName("WMS Driver");
654
//                        } catch (Exception ex){
655
//                        }
656
//                        type.setUrl(host);
657
//                        throw new ReadDriverException(PluginServices.getText(this, "version_conflict"));
658

    
659
//                }
660
                catch (IOException e) {
661
//                        ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
662
//                        type.setLayerName(getName());
663
//                        try {
664
//                                type.setDriverName("WMS Driver");
665
//                        } catch (Exception e1) {
666
//                        }
667
//                        type.setHost(host);
668
                        throw new ReadDriverException(FMapWMSDriver.class.getName()+"::"+getName()+" - IOException", e);
669

    
670
                }
671
                catch (NoninvertibleTransformException e) {
672
                        NotificationManager.addError("NotinvertibleTransform", e);
673
                }
674
                return null;
675
        }
676

    
677
        /**
678
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent()
679
         */
680
        public Rectangle2D getFullExtent() {
681
                return fullExtent;
682
        }
683

    
684
        /**
685
         *
686
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#draw(java.awt.image.BufferedImage,
687
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
688
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
689
         */
690
        private int callCount; // mess code, represents the amount of times the methods drawFixedSize or drawTile where tried for an extent
691
        private static final int MAX_RETRY_TIMES = 5; // mess code, represents the max amount of retries allowed.
692
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
693
                        Cancellable cancel,double scale) throws ReadDriverException {
694
                callCount = 0; // mess code
695
                enableStopped();
696
                if (isWithinScale(scale)){
697
                        Point2D p = viewPort.getOffset();
698
                        // p will be (0, 0) when drawing a view or other when painting onto
699
                        // the Layout.
700
                        visualStatus.minX = viewPort.getAdjustedExtent().getMinX();
701
                        visualStatus.minY = viewPort.getAdjustedExtent().getMinY();
702
                        visualStatus.maxX = viewPort.getAdjustedExtent().getMaxX();
703
                        visualStatus.maxY = viewPort.getAdjustedExtent().getMaxY();
704

    
705

    
706
                        if (isSizeFixed()) {
707
                                // This condition handles those situations in which the server can
708
                                // only give static extent and resolution maps despite we need
709
                                // a specific BBOX and pixel WIDTH and HEIGHT
710
                                try {
711
                                        visualStatus.fileNames = new String[1];
712
                                        drawFixedSize(g, viewPort, cancel, scale);
713
                                        dataset = layerRaster.getDataSource();
714
                                        initializeRasterLayer(null, new IBuffer[][]{{layerRaster.getRender().getLastRenderBuffer()}});
715
                                        getRender().setLastRenderBuffer(layerRaster.getRender().getLastRenderBuffer());
716
                                } catch (LoadLayerException e) {
717
                                        // TODO Auto-generated catch block
718
                                        e.printStackTrace();
719
                                }
720

    
721
                        } else {
722
                                if(mustTileDraw){
723
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), viewPort.getImageWidth(), viewPort.getImageHeight());
724
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
725
                                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
726
                                        visualStatus.fileNames = new String[tiles.getNumTiles()];
727
                                        MultiRasterDataset[][] datasets = new MultiRasterDataset[tiles.getNumRows()][tiles.getNumCols()];
728
                                        IBuffer[][] buf = new IBuffer[tiles.getNumRows()][tiles.getNumCols()];
729
                                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
730
                                                // drawing part
731
                                                try {
732
                                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
733
                                                        drawTile(g, vp, cancel, tileNr, scale);
734
                                                        if(layerRaster != null) {
735
                                                                datasets[(int)(tileNr / tiles.getNumCols())][tileNr % tiles.getNumCols()] = (MultiRasterDataset)layerRaster.getDataSource().copy();
736
                                                                buf[(int)(tileNr / tiles.getNumCols())][tileNr % tiles.getNumCols()] = layerRaster.getRender().getLastRenderBuffer();
737
                                                        }
738
                                                } catch (NoninvertibleTransformException e) {
739
                                                        e.printStackTrace();
740
                                                } catch (LoadLayerException e) {
741
                                                        // TODO Auto-generated catch block
742
                                                        e.printStackTrace();
743
                                                }
744
                                        }
745
                                        try {
746
                                                if(datasets != null && datasets[0][0] != null) {
747
                                                        dataset = new CompositeDataset(datasets);
748
                                                        initializeRasterLayer(datasets, buf);
749
                                                }
750
                                        } catch (MosaicNotValidException e) {
751
                                                throw new ReadDriverException("No hay continuidad en el mosaico.", e);
752
                                        } catch (LoadLayerException e) {
753
                                                throw new ReadDriverException("Error inicializando la capa.", e);
754
                                        }
755
                                } else
756
                                        try {
757
                                                visualStatus.fileNames = new String[1];
758
                                                drawTile(g, viewPort, cancel, 0, scale);
759
                                                dataset = layerRaster.getDataSource();
760
                                                getRender().setLastRenderBuffer(layerRaster.getRender().getLastRenderBuffer());
761
                                                initializeRasterLayer(null, new IBuffer[][]{{layerRaster.getRender().getLastRenderBuffer()}});
762
                                        } catch (LoadLayerException e) {
763
                                                // TODO Auto-generated catch block
764
                                                e.printStackTrace();
765
                                        }
766
                        }
767
                }
768
                disableStopped();
769
//                Runtime r = Runtime.getRuntime();
770
//                long mem = r.totalMemory() - r.freeMemory();
771
//                System.err.println("Memoria total: " + (mem / 1024) +"KB");
772
        }
773

    
774
        /**
775
         * Acciones que se realizan despu?s de asignar la fuente de datos a
776
         * la capa raster.
777
         *
778
         * @throws LoadLayerException
779
         */
780
        private void initializeRasterLayer(MultiRasterDataset[][] datasets, IBuffer[][] buf) throws LoadLayerException {
781
                if(this.filterList != null)
782
                        getRender().setFilterList(filterList);
783
                if(this.transparency != null)
784
                        getRender().setLastTransparency(transparency);
785
                if(this.renderBands != null)
786
                        getRender().setRenderBands(renderBands);
787
                if(datasets != null) {
788
                        String[][] names = new String[datasets.length][datasets[0].length];
789
                        for (int i = 0; i < datasets.length; i++)
790
                                for (int j = 0; j < datasets[i].length; j++)
791
                                        names[i][j] = datasets[i][j].getDataset(0)[0].getFName();
792
                        super.setLoadParams(names);
793
                }
794
                super.init();
795
                if(buf != null) {
796
                        int drawablesBandCount = layerRaster.getDataSource().getBands().getDrawableBandsCount();
797
                        IBuffer buff = null;
798
                        if(dataset instanceof CompositeDataset)
799
                                buff = ((CompositeDataset)dataset).generateBuffer(buf, drawablesBandCount);
800
                        else
801
                                buff = buf[0][0];
802
                        getRender().setLastRenderBuffer(buff);
803
                }
804
        }
805

    
806
        private void drawFixedSize(Graphics2D g, ViewPort vp, Cancellable cancel, double scale) throws ReadDriverException, LoadLayerException {
807
                callCount++; // mess code, it is not unusual a wms server to response an error which is completely
808
                                         // temporal and the response is available if we retry requesting.
809
                                         //
810

    
811

    
812
                // This is the extent that will be requested
813
                Rectangle2D bBox = getFullExtent();
814
                MyCancellable c = new MyCancellable(cancel);
815

    
816
                try {
817
                        wmsStatus.setExtent( bBox );
818
                        wmsStatus.setFormat( m_Format );
819
                        wmsStatus.setHeight( fixedSize.height );
820
                        wmsStatus.setWidth( fixedSize.width );
821
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
822
                        wmsStatus.setSrs(m_SRS);
823
                        wmsStatus.setStyles(styles);
824
                        wmsStatus.setDimensions(dimensions);
825
                        wmsStatus.setTransparency(wmsTransparency);
826
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
827
                        File f = getDriver().getMap(wmsStatus, c);
828
                        if (f == null)
829
                                return;
830
                        String nameWorldFile = f.getPath() + getExtensionWorldFile();
831
                        com.iver.andami.Utilities.createTemp(nameWorldFile, this.getDataWorldFile(bBox, fixedSize));
832

    
833
                        IStatusRaster status = getStatus();
834
                        if(status!=null && firstLoad){
835
                                status.applyStatus(this);
836
                                firstLoad = false;
837
                        }
838

    
839
                        // And finally, obtain the extent intersecting the view and the BBox
840
                        // to draw to.
841
                        Rectangle2D extent = new Rectangle2D.Double();
842
                        Rectangle2D.intersect(vp.getAdjustedExtent(), bBox, extent);
843

    
844
                        ViewPortData vpData = new ViewPortData(
845
                                vp.getProjection(), new Extent(extent), fixedSize );
846
                        vpData.setMat(vp.getAffineTransform());
847

    
848
                        String filePath = f.getAbsolutePath();
849
                        visualStatus.fileNames[0] = filePath;
850

    
851
                        rasterProcess(filePath, g, vp, scale, cancel);
852
                } catch (ValidationException e) {
853
                        if (!c.isCanceled())
854
                        {
855
//                                UnknownResponseFormatExceptionType type =
856
//                                        new UnknownResponseFormatExceptionType();
857
//                                type.setLayerName(getName());
858
//                                try {
859
//                                        type.setDriverName("WMS Driver");
860
//                                } catch (Exception e1) {
861
//                                        e1.printStackTrace();
862
//                                }
863
//                                type.setFormat(m_Format);
864
//                                type.setHost(host);
865
//                                type.setProtocol("WMS");
866
                                LoadLayerException exception = new LoadLayerException(getName(),e);
867
                                throw exception;
868
                        }
869
//        azabala                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
870
//                } catch (UnsupportedVersionLayerException e) {
871
//                        if (!c.isCanceled()){
872
//                                UnsuportedProtocolVersionExceptionType type =
873
//                                        new UnsuportedProtocolVersionExceptionType();
874
//                                type.setLayerName(getName());
875
//                                try {
876
//                                        type.setDriverName("WMS Driver");
877
//                                } catch (Exception ex){
878
//                                }
879
//                                type.setUrl(host);
880
//                                throw new ReadDriverException(PluginServices.getText(this, "version_conflict"));
881
//                        }
882
//        azabala                throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
883
                } catch (IOException e) {
884
                        if (!c.isCanceled())
885
                                if (callCount<MAX_RETRY_TIMES) { // mess code
886
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
887
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
888
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
889
                                        drawFixedSize(g, vp, cancel, scale); // mess code
890
                                } // mess code
891

    
892
                                if (callCount == 1) { // mess code
893
                                        ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
894
                                        type.setLayerName(getName());
895
                                        try {
896
                                                type.setDriverName("WMS Driver");
897
                                        } catch (Exception e1) {
898
                                        }
899
                                        type.setHost(host);
900
                                        throw new ConnectionErrorLayerException(getName(),e);
901
//        azabala        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
902
                                } // mess code
903

    
904

    
905
                } catch (WMSException e) {
906
                        if (!c.isCanceled()) {
907
                                if (callCount<MAX_RETRY_TIMES) { // mess code
908
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
909
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
910
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
911
                                        drawFixedSize(g, vp, cancel, scale); // mess code
912
                                } // mess code
913
                                if (callCount == 1) { // mess code
914
//                azabala                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
915
//                                        WMSDriverExceptionType type = new WMSDriverExceptionType();
916
//                                        type.setLayerName(getName());
917
//                                        try {
918
//                                                type.setDriverName("WMS Driver");
919
//                                        } catch (Exception e1) {
920
//                                        }
921
//                                        type.setWcsStatus(this.wmsStatus);
922
                                        if (!isPrinting)
923
                                                this.setVisible(false);
924
                                        throw new LoadLayerException(getName(),e);
925

    
926

    
927
                                } // mess code
928
                        }
929
                }
930
                callCount--; // mess code
931
        }
932

    
933
        /**
934
         * Carga y dibuja el raster usando la librer?a
935
         * @param filePath Ruta al fichero en disco
936
         * @param g Graphics2D
937
         * @param vp ViewPort
938
         * @param scale Escala para el draw
939
         * @param cancel Cancelaci?n para el draw
940
         * @throws ReadDriverException
941
         * @throws LoadLayerException
942
         */
943
        private void rasterProcess(String filePath, Graphics2D g, ViewPort vp, double scale, Cancellable cancel) throws ReadDriverException, LoadLayerException {
944
                //Cerramos el dataset asociado a la capa si est? abierto.
945
                if(layerRaster != null) {
946
                        layerRaster.setRemoveRasterFlag(true);
947
                        layerRaster.getDataSource().close();
948
                }
949

    
950
                //Cargamos el dataset con el raster de disco.
951
                layerRaster = FLyrRasterSE.createLayer("", filePath, vp.getProjection());
952
                layerRaster.getRender().setBufferFactory(layerRaster.getBufferFactory());
953

    
954
                //Obtenemos la tabla de color del raster abierto ya que se le va a sustituir la lista
955
                //de filtros y el de tabla de color no queremos sustituirlo.
956
                RasterFilterList rasterFilterList = layerRaster.getRender().getFilterList();
957
                ColorTableFilter ct = (ColorTableFilter)rasterFilterList.getFilterByBaseClass(ColorTableFilter.class);
958
                Object param = null;
959
                if(ct != null)
960
                        param = ct.getParam("colorTable");
961

    
962
                //En caso de cargar un proyecto con XMLEntity se crean los filtros
963
                if(filterArguments != null) {
964
                        RasterFilterList fl = new RasterFilterList();
965
                        fl.addEnvParam("IStatistics", layerRaster.getDataSource().getStatistics());
966
                        fl.addEnvParam("MultiRasterDataset", layerRaster.getDataSource());
967
                        fl.setInitDataType(layerRaster.getDataType()[0]);
968
                        RasterFilterListManager filterListManager = new RasterFilterListManager(fl);
969
                        filterListManager.createFilterListFromStrings(filterArguments);
970
                        filterArguments = null;
971
                        filterList = fl;
972
                }
973

    
974
                //Como el raster se carga a cada zoom el render se crea nuevamente y la lista de
975
                //filtros siempre estar? vacia a cada visualizaci?n. Para evitarlo tenemos que
976
                //guardar la lista de filtro aplicada en la visualizaci?n anterior.
977
                if(this.filterList != null) {
978
                        //Si ten?a tabla de color le asignamos la original
979
                        if(param != null && param instanceof GridPalette) {
980
                                this.filterList.remove(ColorTableFilter.class);
981
                                RasterFilterListManager filterManager = new RasterFilterListManager(filterList);
982
                                ColorTableListManager ctm = new ColorTableListManager(filterManager);
983
                                ctm.addColorTableFilter((GridPalette)param);
984
                                filterList.move(ColorTableFilter.class, 0);
985
                                filterList.controlTypes();
986
                        }
987
                        layerRaster.getRender().setFilterList(filterList);
988
                }
989
                if(this.transparency != null)
990
                        layerRaster.getRender().setLastTransparency(transparency);
991
                if(this.renderBands != null)
992
                        layerRaster.getRender().setRenderBands(renderBands);
993

    
994
                //Dibujamos
995
                layerRaster.draw(null, g, vp, cancel, scale);
996

    
997
                //La primera vez asignamos la lista de filtros asociada al renderizador. Guardamos una referencia
998
                //en esta clase para que a cada zoom no se pierda.
999
                if (this.filterList == null)
1000
                        filterList = layerRaster.getRender().getFilterList();
1001
                if (this.transparency == null)
1002
                        transparency = layerRaster.getRender().getLastTransparency();
1003
                if (this.renderBands == null)
1004
                        renderBands = layerRaster.getRender().getRenderBands();
1005

    
1006
        }
1007

    
1008
        /*
1009
         * (non-Javadoc)
1010
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderFilterList()
1011
         */
1012
        public RasterFilterList getRenderFilterList(){
1013
                return (filterList != null) ? filterList : getRender().getFilterList();
1014
        }
1015

    
1016
        /*
1017
         * (non-Javadoc)
1018
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderFilterList(org.gvsig.raster.grid.filter.RasterFilterList)
1019
         */
1020
        public void setRenderFilterList(RasterFilterList filterList) {
1021
                this.filterList = filterList;
1022
                super.getRender().setFilterList(filterList);
1023
        }
1024

    
1025
        /*
1026
         * (non-Javadoc)
1027
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderTransparency()
1028
         */
1029
        public GridTransparency getRenderTransparency() {
1030
                return (transparency != null) ? transparency : getRender().getLastTransparency();
1031
        }
1032

    
1033
        /*
1034
         * (non-Javadoc)
1035
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getRenderBands()
1036
         */
1037
        public int[] getRenderBands() {
1038
                return (renderBands != null) ? renderBands : getRender().getRenderBands();
1039
        }
1040

    
1041
        /*
1042
         * (non-Javadoc)
1043
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderBands(int[])
1044
         */
1045
        public void setRenderBands(int[] renderBands) {
1046
                this.renderBands = renderBands;
1047
                getRender().setRenderBands(renderBands);
1048
        }
1049

    
1050
        /**
1051
         * This is the method used to draw a tile in a WMS mosaic layer.
1052
         * @throws LoadLayerException
1053
         * @throws ReadDriverException
1054
         */
1055
        private void drawTile(Graphics2D g, ViewPort vp, Cancellable cancel, int tile, double scale) throws LoadLayerException, ReadDriverException {
1056
                callCount++;
1057
                // Compute the query geometry
1058
                // 1. Check if it is within borders
1059
                Rectangle2D extent = getFullExtent();
1060
        if ((vp.getAdjustedExtent().getMinX() > extent.getMaxX()) ||
1061
                (vp.getAdjustedExtent().getMinY() > extent.getMaxY()) ||
1062
                (vp.getAdjustedExtent().getMaxX() < extent.getMinX()) ||
1063
                (vp.getAdjustedExtent().getMaxY() < extent.getMinY())) {
1064
            return;
1065
        }
1066

    
1067
        // 2. Compute extent to be requested.
1068
        Rectangle2D bBox = new Rectangle2D.Double();
1069
        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
1070

    
1071
        // 3. Compute size in pixels
1072
        double scalex = vp.getAffineTransform().getScaleX();
1073
        double scaley = vp.getAffineTransform().getScaleY();
1074
        int wImg = (int) Math.ceil(Math.abs(bBox.getWidth() * scalex) + 1);
1075
        int hImg = (int) Math.ceil(Math.abs(bBox.getHeight() * scaley) + 1);
1076

    
1077
        Dimension sz = new Dimension(wImg, hImg);
1078

    
1079
        if ((wImg <= 0) || (hImg <= 0)) {
1080
            return;
1081
        }
1082
        MyCancellable c = new MyCancellable(cancel);
1083

    
1084
                try {
1085
//                        wImg = vp.getImageWidth();
1086
//                        hImg = vp.getImageHeight();
1087
                        sz = new Dimension(wImg, hImg);
1088
                        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
1089

    
1090

    
1091
                        wmsStatus.setExtent( bBox );
1092
                        wmsStatus.setFormat(m_Format);
1093
                        wmsStatus.setHeight( hImg );
1094
                        wmsStatus.setWidth( wImg );
1095
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
1096
                        wmsStatus.setSrs(m_SRS);
1097
                        wmsStatus.setStyles(styles);
1098
                        wmsStatus.setDimensions(dimensions);
1099
                        wmsStatus.setTransparency(wmsTransparency);
1100
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
1101

    
1102
                        // begin patch; Avoid to request too small tiles.
1103
                        // This generally occurs when printing
1104

    
1105
                        if (wImg < minTilePrintWidth) {
1106
                                double wScale = (double) minTilePrintWidth / wImg;
1107
                                wmsStatus.setWidth(minTilePrintWidth);
1108
                                Rectangle2D sExtent = wmsStatus.getExtent();
1109
                                Point2D initialPoint = new Point2D.Double(sExtent.getX(), sExtent.getY());
1110
                                sExtent.setRect(sExtent.getX()*wScale, sExtent.getY(), sExtent.getWidth()*wScale, sExtent.getHeight());
1111
                                if (!bBox.contains(initialPoint)) {
1112
                                        sExtent.setRect(sExtent.getX() - initialPoint.getX(), sExtent.getY(), sExtent.getWidth(), sExtent.getHeight());
1113
                                }
1114
                        }
1115

    
1116
                        if (hImg < minTilePrintHeight) {
1117
                                double hScale = (double) minTilePrintHeight / hImg;
1118
                                wmsStatus.setHeight(minTilePrintHeight);
1119
                                Rectangle2D sExtent = wmsStatus.getExtent();
1120
                                Point2D initialPoint = new Point2D.Double(sExtent.getX(), sExtent.getY());
1121
                                sExtent.setRect(sExtent.getX(), sExtent.getY()*hScale, sExtent.getWidth(), sExtent.getHeight()*hScale);
1122
                                if (!bBox.contains(initialPoint)) {
1123
                                        sExtent.setRect(sExtent.getX(), sExtent.getY() - initialPoint.getY(), sExtent.getWidth(), sExtent.getHeight());
1124
                                }
1125
                        }
1126

    
1127
                        // end patch
1128
                        File f = getDriver().getMap(wmsStatus, c);
1129
                        if (f == null)
1130
                                return;
1131
                        String nameWordFile = f.getPath() + getExtensionWorldFile();
1132
                        com.iver.andami.Utilities.createTemp(nameWordFile, this.getDataWorldFile(bBox, sz));
1133

    
1134
                        ViewPortData vpData = new ViewPortData(
1135
                                vp.getProjection(), new Extent(bBox), sz );
1136
                        vpData.setMat(vp.getAffineTransform());
1137

    
1138
                        String filePath = f.getAbsolutePath();
1139
                        visualStatus.fileNames[tile] = filePath;
1140
                        rasterProcess(filePath, g, vp, scale, cancel);
1141

    
1142
                } catch (ValidationException e) {
1143
                //azabala
1144
//                        if (!c.isCanceled())
1145
//                                throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
1146

    
1147
                        if (!c.isCanceled())
1148
                        {
1149
//                                UnknownResponseFormatExceptionType type =
1150
//                                        new UnknownResponseFormatExceptionType();
1151
//                                type.setLayerName(getName());
1152
//                                try {
1153
//                                        type.setDriverName("WMS Driver");
1154
//                                } catch (Exception e1) {
1155
//                                        e1.printStackTrace();
1156
//                                }
1157
//                                type.setFormat(m_Format);
1158
//                                type.setHost(host);
1159
//                                type.setProtocol("WMS");
1160
                                LoadLayerException exception = new LoadLayerException(getName(),e);
1161
                                throw exception;
1162
                        }
1163
//                } catch (UnsupportedVersionLayerException e) {
1164
//
1165
////                        if (!c.isCanceled())
1166
////                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
1167
//
1168
//                        if (!c.isCanceled()){
1169
//                                UnsuportedProtocolVersionExceptionType type =
1170
//                                        new UnsuportedProtocolVersionExceptionType();
1171
//                                type.setLayerName(getName());
1172
//                                try {
1173
//                                        type.setDriverName("WMS Driver");
1174
//                                } catch (Exception ex){
1175
//                                }
1176
//                                type.setUrl(host);
1177
//                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e, type);
1178
//                        }
1179
//
1180
                } catch (IOException e) {
1181
                        /*azabala
1182
                        if (!c.isCanceled())
1183
                                if (callCount<MAX_RETRY_TIMES) {
1184
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null);
1185
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error
1186
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0)
1187
                                        drawTile(g, vp, cancel);
1188
                                }
1189
                                if (callCount == 1) {
1190
                                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
1191
                                }
1192
                        */
1193
                        if (!c.isCanceled()){
1194
                                if (callCount<MAX_RETRY_TIMES) { // mess code
1195
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
1196
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
1197
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
1198

    
1199
                                        drawFixedSize(g, vp, cancel, scale); // mess code
1200
                                } // mess code
1201
                        }
1202
                        if (callCount == 1) { // mess code
1203
//                                ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
1204
//                                type.setLayerName(getName());
1205
//                                try {
1206
//                                        type.setDriverName("WMS Driver");
1207
//                                } catch (Exception e1) {}
1208
//                                type.setHost(host);
1209
                                throw new ConnectionErrorLayerException(getName(),e);
1210
                        }//if
1211
                } catch (WMSException e) {
1212
                        /*azabala
1213
                        if (!c.isCanceled()) {
1214
                                if (callCount<MAX_RETRY_TIMES) {
1215
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawTile() ] Failed in trying " + callCount + "/" + MAX_RETRY_TIMES +" \n", null);
1216
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error
1217
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0)
1218
                                        drawTile(g, vp, cancel);
1219
                                }
1220
                                if (callCount == 1) {
1221
                                        if (!isPrinting) {
1222
                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
1223
                                                this.setVisible(false);
1224
                                        }
1225
                                }
1226
                        }
1227
                        */
1228
                        if (!c.isCanceled()) {
1229
                                if (callCount<MAX_RETRY_TIMES) { // mess code
1230
                                        Logger.getAnonymousLogger().warning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n"); // mess code
1231
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
1232
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
1233
                                        drawTile(g, vp, cancel, tile, scale);
1234
                                } // mess code
1235
                                if (callCount == 1) { // mess code
1236
//                azabala                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
1237
                                        WMSDriverExceptionType type = new WMSDriverExceptionType();
1238
                                        type.setLayerName(getName());
1239
                                        try {
1240
                                                type.setDriverName("WMS Driver");
1241
                                        } catch (Exception e1) {
1242
                                        }
1243
                                        type.setWcsStatus(this.wmsStatus);
1244
                                        if (!isPrinting)
1245
                                                this.setVisible(false);
1246
                                        throw new LoadLayerException(getName(),e);
1247

    
1248

    
1249
                                } //if
1250
                        }//if
1251
                }//catch
1252
                callCount--;
1253
        }
1254

    
1255
        /**
1256
         * Obtiene la extensi?n del fichero de georreferenciaci?n
1257
         * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
1258
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
1259
         */
1260
        private String getExtensionWorldFile(){
1261
                String extWorldFile = ".wld";
1262
            if(m_Format.equals("image/tif") || m_Format.equals("image/tiff"))
1263
                    extWorldFile = ".tfw";
1264
            if(m_Format.equals("image/jpeg"))
1265
                    extWorldFile = ".jpgw";
1266
            return extWorldFile;
1267
        }
1268

    
1269
        /**
1270
         * Calcula el contenido del fichero de georreferenciaci?n de una imagen.
1271
         * @param bBox Tama?o y posici?n de la imagen (en coordenadas de usuario)
1272
         * @param sz Tama?o de la imagen en pixeles.
1273
         * @return el 'WorldFile', como String.
1274
         * @throws IOException
1275
         */
1276
        public String getDataWorldFile(Rectangle2D bBox, Dimension sz) throws IOException {
1277
                StringBuffer data = new StringBuffer();
1278
            data.append((bBox.getMaxX() - bBox.getMinX())/(sz.getWidth() - 1)+"\n");
1279
            data.append("0.0\n");
1280
            data.append("0.0\n");
1281
            data.append("-"+(bBox.getMaxY() - bBox.getMinY())/(sz.getHeight() - 1)+"\n");
1282
            data.append(""+bBox.getMinX()+"\n");
1283
            data.append(""+bBox.getMaxY()+"\n");
1284
            return data.toString();
1285
        }
1286

    
1287
        /**
1288
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D,
1289
         *                 com.iver.cit.gvsig.fmap.ViewPort,
1290
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
1291
         */
1292
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet properties)
1293
                throws ReadDriverException {
1294
                if (isVisible() && isWithinScale(scale)){
1295
                isPrinting = true;
1296
                if (!mustTilePrint) {
1297
                        draw(null, g, viewPort, cancel,scale);
1298
                } else {
1299
                // Para no pedir imagenes demasiado grandes, vamos
1300
                // a hacer lo mismo que hace EcwFile: chunkear.
1301
                // Llamamos a drawView con cuadraditos m?s peque?os
1302
                // del BufferedImage ni caso, cuando se imprime viene con null
1303

    
1304
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
1305
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
1306
                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
1307
                            // Parte que dibuja
1308
                            try {
1309
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
1310
                                drawTile(g, vp, cancel, tileNr, scale);
1311
                                } catch (NoninvertibleTransformException e) {
1312
                                        e.printStackTrace();
1313
                                } catch (LoadLayerException e) {
1314
                                        // TODO Auto-generated catch block
1315
                                        e.printStackTrace();
1316
                                }
1317
                }
1318
                }
1319
            isPrinting = false;
1320
                }
1321
        }
1322

    
1323
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale)
1324
                throws ReadDriverException {
1325
                draw(null, g, viewPort, cancel,scale);
1326
        }
1327

    
1328
        /**
1329
         * Devuelve el FMapWMSDriver.
1330
         *
1331
         * @return FMapWMSDriver
1332
         *
1333
         * @throws IllegalStateException
1334
         * @throws ValidationException
1335
         * @throws UnsupportedVersionLayerException
1336
         * @throws IOException
1337
         */
1338
        private FMapWMSDriver getDriver()
1339
                throws IllegalStateException, ValidationException,
1340
                        UnsupportedVersionLayerException, IOException {
1341
                return FMapWMSDriverFactory.getFMapDriverForURL(host);
1342
        }
1343

    
1344
        /**
1345
         * Devuelve el FMapWMSDriver.
1346
         *
1347
         * @return FMapWMSDriver
1348
         *
1349
         * @throws IllegalStateException
1350
         * @throws ValidationException
1351
         * @throws UnsupportedVersionLayerException
1352
         * @throws IOException
1353
         */
1354
        public void setDriver(FMapWMSDriver drv) {
1355
                wms = drv;
1356
        }
1357

    
1358
        /**
1359
         * Devuelve el URL.
1360
         *
1361
         * @return URL.
1362
         */
1363
        public URL getHost() {
1364
                return host;
1365
        }
1366

    
1367
        /**
1368
         * Inserta el URL.
1369
         *
1370
         * @param host URL.
1371
         */
1372
        public void setHost(URL host) {
1373
                this.host = host;
1374
        }
1375

    
1376
        /**
1377
         * Devuelve la informaci?n de la consulta.
1378
         *
1379
         * @return String.
1380
         */
1381
        public String getInfoLayerQuery() {
1382
                return infoLayerQuery;
1383
        }
1384

    
1385
        /**
1386
         * Inserta la informaci?n de la consulta.
1387
         *
1388
         * @param infoLayerQuery String.
1389
         */
1390
        public void setInfoLayerQuery(String infoLayerQuery) {
1391
                this.infoLayerQuery = infoLayerQuery;
1392
        }
1393

    
1394
        /**
1395
         * Devuelve la consulta.
1396
         *
1397
         * @return String.
1398
         */
1399
        public String getLayerQuery() {
1400
                return layerQuery;
1401
        }
1402

    
1403
        /**
1404
         * Inserta la consulta.
1405
         *
1406
         * @param layerQuery consulta.
1407
         */
1408
        public void setLayerQuery(String layerQuery) {
1409
                this.layerQuery = layerQuery;
1410
        }
1411

    
1412
        /**
1413
         * Devuelve el formato.
1414
         *
1415
         * @return Formato.
1416
         */
1417
        public String getFormat() {
1418
                return m_Format;
1419
        }
1420

    
1421
        /**
1422
         * Inserta el formato.
1423
         *
1424
         * @param format Formato.
1425
         */
1426
        public void setFormat(String format) {
1427
                m_Format = format;
1428
        }
1429

    
1430
        /**
1431
         * Devuelve el SRS.
1432
         *
1433
         * @return SRS.
1434
         */
1435
        public String getSRS() {
1436
                return m_SRS;
1437
        }
1438

    
1439
        /**
1440
         * Inserta el SRS.
1441
         *
1442
         * @param m_srs SRS.
1443
         */
1444
        public void setSRS(String m_srs) {
1445
                m_SRS = m_srs;
1446
                setProjection(CRSFactory.getCRS(getSRS()));
1447
        }
1448

    
1449
        /**
1450
         * Inserta la extensi?n total de la capa.
1451
         *
1452
         * @param fullExtent Rect?ngulo.
1453
         */
1454
        public void setFullExtent(Rectangle2D fullExtent) {
1455
                this.fullExtent = fullExtent;
1456
        }
1457

    
1458
        public HashMap getProperties() {
1459
                HashMap info = new HashMap();
1460
        String[] layerNames = getLayerQuery().split(",");
1461
        Vector layers = new Vector(layerNames.length);
1462
        try {
1463
            if(getDriver().connect(null)){
1464
                for (int i = 0; i < layerNames.length; i++) {
1465
                    layers.add(i, getDriver().getLayer(layerNames[i]));
1466
                }
1467
                info.put("name", getName());
1468
                info.put("selectedLayers", layers);
1469
                info.put("host", getHost());
1470
                info.put("srs", getSRS());
1471
                info.put("format", getFormat());
1472
                info.put("wmsTransparency", new Boolean(wmsTransparency));
1473
                info.put("styles", styles);
1474
                info.put("dimensions", dimensions);
1475
                info.put("fixedSize", fixedSize);
1476
                return info;
1477
            }
1478
        } catch (Exception e) {
1479
            e.printStackTrace();
1480
        }
1481
        return null;
1482
        }
1483

    
1484
        public double getMaxX() {
1485
                return visualStatus.maxX;
1486
        }
1487

    
1488
        public double getMaxY() {
1489
                return visualStatus.maxY;
1490
        }
1491

    
1492
        public double getMinX() {
1493
                return visualStatus.minX;
1494
        }
1495

    
1496
        public double getMinY() {
1497
                return visualStatus.minY;
1498
        }
1499

    
1500
    /**
1501
     * @return Returns the wmsTransparency.
1502
     */
1503
    public boolean isWmsTransparent() {
1504
        return wmsTransparency;
1505
    }
1506

    
1507
    /**
1508
     * @param wmsTransparency The wmsTransparency to set.
1509
     */
1510
    public void setWmsTransparency(boolean wmsTransparency) {
1511
        this.wmsTransparency = wmsTransparency;
1512
    }
1513

    
1514
     /**
1515
     * @param styles
1516
     */
1517
    public void setStyles(Vector styles) {
1518
            this.styles = styles;
1519
    }
1520

    
1521
    /**
1522
     * Sets the dimension vector that is a list of key-value pairs containing
1523
     * the name of the dimension and the value for it
1524
     * @param dimensions
1525
     */
1526
    public void setDimensions(Vector dimensions) {
1527
        this.dimensions = dimensions;
1528
    }
1529

    
1530
    /**
1531
     * Sets the set of URLs that should be accessed for each operation performed
1532
     * to the server.
1533
     *
1534
     * @param onlineResources
1535
     */
1536
        public void setOnlineResources(Hashtable onlineResources) {
1537
                this.onlineResources = onlineResources;
1538
        }
1539

    
1540
    /**
1541
     * Gets the URL that should be accessed for an operation performed
1542
     * to the server.
1543
     *
1544
     * @param onlineResources
1545
     */
1546
        public String getOnlineResource(String operation) {
1547
                return ((String) onlineResources.get(operation));
1548
        }
1549

    
1550
        /**
1551
         * When a server is not fully featured and it only can serve constant map
1552
         * sizes this value must be set. It expresses the size in pixels (width, height)
1553
         * that the map will be requested.
1554
         * @param Dimension sz
1555
         */
1556
        public void setFixedSize(Dimension sz) {
1557
                fixedSize = sz;
1558
        }
1559

    
1560
        /**
1561
         * Tells whether if this layer must deal with the server with the constant-size
1562
         * limitations or not.
1563
         * @return boolean.
1564
         */
1565
        private boolean isSizeFixed() {
1566
                return fixedSize != null && fixedSize.getWidth() > 0 && fixedSize.getHeight() > 0;
1567
        }
1568

    
1569
        /**
1570
         * If it is true, this layer accepts GetFeatureInfo operations. This WMS operations
1571
         * maps to FMap's infoByPoint(p) operation.
1572
         * @param b
1573
         */
1574
        public void setQueryable(boolean b) {
1575
                queryable = b;
1576
        }
1577

    
1578
        /**
1579
         * Creates the part of a OGC's MapContext document that would describe this
1580
         * layer(s).
1581
         * @param version, The desired version of the resulting document. (1.1.0)
1582
         * @return String containing the xml.
1583
         * @throws UnsupportedVersionLayerException
1584
         */
1585
        public String toMapContext(String mapContextVersion) {
1586
                XmlBuilder xml = new XmlBuilder();
1587
                FMapWMSDriver drv;
1588
                try {
1589
                        drv = getDriver();
1590
                } catch (Exception e) {
1591
                        return xml.toString();
1592
                }
1593
                String[] layerNames = getLayerQuery().split(",");
1594
                String[] styleNames = (String[]) styles.toArray(new String[0]);
1595
                for (int i = 0; i < layerNames.length; i++) {
1596
                        WMSLayerNode layer = drv.getLayer(layerNames[i]);
1597
                        HashMap xmlAttrs = new HashMap();
1598

    
1599
                        // <Layer>
1600
                        xmlAttrs.put(WebMapContextTags.HIDDEN, !isVisible()+"");
1601
                        xmlAttrs.put(WebMapContextTags.QUERYABLE, queryable+"");
1602
                        xml.openTag(WebMapContextTags.LAYER, xmlAttrs);
1603
                        xmlAttrs.clear();
1604
                        if (mapContextVersion.equals("1.1.0") || mapContextVersion.equals("1.0.0")) {
1605
                                // <Server>
1606
                                xmlAttrs.put(WebMapContextTags.SERVICE, WebMapContextTags.WMS);
1607
                                xmlAttrs.put(WebMapContextTags.VERSION, drv.getVersion());
1608
                                xmlAttrs.put(WebMapContextTags.SERVER_TITLE, drv.getServiceTitle());
1609
                                xml.openTag(WebMapContextTags.SERVER, xmlAttrs);
1610
                                xmlAttrs.clear();
1611

    
1612
                                        // <OnlineResource>
1613
                                        xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1614
                                        xmlAttrs.put(WebMapContextTags.XLINK_HREF, getHost().toString());
1615
                                        xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1616
                                        xmlAttrs.clear();
1617
                                        // </OnlineResource>
1618

    
1619
                                xml.closeTag();
1620
                                // </Server>
1621

    
1622
                                // <Name>
1623
                                xml.writeTag(WebMapContextTags.NAME, layer.getName().trim());
1624
                                // </Name>
1625

    
1626
                                // <Title>
1627
                                xml.writeTag(WebMapContextTags.TITLE, layer.getTitle().trim());
1628
                                //?xml.writeTag(WebMapContextTags.TITLE, getName().trim());
1629
                                // </Title>
1630

    
1631
                                // <Abstract>
1632
                                if (layer.getAbstract() != null)
1633
                                        xml.writeTag(WebMapContextTags.ABSTRACT, layer.getAbstract());
1634
                                // </Abstract>
1635

    
1636
                                // <SRS> (a list of available SRS for the enclosing layer)
1637
                                String[] strings = (String[]) layer.getAllSrs().toArray(new String[0]);
1638
                                String mySRS = strings[0];
1639
                                for (int j = 1; j < strings.length; j++) {
1640
                                        mySRS += ","+strings[j];
1641
                                }
1642
                                xml.writeTag(WebMapContextTags.SRS, mySRS);
1643
                                // </SRS>
1644

    
1645
                                // <FormatList>
1646
                                xml.openTag(WebMapContextTags.FORMAT_LIST);
1647
                                        strings = (String[]) drv.getFormats().toArray(new String[0]);
1648
                                        for (int j = 0; j < strings.length; j++) {
1649
                    // <Format>
1650
                                                String str = strings[j].trim();
1651
                                                if (str.equals(getFormat()))
1652
                                                        xml.writeTag(WebMapContextTags.FORMAT, str, WebMapContextTags.CURRENT, "1");
1653
                                                else
1654
                                                        xml.writeTag(WebMapContextTags.FORMAT, str);
1655
                    // </Format>
1656
                                        }
1657
                                xml.closeTag();
1658
                                // </FormatList>
1659

    
1660
                                // <StyleList>
1661
                                xml.openTag(WebMapContextTags.STYLE_LIST);
1662

    
1663
                                        if (layer.getStyles().size()>0) {
1664
                                                for (int j = 0; j < layer.getStyles().size(); j++) {
1665
                                                        // <Style>
1666
                                                        FMapWMSStyle st = (FMapWMSStyle) layer.getStyles().get(j);
1667
                                                        if (st.name.equals(styleNames[i]))
1668
                                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1669
                                                        xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1670
                                                        xmlAttrs.clear();
1671

    
1672
                                                                // <Name>
1673
                                                                xml.writeTag(WebMapContextTags.NAME, st.name);
1674
                                                                // </Name>
1675

    
1676
                                                                // <Title>
1677
                                                                xml.writeTag(WebMapContextTags.TITLE, st.title);
1678
                                                                // </Title>
1679

    
1680
                                                                // <LegendURL width="180" format="image/gif" height="50">
1681
                                                                        // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1682
                                                                        // </OnlineResource>
1683
                                                                // </LegendURL>
1684
                                                        xml.closeTag();
1685
                                                        // </Style>
1686

    
1687
                                                }
1688

    
1689
                                        } else {
1690
                                                // Create fake style (for compatibility issues)
1691
                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1692
                                                // <Style>
1693
                                                xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1694
                                                        xmlAttrs.clear();
1695
                                                        // <Name>
1696
                                                        xml.writeTag(WebMapContextTags.NAME, "default");
1697
                                                        // </Name>
1698

    
1699
                                                        // <Title>
1700
                                                        xml.writeTag(WebMapContextTags.TITLE, "default");
1701
                                                        // </Title>
1702

    
1703
//                                                        // <LegendURL width="180" format="image/gif" height="50">
1704
//                                                        xmlAttrs.put(WebMapContextTags.WIDTH, "0");
1705
//                                                        xmlAttrs.put(WebMapContextTags.HEIGHT, "0");
1706
//                                                        xmlAttrs.put(WebMapContextTags.FORMAT.toLowerCase(), "image/gif");
1707
//                                                        xml.openTag(WebMapContextTags.LEGEND_URL, xmlAttrs);
1708
//                                                        xmlAttrs.clear();
1709
//                                                                // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1710
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1711
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_HREF, "http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif");
1712
//                                                                xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1713
//                                                                // </OnlineResource>
1714
//                                                    // </LegendURL>
1715
//                                                        xml.closeTag();
1716
                                                // </Style>
1717
                                                xml.closeTag();
1718
                                        }
1719
                                // </StyleList>
1720
                                xml.closeTag();
1721
                                if (mapContextVersion.compareTo("1.0.0") > 0) {
1722
                                // <DimensionList>
1723
                                        xml.openTag(WebMapContextTags.DIMENSION_LIST);
1724
                                        // <Dimension>
1725
                                        // </Dimension>
1726
                                        xml.closeTag();
1727
                                // </DimensionList>
1728
                                }
1729
                        } else {
1730
                                xml.writeTag("ERROR", PluginServices.getText(this, "unsupported_map_context_version"));
1731
                        }
1732
                        // </Layer>
1733
                        xml.closeTag();
1734
                }
1735
                return xml.getXML();
1736
        }
1737

    
1738
        public ImageIcon getTocImageIcon() {
1739
                return PluginServices.getIconTheme().get("icon-layer-wms");
1740
        }
1741

    
1742
        /*
1743
         *  (non-Javadoc)
1744
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1745
         */
1746
        public int[] getTileSize() {
1747
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1748
                return size;
1749
        }
1750

    
1751
        /*
1752
         *  (non-Javadoc)
1753
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1754
         */
1755
        public boolean isTiled() {
1756
                return mustTileDraw;
1757
        }
1758

    
1759
        public Image getImageLegend() {
1760
                try {
1761
                        if (wms == null)
1762
                                wms = getDriver();
1763
                        if (wms.hasLegendGraphic()) {
1764
                                wmsStatus.setOnlineResource((String) onlineResources
1765
                                                .get("GetLegendGraphic"));
1766
                                String path = getPathImage();// File legend =
1767
                                                                                                // getDriver().getLegendGraphic(wmsStatus,
1768
                                                                                                // layerQuery, null);
1769
                                Image img = null;
1770
                                if ((path != null) && (path.length() > 0))
1771
                                        img = new ImageIcon(path).getImage();
1772
                                return img;
1773
                        }
1774
                } catch (Exception e) {
1775
                }
1776
                return null;
1777
        }
1778

    
1779
        public String getPathImage() {
1780
                try {
1781
                        File legend = getDriver().getLegendGraphic(wmsStatus, layerQuery, null);
1782
                        return legend.getAbsolutePath();
1783
                }catch(Exception e){
1784
                        e.printStackTrace();
1785
                        return null;
1786
                }
1787
        }
1788

    
1789
        /* (non-Javadoc)
1790
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#newComposedLayer()
1791
         */
1792
        public ComposedLayer newComposedLayer() {
1793
                Preferences prefs = Preferences.userRoot().node("gvsig.wms");
1794

    
1795
                String str = prefs.get("useComposedLayer","false");
1796
                Boolean useComposedLayer = Boolean.FALSE;
1797
                try {
1798
                        useComposedLayer = Boolean.valueOf(str);
1799
                } catch (Exception e) {
1800

    
1801
                }
1802
                if (useComposedLayer.booleanValue()) {
1803
                        return new ComposedLayerWMS();
1804
                } else {
1805
                        return null;
1806
                }
1807
        }
1808

    
1809
        /**
1810
   * @param styles
1811
   */
1812
        public Vector getStyles() {
1813
                return this.styles;
1814
        }
1815

    
1816

    
1817
        /*
1818
   * Checks if can make a single petition for the two layers to the server
1819
   * @see com.iver.cit.gvsig.fmap.layers.ComposedLayerWMS#canAdd(com.iver.cit.gvsig.fmap.layers.FLayer)
1820
   */
1821
        boolean isComposedLayerCompatible(FLayer layer) {
1822
                FLyrWMS aLayer;
1823

    
1824
                if (!(layer instanceof FLyrWMS)) {
1825
                        return false;
1826
                }
1827
                aLayer = (FLyrWMS)layer;
1828
                if (!this.getHost().equals(aLayer.getHost())) {
1829
                        return false;
1830
                }
1831
                if (!this.getFormat().equals(aLayer.getFormat())) {
1832
                        return false;
1833
                }
1834
                if (!this.getSRS().equals(aLayer.getSRS())) {
1835
                        return false;
1836
                }
1837
                if (this.getInfoLayerQuery() != null) {
1838
                        if (!this.getInfoLayerQuery().equals(aLayer.getInfoLayerQuery())) {
1839
                                return false;
1840
                        }
1841
                }else if (aLayer.getInfoLayerQuery() != null) {
1842
                        return false;
1843
                }
1844

    
1845

    
1846
                // isFixedSize es privado
1847
                if ((this.fixedSize != null) &&
1848
                                (aLayer.fixedSize!= null)) {
1849
                        if (this.fixedSize.equals(aLayer.fixedSize)) {
1850
                                return false;
1851
                        }
1852
                } else if ((this.fixedSize != null) != (aLayer.fixedSize != null)) {
1853
                        return false;
1854
                }
1855

    
1856
                // time elevation (dimensions)
1857
                if ((this.dimensions != null) &&
1858
                                (aLayer.dimensions != null)) {
1859
                        if (this.dimensions.size() != aLayer.dimensions.size()) {
1860
                                return false;
1861
                        } else {
1862
                                Iterator iter = this.dimensions.iterator();
1863
                                while (iter.hasNext()) {
1864
                                        if (!aLayer.dimensions.contains(iter.next())) {
1865
                                                return false;
1866
                                        }
1867
                                }
1868
                        }
1869

    
1870
                } else if ((this.dimensions != null) != (aLayer.dimensions != null)) {
1871
                        return false;
1872
                }
1873

    
1874
                return true;
1875
        }
1876

    
1877
        /*
1878
         * (non-Javadoc)
1879
         * @see org.gvsig.fmap.raster.layers.FLyrRasterSE#isActionEnabled(int)
1880
         */
1881
        public boolean isActionEnabled(int action) {
1882
                switch (action) {
1883
                        case IRasterLayerActions.ZOOM_PIXEL_RESOLUTION:
1884
                        case IRasterLayerActions.FLYRASTER_BAR_TOOLS:
1885
                        case IRasterLayerActions.BANDS_FILE_LIST:
1886
                        case IRasterLayerActions.COLOR_TABLE:
1887
                        case IRasterLayerActions.GEOLOCATION:
1888
                        case IRasterLayerActions.PANSHARPENING:
1889
                                return false;
1890
                }
1891

    
1892
                return super.isActionEnabled(action);
1893
        }
1894

    
1895
        /*
1896
         * (non-Javadoc)
1897
         * @see org.gvsig.fmap.raster.layers.FLyrRasterSE#getLegend()
1898
         */
1899
        public ILegend getLegend() {
1900
                return null;
1901
        }
1902

    
1903
        /*
1904
         * (non-Javadoc)
1905
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
1906
         */
1907
        public int[] getDataType(){
1908
                try {
1909
                        return dataset.getDataType();
1910
                } catch (NullPointerException e) {
1911
                        if(layerRaster != null)
1912
                                return layerRaster.getDataType();
1913
                        else
1914
                                return new int[]{IBuffer.TYPE_UNDEFINED};
1915
                }
1916
        }
1917
}