Statistics
| Revision:

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

History | View | Annotate | Download (58.6 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.dataset.NotSupportedExtensionException;
85
import org.gvsig.raster.dataset.io.RasterDriverException;
86
import org.gvsig.raster.grid.GridPalette;
87
import org.gvsig.raster.grid.GridTransparency;
88
import org.gvsig.raster.grid.filter.FilterTypeException;
89
import org.gvsig.raster.grid.filter.RasterFilterList;
90
import org.gvsig.raster.grid.filter.RasterFilterListManager;
91
import org.gvsig.raster.grid.filter.bands.ColorTableFilter;
92
import org.gvsig.raster.grid.filter.bands.ColorTableListManager;
93
import org.gvsig.remoteClient.utils.Utilities;
94
import org.gvsig.remoteClient.wms.ICancellable;
95
import org.gvsig.remoteClient.wms.WMSStatus;
96

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

    
125

    
126

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

    
164
        public URL                                                         host;
165
        public String                                                 m_Format;
166

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

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

    
205
        }
206

    
207
        public FLyrWMS(){
208
                super();
209
                this.updateDrawVersion();
210
        }
211

    
212
        public FLyrWMS(Map args) throws LoadLayerException{
213
                this.updateDrawVersion();
214
                FMapWMSDriver drv = null;
215
                String host = (String)args.get("host");
216
                String sLayer = (String)args.get("layer");
217
                Rectangle2D fullExtent = (Rectangle2D)args.get("FullExtent");
218
                String sSRS = (String)args.get("SRS");
219
                String sFormat = (String)args.get("Format");
220
                String[] sLayers = sLayer.split(",");
221

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

    
241
                        WMSLayerNode wmsNode = drv.getLayer(sLayer);
242

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

    
260
                                 if(!isSRSSupported) {
261
                                         for (int i=0; i<allSrs.size() ; i++){
262
                                                 if (((String)wmsNode.getAllSrs().get(i)).compareTo("EPSG:4326") == 0){
263
                                                         sSRS = (String)wmsNode.getAllSrs().get(i);
264
                                                 }
265
                                         }
266
                                         if (sSRS==null){
267
                                                 sSRS = (String)wmsNode.getAllSrs().get(0);
268
                                         }
269
                                 }
270
                        if( fullExtent == null ) {
271
                                fullExtent = drv.getLayersExtent(sLayers,sSRS);
272
                        }
273
                }
274

    
275

    
276
                this.setFullExtent(fullExtent);
277
                this.setFormat(sFormat);
278
                this.setLayerQuery(sLayer);
279
                this.setInfoLayerQuery("");
280
                this.setSRS(sSRS);
281
                this.setName(sLayer);
282
                this.setOnlineResources(drv.getOnlineResources());
283
                load();
284
        }
285

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

    
305
                        return (String)formats.get(0);
306
        }
307

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

    
326
        }
327

    
328

    
329
        /**
330
         * Devuelve el XMLEntity con la informaci?n necesaria para reproducir la
331
         * capa.
332
         *
333
         * @return XMLEntity.
334
         * @throws XMLException
335
         */
336
        public XMLEntity getXMLEntity() throws XMLException {
337
                XMLEntity xml = super.getXMLEntity();
338

    
339
                // Full extent
340
                xml.putProperty("fullExtent", StringUtilities.rect2String(fullExtent));
341

    
342
                // Host
343
                xml.putProperty("host", host.toExternalForm());
344

    
345
                // Part of the query that is not the host, or the
346
                // layer names, or other not listed bellow
347
                xml.putProperty("infoLayerQuery", infoLayerQuery);
348

    
349
                // Part of the query containing the layer names
350
                xml.putProperty("layerQuery", layerQuery);
351

    
352
                // Format
353
                xml.putProperty("format", m_Format);
354

    
355
                // SRS
356
                xml.putProperty("srs", m_SRS);
357
                if (status!=null)
358
                        status.getXMLEntity(xml, true, this);
359
                else{
360
                        status = new StatusLayerRaster();
361
                        status.getXMLEntity(xml, true, this);
362
                }
363

    
364
                                // Transparency
365
                                xml.putProperty("wms_transparency", wmsTransparency);
366

    
367
                                // Styles
368
                                if (styles!=null){
369
                                                String stylePr = "";
370
                                                for (int i = 0; i < styles.size(); i++) {
371
                                                                stylePr += (String) styles.get(i);
372
                                                                if (i<styles.size()-1)
373
                                                                                stylePr += ",";
374
                                                }
375
                                                if (stylePr.endsWith(","))
376
                                                        stylePr += " ";
377
                                                xml.putProperty("styles", stylePr);
378
                                }
379

    
380
                                // Dimensions
381
                                if (dimensions!=null){
382
                                                String dim = "";
383
                                                for (int i = 0; i < dimensions.size(); i++) {
384
                                                                dim += (String) dimensions.get(i);
385
                                                                if (i<dimensions.size()-1)
386
                                                                                dim += ",";
387
                                                }
388
                                                if (dim.endsWith(","))
389
                                                        dim += " ";
390
                                                xml.putProperty("dimensions", dim);
391
                                }
392

    
393
                                // OnlineResources
394
                                Iterator it = onlineResources.keySet().iterator();
395
                                String strOnlines = "";
396
                                while (it.hasNext()) {
397
                                        String key = (String) it.next();
398
                                        String value = (String) onlineResources.get(key);
399
                                        strOnlines += key+"~##SEP2##~"+value;
400
                                        if (it.hasNext())
401
                                                strOnlines += "~##SEP1##~";
402
                                }
403
                                xml.putProperty("onlineResources", strOnlines);
404

    
405
                                // Queryable
406
                                xml.putProperty("queryable", queryable);
407

    
408
                                // fixedSize
409
                                if (isSizeFixed()) {
410
                                        xml.putProperty("fixedSize", true);
411
                                        xml.putProperty("fixedWidth", fixedSize.width);
412
                                        xml.putProperty("fixedHeight", fixedSize.height);
413
                                }
414
                                return xml;
415
        }
416

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

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

    
438
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
439
                layerQuery = xml.getStringProperty("layerQuery");
440
                m_Format = xml.getStringProperty("format");
441
                m_SRS = xml.getStringProperty("srs");
442
        }
443

    
444
        /**
445
         * A partir del XMLEntity reproduce la capa.
446
         *
447
         * @param xml XMLEntity
448
         *
449
         * @throws XMLException
450
         * @throws DriverException
451
         * @throws DriverIOException
452
         */
453
        public void setXMLEntity(XMLEntity xml)
454
                throws XMLException {
455
                super.setXMLEntity(xml);
456
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty(
457
                                        "fullExtent"));
458

    
459
                // Host
460
                try {
461
                        host = new URL(xml.getStringProperty("host"));
462
                } catch (MalformedURLException e) {
463
                        throw new XMLException(e);
464
                }
465

    
466
                // Part of the query that is not the host, or the
467
                // layer names, or other not listed bellow
468
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
469

    
470
                // Part of the query containing the layer names
471
                layerQuery = xml.getStringProperty("layerQuery");
472

    
473
                // Format
474
                m_Format = xml.getStringProperty("format");
475

    
476
                // SRS
477
                m_SRS = xml.getStringProperty("srs");
478

    
479
                String claseStr = StatusLayerRaster.defaultClass;
480
                if (xml.contains("raster.class")) {
481
                        claseStr = xml.getStringProperty("raster.class");
482
                }
483

    
484
                // Transparency
485
                                if (xml.contains("wms_transparency"))
486
                                                wmsTransparency = xml.getBooleanProperty("wms_transparency");
487

    
488
                                // Styles
489
                                if (xml.contains("styles")){
490
                                                styles = new Vector();
491
                                                String[] stl = xml.getStringProperty("styles").split(",");
492

    
493
                                                for (int i = 0; i < stl.length; i++) {
494
                                                        if (stl[i].equals(" "))
495
                                                                stl[i]="";
496
                                                                styles.add(stl[i]);
497
                                                }
498
                                }
499

    
500
                                // Dimensions
501
                                if (xml.contains("dimensions")){
502
                                                dimensions = new Vector();
503
                                                String[] dims = xml.getStringProperty("dimensions").split(",");
504
                                                for (int i = 0; i < dims.length; i++){
505
                                                        if (dims[i].equals(" "))
506
                                                                dims[i]="";
507

    
508
                                                                dimensions.add(dims[i]);
509
                                                }
510
                                }
511

    
512
                                // OnlineResources
513
                                if (xml.contains("onlineResources")) {
514
                                        String[] operations = xml.getStringProperty("onlineResources").split("~##SEP1##~");
515
                                        for (int i = 0; i < operations.length; i++) {
516
                                String[] resources = operations[i].split("~##SEP2##~");
517
                                if (resources.length==2 && resources[1]!="")
518
                                        onlineResources.put(resources[0], resources[1]);
519
                        }
520
                                }
521

    
522
                                // Queryable
523
                                queryable = true; // let's assume that the layer is queryable by default
524
                                if (xml.contains("queryable"))
525
                                        queryable = xml.getBooleanProperty("queryable");
526

    
527
                                // fixedSize
528
                                if (xml.contains("fixedSize")) {
529
                                        fixedSize = new Dimension(xml.getIntProperty("fixedWidth"),
530
                                                                                                                                xml.getIntProperty("fixedHeight"));
531
                                }
532

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

    
564
        /**
565
         * @throws ReadDriverException
566
         * @throws LoadLayerException
567
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(com.iver.cit.gvsig.fmap.operations.QueriedPoint)
568
         */
569
        public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancellable) throws ReadDriverException {
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
                } catch (ValidationException e) {
625
                        throw new ReadDriverException(FMapWMSDriver.class.getName()+"::"+getName()+" - ValidationException", e);
626
                } catch (IOException e) {
627
                        throw new ReadDriverException(FMapWMSDriver.class.getName()+"::"+getName()+" - IOException", e);
628
                } catch (NoninvertibleTransformException e) {
629
                        NotificationManager.addError("NotinvertibleTransform", e);
630
                }
631
                return null;
632
        }
633

    
634
        /*
635
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent()
636
         */
637
        public Rectangle2D getFullExtent() {
638
                return fullExtent;
639
        }
640

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

    
662

    
663
                        if (isSizeFixed()) {
664
                                // This condition handles those situations in which the server can
665
                                // only give static extent and resolution maps despite we need
666
                                // a specific BBOX and pixel WIDTH and HEIGHT
667
                                try {
668
                                        visualStatus.fileNames = new String[1];
669
                                        drawFixedSize(g, viewPort, cancel, scale);
670
                                        dataset = layerRaster.getDataSource();
671
                                        initializeRasterLayer(null, new IBuffer[][]{{layerRaster.getRender().getLastRenderBuffer()}});
672
                                        getRender().setLastRenderBuffer(layerRaster.getRender().getLastRenderBuffer());
673
                                } catch (LoadLayerException e) {
674
                                        // TODO Auto-generated catch block
675
                                        e.printStackTrace();
676
                                }
677

    
678
                        } else {
679
                                if(mustTileDraw){
680
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), viewPort.getImageWidth(), viewPort.getImageHeight());
681
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
682
                                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
683
                                        visualStatus.fileNames = new String[tiles.getNumTiles()];
684
                                        MultiRasterDataset[][] datasets = new MultiRasterDataset[tiles.getNumRows()][tiles.getNumCols()];
685
                                        IBuffer[][] buf = new IBuffer[tiles.getNumRows()][tiles.getNumCols()];
686
                                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
687
                                                // drawing part
688
                                                try {
689
                                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
690
                                                        boolean painted = drawTile(g, vp, cancel, tileNr, scale);
691
                                                        if(layerRaster != null && painted) {
692
                                                                datasets[(int)(tileNr / tiles.getNumCols())][tileNr % tiles.getNumCols()] = (MultiRasterDataset)layerRaster.getDataSource().newDataset();
693
                                                                buf[(int)(tileNr / tiles.getNumCols())][tileNr % tiles.getNumCols()] = layerRaster.getRender().getLastRenderBuffer();
694
                                                        }
695
                                                } catch (NoninvertibleTransformException e) {
696
                                                        e.printStackTrace();
697
                                                } catch (LoadLayerException e) {
698
                                                        // TODO Auto-generated catch block
699
                                                        e.printStackTrace();
700
                                                }
701
                                        }
702
                                        try {
703
                                                if(datasets != null && datasets[0][0] != null) {
704
                                                        dataset = new CompositeDataset(datasets);
705
                                                        initializeRasterLayer(datasets, buf);
706
                                                }
707
                                        } catch (MosaicNotValidException e) {
708
                                                throw new ReadDriverException("No hay continuidad en el mosaico.", e);
709
                                        } catch (LoadLayerException e) {
710
                                                throw new ReadDriverException("Error inicializando la capa.", e);
711
                                        }
712
                                } else
713
                                        try {
714
                                                visualStatus.fileNames = new String[1];
715
                                                drawTile(g, viewPort, cancel, 0, scale);
716
                                                dataset = layerRaster.getDataSource();
717
                                                getRender().setLastRenderBuffer(layerRaster.getRender().getLastRenderBuffer());
718
                                                initializeRasterLayer(null, new IBuffer[][]{{layerRaster.getRender().getLastRenderBuffer()}});
719
                                        } catch (LoadLayerException e) {
720
                                                // TODO Auto-generated catch block
721
                                                e.printStackTrace();
722
                                        }
723
                        }
724
                }
725
                disableStopped();
726
        }
727

    
728
        /**
729
         * Acciones que se realizan despu?s de asignar la fuente de datos a
730
         * la capa raster.
731
         *
732
         * @throws LoadLayerException
733
         */
734
        private void initializeRasterLayer(MultiRasterDataset[][] datasets, IBuffer[][] buf) throws LoadLayerException {
735
                if(this.filterList != null)
736
                        getRender().setFilterList(filterList);
737
                if(this.transparency != null)
738
                        getRender().setLastTransparency(transparency);
739
                if(this.renderBands != null)
740
                        getRender().setRenderBands(renderBands);
741
                if(datasets != null) {
742
                        String[][] names = new String[datasets.length][datasets[0].length];
743
                        for (int i = 0; i < datasets.length; i++) {
744
                                for (int j = 0; j < datasets[i].length; j++) {
745
                                        if(datasets[i][j] != null)
746
                                                names[i][j] = datasets[i][j].getDataset(0)[0].getFName();
747
                                }
748
                        }
749
                        super.setLoadParams(names);
750
                }
751
                super.init();
752
                if(buf != null) {
753
                        int drawablesBandCount = layerRaster.getDataSource().getBands().getDrawableBandsCount();
754
                        IBuffer buff = null;
755
                        if(dataset instanceof CompositeDataset)
756
                                buff = ((CompositeDataset)dataset).generateBuffer(buf, drawablesBandCount);
757
                        else
758
                                buff = buf[0][0];
759
                        getRender().setLastRenderBuffer(buff);
760
                }
761
        }
762

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

    
768

    
769
                // This is the extent that will be requested
770
                Rectangle2D bBox = getFullExtent();
771
                MyCancellable c = new MyCancellable(cancel);
772

    
773
                try {
774
                        wmsStatus.setExtent( bBox );
775
                        wmsStatus.setFormat( m_Format );
776
                        wmsStatus.setHeight( fixedSize.height );
777
                        wmsStatus.setWidth( fixedSize.width );
778
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
779
                        wmsStatus.setSrs(m_SRS);
780
                        wmsStatus.setStyles(styles);
781
                        wmsStatus.setDimensions(dimensions);
782
                        wmsStatus.setTransparency(wmsTransparency);
783
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
784
                        File f = getDriver().getMap(wmsStatus, c);
785
                        if (f == null)
786
                                return;
787
                        String nameWorldFile = f.getPath() + getExtensionWorldFile();
788
                        com.iver.andami.Utilities.createTemp(nameWorldFile, this.getDataWorldFile(bBox, fixedSize));
789

    
790
                        IStatusRaster status = getStatus();
791
                        if(status!=null && firstLoad){
792
                                try {
793
                                        status.applyStatus(this);
794
                                } catch (NotSupportedExtensionException e) {
795
                                        throw new ReadDriverException("", e);
796
                                } catch (RasterDriverException e) {
797
                                        throw new ReadDriverException("", e);
798
                                } catch (FilterTypeException e) {
799
                                        throw new ReadDriverException("", e);
800
                                }
801
                                firstLoad = false;
802
                        }
803

    
804
                        // And finally, obtain the extent intersecting the view and the BBox
805
                        // to draw to.
806
                        Rectangle2D extent = new Rectangle2D.Double();
807
                        Rectangle2D.intersect(vp.getAdjustedExtent(), bBox, extent);
808

    
809
                        ViewPortData vpData = new ViewPortData(
810
                                vp.getProjection(), new Extent(extent), fixedSize );
811
                        vpData.setMat(vp.getAffineTransform());
812

    
813
                        String filePath = f.getAbsolutePath();
814
                        visualStatus.fileNames[0] = filePath;
815

    
816
                        try {
817
                                rasterProcess(filePath, g, vp, scale, cancel);
818
                                this.updateDrawVersion();
819
                        } catch (FilterTypeException e) {
820
                        }
821
                } catch (ValidationException e) {
822
                        if (!c.isCanceled())
823
                        {
824
                                LoadLayerException exception = new LoadLayerException(getName(),e);
825
                                throw exception;
826
                        }
827
                } catch (IOException e) {
828
                        if (!c.isCanceled())
829
                                if (callCount<MAX_RETRY_TIMES) { // mess code
830
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
831
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
832
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
833
                                        drawFixedSize(g, vp, cancel, scale); // mess code
834
                                } // mess code
835

    
836
                                if (callCount == 1) { // mess code
837
                                        ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
838
                                        type.setLayerName(getName());
839
                                        try {
840
                                                type.setDriverName("WMS Driver");
841
                                        } catch (Exception e1) {
842
                                        }
843
                                        type.setHost(host);
844
                                        throw new ConnectionErrorLayerException(getName(),e);
845
                                } // mess code
846

    
847
                } catch (WMSException e) {
848
                        if (!c.isCanceled()) {
849
                                if (callCount<MAX_RETRY_TIMES) { // mess code
850
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
851
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
852
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
853
                                        drawFixedSize(g, vp, cancel, scale); // mess code
854
                                } // mess code
855
                                if (callCount == 1) { // mess code
856
                                        if (!isPrinting)
857
                                                this.setVisible(false);
858
                                        throw new LoadLayerException(getName(),e);
859

    
860

    
861
                                } // mess code
862
                        }
863
                }
864
                callCount--; // mess code
865
        }
866

    
867
        /**
868
         * Carga y dibuja el raster usando la librer?a
869
         * @param filePath Ruta al fichero en disco
870
         * @param g Graphics2D
871
         * @param vp ViewPort
872
         * @param scale Escala para el draw
873
         * @param cancel Cancelaci?n para el draw
874
         * @throws ReadDriverException
875
         * @throws LoadLayerException
876
         */
877
        private void rasterProcess(String filePath, Graphics2D g, ViewPort vp, double scale, Cancellable cancel) throws ReadDriverException, LoadLayerException, FilterTypeException {
878
                //Cerramos el dataset asociado a la capa si est? abierto.
879
                if(layerRaster != null) {
880
                        layerRaster.setRemoveRasterFlag(true);
881
                        layerRaster.getDataSource().close();
882
                }
883

    
884
                //Cargamos el dataset con el raster de disco.
885
                layerRaster = FLyrRasterSE.createLayer("", filePath, vp.getProjection());
886
                layerRaster.getRender().setBufferFactory(layerRaster.getBufferFactory());
887
                layerRaster.setNoDataValue(getNoDataValue());
888
                layerRaster.setNoDataType(getNoDataType());
889

    
890
                //Obtenemos la tabla de color del raster abierto ya que se le va a sustituir la lista
891
                //de filtros y el de tabla de color no queremos sustituirlo.
892
                RasterFilterList rasterFilterList = layerRaster.getRender().getFilterList();
893
                ColorTableFilter ct = (ColorTableFilter)rasterFilterList.getFilterByBaseClass(ColorTableFilter.class);
894
                Object param = null;
895
                if(ct != null)
896
                        param = ct.getParam("colorTable");
897

    
898
                //En caso de cargar un proyecto con XMLEntity se crean los filtros
899
                if(filterArguments != null) {
900
                        RasterFilterList fl = new RasterFilterList();
901
                        fl.addEnvParam("IStatistics", layerRaster.getDataSource().getStatistics());
902
                        fl.addEnvParam("MultiRasterDataset", layerRaster.getDataSource());
903
                        fl.setInitDataType(layerRaster.getDataType()[0]);
904
                        RasterFilterListManager filterListManager = new RasterFilterListManager(fl);
905
                        filterListManager.createFilterListFromStrings(filterArguments);
906
                        filterArguments = null;
907
                        filterList = fl;
908
                }
909

    
910
                //Como el raster se carga a cada zoom el render se crea nuevamente y la lista de
911
                //filtros siempre estar? vacia a cada visualizaci?n. Para evitarlo tenemos que
912
                //guardar la lista de filtro aplicada en la visualizaci?n anterior.
913
                if(this.filterList != null) {
914
                        //Si ten?a tabla de color le asignamos la original
915
                        if(param != null && param instanceof GridPalette) {
916
                                this.filterList.remove(ColorTableFilter.class);
917
                                RasterFilterListManager filterManager = new RasterFilterListManager(filterList);
918
                                ColorTableListManager ctm = new ColorTableListManager(filterManager);
919
                                ctm.addColorTableFilter((GridPalette)param);
920
                                filterList.move(ColorTableFilter.class, 0);
921
                                filterList.controlTypes();
922
                        }
923
                        layerRaster.getRender().setFilterList(filterList);
924
                }
925
                if(this.transparency != null)
926
                        layerRaster.getRender().setLastTransparency(transparency);
927
                if(this.renderBands != null)
928
                        layerRaster.getRender().setRenderBands(renderBands);
929

    
930
                //Dibujamos
931
                layerRaster.draw(null, g, vp, cancel, scale);
932

    
933
                //La primera vez asignamos la lista de filtros asociada al renderizador. Guardamos una referencia
934
                //en esta clase para que a cada zoom no se pierda.
935
                if (this.filterList == null)
936
                        filterList = layerRaster.getRender().getFilterList();
937
                if (this.transparency == null)
938
                        transparency = layerRaster.getRender().getLastTransparency();
939
                if (this.renderBands == null)
940
                        renderBands = layerRaster.getRender().getRenderBands();
941

    
942
        }
943

    
944
        /*
945
         * (non-Javadoc)
946
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderFilterList()
947
         */
948
        public RasterFilterList getRenderFilterList(){
949
                return (filterList != null) ? filterList : getRender().getFilterList();
950
        }
951

    
952
        /*
953
         * (non-Javadoc)
954
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderFilterList(org.gvsig.raster.grid.filter.RasterFilterList)
955
         */
956
        public void setRenderFilterList(RasterFilterList filterList) {
957
                if (filterList == this.filterList){
958
                        return;
959
                }
960
                this.filterList = filterList;
961
                this.updateDrawVersion();
962
                super.getRender().setFilterList(filterList);
963
        }
964

    
965
        /*
966
         * (non-Javadoc)
967
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderTransparency()
968
         */
969
        public GridTransparency getRenderTransparency() {
970
                return (transparency != null) ? transparency : getRender().getLastTransparency();
971
        }
972

    
973
        /*
974
         * (non-Javadoc)
975
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getRenderBands()
976
         */
977
        public int[] getRenderBands() {
978
                return (renderBands != null) ? renderBands : getRender().getRenderBands();
979
        }
980

    
981
        /*
982
         * (non-Javadoc)
983
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderBands(int[])
984
         */
985
        public void setRenderBands(int[] renderBands) {
986
                //TODO: Comprobar si hay cambios
987
                this.renderBands = renderBands;
988
                this.updateDrawVersion();
989
                getRender().setRenderBands(renderBands);
990
        }
991

    
992
        /**
993
         * This is the method used to draw a tile in a WMS mosaic layer.
994
         * @throws LoadLayerException
995
         * @throws ReadDriverException
996
         * @return true when a tile has been painted
997
         */
998
        private boolean drawTile(Graphics2D g, ViewPort vp, Cancellable cancel, int tile, double scale) throws LoadLayerException, ReadDriverException {
999
                callCount++;
1000
                // Compute the query geometry
1001
                // 1. Check if it is within borders
1002
                Rectangle2D extent = getFullExtent();
1003
                                if ((vp.getAdjustedExtent().getMinX() > extent.getMaxX()) ||
1004
                                                                (vp.getAdjustedExtent().getMinY() > extent.getMaxY()) ||
1005
                                                                (vp.getAdjustedExtent().getMaxX() < extent.getMinX()) ||
1006
                                                                (vp.getAdjustedExtent().getMaxY() < extent.getMinY())) {
1007
                                                return false;
1008
                                }
1009

    
1010
                                // 2. Compute extent to be requested.
1011
                                Rectangle2D bBox = new Rectangle2D.Double();
1012
                                Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
1013

    
1014
                                // 3. Compute size in pixels
1015
                                double scalex = vp.getAffineTransform().getScaleX();
1016
                                double scaley = vp.getAffineTransform().getScaleY();
1017
                                int wImg = (int) Math.ceil(Math.abs(bBox.getWidth() * scalex) + 1);
1018
                                int hImg = (int) Math.ceil(Math.abs(bBox.getHeight() * scaley) + 1);
1019

    
1020
                                Dimension sz = new Dimension(wImg, hImg);
1021

    
1022
                                if ((wImg <= 0) || (hImg <= 0)) {
1023
                                                return false;
1024
                                }
1025
                                MyCancellable c = new MyCancellable(cancel);
1026

    
1027
                try {
1028
                        sz = new Dimension(wImg, hImg);
1029
                        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
1030

    
1031

    
1032
                        wmsStatus.setExtent( bBox );
1033
                        wmsStatus.setFormat(m_Format);
1034
                        wmsStatus.setHeight( hImg );
1035
                        wmsStatus.setWidth( wImg );
1036
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
1037
                        wmsStatus.setSrs(m_SRS);
1038
                        wmsStatus.setStyles(styles);
1039
                        wmsStatus.setDimensions(dimensions);
1040
                        wmsStatus.setTransparency(wmsTransparency);
1041
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
1042

    
1043
                        // begin patch; Avoid to request too small tiles.
1044
                        // This generally occurs when printing
1045

    
1046
                        if (wImg < minTilePrintWidth) {
1047
                                double wScale = (double) minTilePrintWidth / wImg;
1048
                                wmsStatus.setWidth(minTilePrintWidth);
1049
                                Rectangle2D sExtent = wmsStatus.getExtent();
1050
                                Point2D initialPoint = new Point2D.Double(sExtent.getX(), sExtent.getY());
1051
                                sExtent.setRect(sExtent.getX()*wScale, sExtent.getY(), sExtent.getWidth()*wScale, sExtent.getHeight());
1052
                                if (!bBox.contains(initialPoint)) {
1053
                                        sExtent.setRect(sExtent.getX() - initialPoint.getX(), sExtent.getY(), sExtent.getWidth(), sExtent.getHeight());
1054
                                }
1055
                        }
1056

    
1057
                        if (hImg < minTilePrintHeight) {
1058
                                double hScale = (double) minTilePrintHeight / hImg;
1059
                                wmsStatus.setHeight(minTilePrintHeight);
1060
                                Rectangle2D sExtent = wmsStatus.getExtent();
1061
                                Point2D initialPoint = new Point2D.Double(sExtent.getX(), sExtent.getY());
1062
                                sExtent.setRect(sExtent.getX(), sExtent.getY()*hScale, sExtent.getWidth(), sExtent.getHeight()*hScale);
1063
                                if (!bBox.contains(initialPoint)) {
1064
                                        sExtent.setRect(sExtent.getX(), sExtent.getY() - initialPoint.getY(), sExtent.getWidth(), sExtent.getHeight());
1065
                                }
1066
                        }
1067

    
1068
                        // end patch
1069
                        File f = getDriver().getMap(wmsStatus, c);
1070
                        if (f == null)
1071
                                return false;
1072
                        String nameWordFile = f.getPath() + getExtensionWorldFile();
1073
                        com.iver.andami.Utilities.createTemp(nameWordFile, this.getDataWorldFile(bBox, sz));
1074

    
1075
                        ViewPortData vpData = new ViewPortData(
1076
                                vp.getProjection(), new Extent(bBox), sz );
1077
                        vpData.setMat(vp.getAffineTransform());
1078

    
1079
                        String filePath = f.getAbsolutePath();
1080
                        visualStatus.fileNames[tile] = filePath;
1081
                        try {
1082
                                rasterProcess(filePath, g, vp, scale, cancel);
1083
                                this.updateDrawVersion();
1084
                        } catch (FilterTypeException e) {
1085
                        }
1086

    
1087
                } catch (ValidationException e) {
1088
                        if (!c.isCanceled())
1089
                        {
1090
                                LoadLayerException exception = new LoadLayerException(getName(),e);
1091
                                throw exception;
1092
                        }
1093
                } catch (IOException e) {
1094
                        if (!c.isCanceled()){
1095
                                if (callCount<MAX_RETRY_TIMES) { // mess code
1096
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
1097
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
1098
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
1099

    
1100
                                        drawFixedSize(g, vp, cancel, scale); // mess code
1101
                                } // mess code
1102
                        }
1103
                        if (callCount == 1) { // mess code
1104
                                throw new ConnectionErrorLayerException(getName(),e);
1105
                        }//if
1106
                } catch (WMSException e) {
1107
                        if (!c.isCanceled()) {
1108
                                if (callCount<MAX_RETRY_TIMES) { // mess code
1109
                                        Logger.getAnonymousLogger().warning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n"); // mess code
1110
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
1111
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
1112
                                        drawTile(g, vp, cancel, tile, scale);
1113
                                } // mess code
1114
                                if (callCount == 1) { // mess code
1115
//                azabala                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
1116
                                        WMSDriverExceptionType type = new WMSDriverExceptionType();
1117
                                        type.setLayerName(getName());
1118
                                        try {
1119
                                                type.setDriverName("WMS Driver");
1120
                                        } catch (Exception e1) {
1121
                                        }
1122
                                        type.setWcsStatus(this.wmsStatus);
1123
                                        if (!isPrinting)
1124
                                                this.setVisible(false);
1125
                                        throw new LoadLayerException(getName(),e);
1126

    
1127

    
1128
                                } //if
1129
                        }//if
1130
                }//catch
1131
                callCount--;
1132
                return true;
1133
        }
1134

    
1135
        /**
1136
         * Obtiene la extensi?n del fichero de georreferenciaci?n
1137
         * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
1138
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
1139
         */
1140
        private String getExtensionWorldFile(){
1141
                String extWorldFile = ".wld";
1142
                        if(m_Format.equals("image/tif") || m_Format.equals("image/tiff"))
1143
                                extWorldFile = ".tfw";
1144
                        if(m_Format.equals("image/jpeg"))
1145
                                extWorldFile = ".jpgw";
1146
                        return extWorldFile;
1147
        }
1148

    
1149
        /**
1150
         * Calcula el contenido del fichero de georreferenciaci?n de una imagen.
1151
         * @param bBox Tama?o y posici?n de la imagen (en coordenadas de usuario)
1152
         * @param sz Tama?o de la imagen en pixeles.
1153
         * @return el 'WorldFile', como String.
1154
         * @throws IOException
1155
         */
1156
        public String getDataWorldFile(Rectangle2D bBox, Dimension sz) throws IOException {
1157
                StringBuffer data = new StringBuffer();
1158
                        data.append((bBox.getMaxX() - bBox.getMinX())/(sz.getWidth() - 1)+"\n");
1159
                        data.append("0.0\n");
1160
                        data.append("0.0\n");
1161
                        data.append("-"+(bBox.getMaxY() - bBox.getMinY())/(sz.getHeight() - 1)+"\n");
1162
                        data.append(""+bBox.getMinX()+"\n");
1163
                        data.append(""+bBox.getMaxY()+"\n");
1164
                        return data.toString();
1165
        }
1166

    
1167
        /**
1168
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D,
1169
         *                 com.iver.cit.gvsig.fmap.ViewPort,
1170
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
1171
         */
1172
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet properties)
1173
                throws ReadDriverException {
1174
                if (isVisible() && isWithinScale(scale)){
1175
                isPrinting = true;
1176
                if (!mustTilePrint) {
1177
                        draw(null, g, viewPort, cancel,scale);
1178
                } else {
1179
                                        // Para no pedir imagenes demasiado grandes, vamos
1180
                                        // a hacer lo mismo que hace EcwFile: chunkear.
1181
                                        // Llamamos a drawView con cuadraditos m?s peque?os
1182
                                        // del BufferedImage ni caso, cuando se imprime viene con null
1183

    
1184
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
1185
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
1186
                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
1187
                                        // Parte que dibuja
1188
                                        try {
1189
                                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
1190
                                                        drawTile(g, vp, cancel, tileNr, scale);
1191
                                } catch (NoninvertibleTransformException e) {
1192
                                        e.printStackTrace();
1193
                                } catch (LoadLayerException e) {
1194
                                        // TODO Auto-generated catch block
1195
                                        e.printStackTrace();
1196
                                }
1197
                                        }
1198
                }
1199
                        isPrinting = false;
1200
                }
1201
        }
1202

    
1203
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale)
1204
                throws ReadDriverException {
1205
                draw(null, g, viewPort, cancel,scale);
1206
        }
1207

    
1208
        /**
1209
         * Devuelve el FMapWMSDriver.
1210
         *
1211
         * @return FMapWMSDriver
1212
         *
1213
         * @throws IllegalStateException
1214
         * @throws ValidationException
1215
         * @throws UnsupportedVersionLayerException
1216
         * @throws IOException
1217
         */
1218
        public FMapWMSDriver getDriver()
1219
                throws IllegalStateException, ValidationException,
1220
                        UnsupportedVersionLayerException, IOException {
1221
                return FMapWMSDriverFactory.getFMapDriverForURL(host);
1222
        }
1223

    
1224
        /**
1225
         * Devuelve el FMapWMSDriver.
1226
         *
1227
         * @return FMapWMSDriver
1228
         *
1229
         * @throws IllegalStateException
1230
         * @throws ValidationException
1231
         * @throws UnsupportedVersionLayerException
1232
         * @throws IOException
1233
         */
1234
        public void setDriver(FMapWMSDriver drv) {
1235
                //TODO: Comprobar cambio
1236
                wms = drv;
1237
                this.updateDrawVersion();
1238
        }
1239

    
1240
        /**
1241
         * Devuelve el URL.
1242
         *
1243
         * @return URL.
1244
         */
1245
        public URL getHost() {
1246
                return host;
1247
        }
1248

    
1249
        /**
1250
         * Inserta el URL.
1251
         *
1252
         * @param host URL.
1253
         */
1254
        public void setHost(URL host) {
1255
                if (this.host == host){
1256
                        return;
1257
                }
1258
                if (this.host != null && this.fullExtent.equals(host)){
1259
                        return;
1260
                }
1261

    
1262
                this.host = host;
1263
                this.updateDrawVersion();
1264
        }
1265

    
1266
        /**
1267
         * Devuelve la informaci?n de la consulta.
1268
         *
1269
         * @return String.
1270
         */
1271
        public String getInfoLayerQuery() {
1272
                return infoLayerQuery;
1273
        }
1274

    
1275
        /**
1276
         * Inserta la informaci?n de la consulta.
1277
         *
1278
         * @param infoLayerQuery String.
1279
         */
1280
        public void setInfoLayerQuery(String infoLayerQuery) {
1281
                this.infoLayerQuery = infoLayerQuery;
1282
        }
1283

    
1284
        /**
1285
         * Devuelve la consulta.
1286
         *
1287
         * @return String.
1288
         */
1289
        public String getLayerQuery() {
1290
                return layerQuery;
1291
        }
1292

    
1293
        /**
1294
         * Inserta la consulta.
1295
         *
1296
         * @param layerQuery consulta.
1297
         */
1298
        public void setLayerQuery(String layerQuery) {
1299
                if (this.layerQuery == layerQuery){
1300
                        return;
1301
                }
1302
                if (this.layerQuery != null && this.layerQuery.equals(layerQuery)){
1303
                        return;
1304
                }
1305

    
1306
                this.layerQuery = layerQuery;
1307
                this.updateDrawVersion();
1308
        }
1309

    
1310
        /**
1311
         * Devuelve el formato.
1312
         *
1313
         * @return Formato.
1314
         */
1315
        public String getFormat() {
1316
                return m_Format;
1317
        }
1318

    
1319
        /**
1320
         * Inserta el formato.
1321
         *
1322
         * @param format Formato.
1323
         */
1324
        public void setFormat(String format) {
1325
                if (this.m_Format == format){
1326
                        return;
1327
                }
1328
                if (this.m_Format != null && this.m_Format.equals(format)){
1329
                        return;
1330
                }
1331
                m_Format = format;
1332
                this.updateDrawVersion();
1333
        }
1334

    
1335
        /**
1336
         * Devuelve el SRS.
1337
         *
1338
         * @return SRS.
1339
         */
1340
        public String getSRS() {
1341
                return m_SRS;
1342
        }
1343

    
1344
        /**
1345
         * Inserta el SRS.
1346
         *
1347
         * @param m_srs SRS.
1348
         */
1349
        public void setSRS(String m_srs) {
1350
                if (m_SRS == m_srs){
1351
                        return;
1352
                }
1353
                if (m_SRS != null && m_SRS.equals(m_srs)){
1354
                        return;
1355
                }
1356
                m_SRS = m_srs;
1357
                this.updateDrawVersion();
1358
                setProjection(CRSFactory.getCRS(getSRS()));
1359
        }
1360

    
1361
        /**
1362
         * Inserta la extensi?n total de la capa.
1363
         *
1364
         * @param fullExtent Rect?ngulo.
1365
         */
1366
        public void setFullExtent(Rectangle2D fullExtent) {
1367
                if (this.fullExtent == fullExtent){
1368
                        return;
1369
                }
1370
                if (this.fullExtent != null && this.fullExtent.equals(fullExtent)){
1371
                        return;
1372
                }
1373

    
1374
                this.fullExtent = fullExtent;
1375
                this.updateDrawVersion();
1376
        }
1377

    
1378
        public HashMap getProperties() {
1379
                HashMap info = new HashMap();
1380
                                String[] layerNames = getLayerQuery().split(",");
1381
                                Vector layers = new Vector(layerNames.length);
1382
                                try {
1383
                                                if(getDriver().connect(null)){
1384
                                                                for (int i = 0; i < layerNames.length; i++) {
1385
                                                                                layers.add(i, getDriver().getLayer(layerNames[i]));
1386
                                                                }
1387
                                                                info.put("name", getName());
1388
                                                                info.put("selectedLayers", layers);
1389
                                                                info.put("host", getHost());
1390
                                                                info.put("srs", getSRS());
1391
                                                                info.put("format", getFormat());
1392
                                                                info.put("wmsTransparency", new Boolean(wmsTransparency));
1393
                                                                info.put("styles", styles);
1394
                                                                info.put("dimensions", dimensions);
1395
                                                                info.put("fixedSize", fixedSize);
1396
                                                                return info;
1397
                                                }
1398
                                } catch (Exception e) {
1399
                                                e.printStackTrace();
1400
                                }
1401
                                return null;
1402
        }
1403

    
1404
        public double getMaxX() {
1405
                return visualStatus.maxX;
1406
        }
1407

    
1408
        public double getMaxY() {
1409
                return visualStatus.maxY;
1410
        }
1411

    
1412
        public double getMinX() {
1413
                return visualStatus.minX;
1414
        }
1415

    
1416
        public double getMinY() {
1417
                return visualStatus.minY;
1418
        }
1419

    
1420
                /**
1421
                 * @return Returns the wmsTransparency.
1422
                 */
1423
                public boolean isWmsTransparent() {
1424
                                return wmsTransparency;
1425
                }
1426

    
1427
                /**
1428
                 * @param wmsTransparency The wmsTransparency to set.
1429
                 */
1430
                public void setWmsTransparency(boolean wmsTransparency) {
1431
                        if (this.wmsTransparency == wmsTransparency){
1432
                                return;
1433
                        }
1434
                        this.wmsTransparency = wmsTransparency;
1435
                        this.updateDrawVersion();
1436
                }
1437

    
1438
                 /**
1439
                 * @param styles
1440
                 */
1441
                public void setStyles(Vector styles) {
1442
                    if (this.styles == styles){
1443
                            return;
1444
                    }
1445
                    if (this.styles != null && styles != null ){
1446
                            if (this.styles.containsAll(styles) && this.styles.size() ==styles.size()){
1447
                                    return;
1448
                            }
1449
                    }
1450
                    this.styles = styles;
1451
                    this.updateDrawVersion();
1452
                }
1453

    
1454
                /**
1455
                 * Sets the dimension vector that is a list of key-value pairs containing
1456
                 * the name of the dimension and the value for it
1457
                 * @param dimensions
1458
                 */
1459
                public void setDimensions(Vector dimensions) {
1460
                        if (this.dimensions == dimensions){
1461
                                return;
1462
                        }
1463
                        if (this.dimensions != null && dimensions != null ){
1464
                                if (this.dimensions.containsAll(dimensions) && this.dimensions.size() ==dimensions.size()){
1465
                                        return;
1466
                                }
1467
                        }
1468
                        this.dimensions = dimensions;
1469
                        this.updateDrawVersion();
1470
                }
1471

    
1472
                /**
1473
                 * Sets the set of URLs that should be accessed for each operation performed
1474
                 * to the server.
1475
                 *
1476
                 * @param onlineResources
1477
                 */
1478
        public void setOnlineResources(Hashtable onlineResources) {
1479
            if (this.onlineResources == onlineResources){
1480
                    return;
1481
            }
1482
            if (this.onlineResources != null && this.onlineResources.equals(onlineResources)){
1483
                    return;
1484
            }
1485

    
1486
                this.onlineResources = onlineResources;
1487
                this.updateDrawVersion();
1488
        }
1489

    
1490
                /**
1491
                 * Gets the URL that should be accessed for an operation performed
1492
                 * to the server.
1493
                 *
1494
                 * @param onlineResources
1495
                 */
1496
        public String getOnlineResource(String operation) {
1497
                return ((String) onlineResources.get(operation));
1498
        }
1499

    
1500
        /**
1501
         * When a server is not fully featured and it only can serve constant map
1502
         * sizes this value must be set. It expresses the size in pixels (width, height)
1503
         * that the map will be requested.
1504
         * @param Dimension sz
1505
         */
1506
        public void setFixedSize(Dimension sz) {
1507
                if (this.fixedSize == sz){
1508
                        return;
1509
                }
1510
                if (this.fixedSize != null && this.fixedSize.equals(sz)){
1511
                        return;
1512
                }
1513
                fixedSize = sz;
1514
                this.updateDrawVersion();
1515
        }
1516

    
1517
        /**
1518
         * Tells whether if this layer must deal with the server with the constant-size
1519
         * limitations or not.
1520
         * @return boolean.
1521
         */
1522
        private boolean isSizeFixed() {
1523
                return fixedSize != null && fixedSize.getWidth() > 0 && fixedSize.getHeight() > 0;
1524
        }
1525

    
1526
        /**
1527
         * If it is true, this layer accepts GetFeatureInfo operations. This WMS operations
1528
         * maps to FMap's infoByPoint(p) operation.
1529
         * @param b
1530
         */
1531
        public void setQueryable(boolean b) {
1532
                queryable = b;
1533
        }
1534

    
1535
        /**
1536
         * Creates the part of a OGC's MapContext document that would describe this
1537
         * layer(s).
1538
         * @param version, The desired version of the resulting document. (1.1.0)
1539
         * @return String containing the xml.
1540
         * @throws UnsupportedVersionLayerException
1541
         */
1542
        public String toMapContext(String mapContextVersion) {
1543
                XmlBuilder xml = new XmlBuilder();
1544
                FMapWMSDriver drv;
1545
                try {
1546
                        drv = getDriver();
1547
                } catch (Exception e) {
1548
                        return xml.toString();
1549
                }
1550
                String[] layerNames = getLayerQuery().split(",");
1551
                String[] styleNames = (String[]) styles.toArray(new String[0]);
1552
                for (int i = 0; i < layerNames.length; i++) {
1553
                        WMSLayerNode layer = drv.getLayer(layerNames[i]);
1554
                        HashMap xmlAttrs = new HashMap();
1555

    
1556
                        // <Layer>
1557
                        xmlAttrs.put(WebMapContextTags.HIDDEN, !isVisible()+"");
1558
                        xmlAttrs.put(WebMapContextTags.QUERYABLE, queryable+"");
1559
                        xml.openTag(WebMapContextTags.LAYER, xmlAttrs);
1560
                        xmlAttrs.clear();
1561
                        if (mapContextVersion.equals("1.1.0") || mapContextVersion.equals("1.0.0")) {
1562
                                // <Server>
1563
                                xmlAttrs.put(WebMapContextTags.SERVICE, WebMapContextTags.WMS);
1564
                                xmlAttrs.put(WebMapContextTags.VERSION, drv.getVersion());
1565
                                xmlAttrs.put(WebMapContextTags.SERVER_TITLE, drv.getServiceTitle());
1566
                                xml.openTag(WebMapContextTags.SERVER, xmlAttrs);
1567
                                xmlAttrs.clear();
1568

    
1569
                                        // <OnlineResource>
1570
                                        xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1571
                                        xmlAttrs.put(WebMapContextTags.XLINK_HREF, getHost().toString());
1572
                                        xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1573
                                        xmlAttrs.clear();
1574
                                        // </OnlineResource>
1575

    
1576
                                xml.closeTag();
1577
                                // </Server>
1578

    
1579
                                // <Name>
1580
                                xml.writeTag(WebMapContextTags.NAME, layer.getName().trim());
1581
                                // </Name>
1582

    
1583
                                // <Title>
1584
                                xml.writeTag(WebMapContextTags.TITLE, layer.getTitle().trim());
1585
                                //?xml.writeTag(WebMapContextTags.TITLE, getName().trim());
1586
                                // </Title>
1587

    
1588
                                // <Abstract>
1589
                                if (layer.getAbstract() != null)
1590
                                        xml.writeTag(WebMapContextTags.ABSTRACT, layer.getAbstract());
1591
                                // </Abstract>
1592

    
1593
                                // <SRS> (a list of available SRS for the enclosing layer)
1594
                                String[] strings = (String[]) layer.getAllSrs().toArray(new String[0]);
1595
                                String mySRS = strings[0];
1596
                                for (int j = 1; j < strings.length; j++) {
1597
                                        mySRS += ","+strings[j];
1598
                                }
1599
                                xml.writeTag(WebMapContextTags.SRS, mySRS);
1600
                                // </SRS>
1601

    
1602
                                // <FormatList>
1603
                                xml.openTag(WebMapContextTags.FORMAT_LIST);
1604
                                        strings = (String[]) drv.getFormats().toArray(new String[0]);
1605
                                        for (int j = 0; j < strings.length; j++) {
1606
                                                                                // <Format>
1607
                                                String str = strings[j].trim();
1608
                                                if (str.equals(getFormat()))
1609
                                                        xml.writeTag(WebMapContextTags.FORMAT, str, WebMapContextTags.CURRENT, "1");
1610
                                                else
1611
                                                        xml.writeTag(WebMapContextTags.FORMAT, str);
1612
                                                                                // </Format>
1613
                                        }
1614
                                xml.closeTag();
1615
                                // </FormatList>
1616

    
1617
                                // <StyleList>
1618
                                xml.openTag(WebMapContextTags.STYLE_LIST);
1619

    
1620
                                        if (layer.getStyles().size()>0) {
1621
                                                for (int j = 0; j < layer.getStyles().size(); j++) {
1622
                                                        // <Style>
1623
                                                        FMapWMSStyle st = (FMapWMSStyle) layer.getStyles().get(j);
1624
                                                        if (st.name.equals(styleNames[i]))
1625
                                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1626
                                                        xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1627
                                                        xmlAttrs.clear();
1628

    
1629
                                                                // <Name>
1630
                                                                xml.writeTag(WebMapContextTags.NAME, st.name);
1631
                                                                // </Name>
1632

    
1633
                                                                // <Title>
1634
                                                                xml.writeTag(WebMapContextTags.TITLE, st.title);
1635
                                                                // </Title>
1636

    
1637
                                                                // <LegendURL width="180" format="image/gif" height="50">
1638
                                                                        // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1639
                                                                        // </OnlineResource>
1640
                                                                // </LegendURL>
1641
                                                        xml.closeTag();
1642
                                                        // </Style>
1643

    
1644
                                                }
1645

    
1646
                                        } else {
1647
                                                // Create fake style (for compatibility issues)
1648
                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1649
                                                // <Style>
1650
                                                xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1651
                                                        xmlAttrs.clear();
1652
                                                        // <Name>
1653
                                                        xml.writeTag(WebMapContextTags.NAME, "default");
1654
                                                        // </Name>
1655

    
1656
                                                        // <Title>
1657
                                                        xml.writeTag(WebMapContextTags.TITLE, "default");
1658
                                                        // </Title>
1659

    
1660
//                                                        // <LegendURL width="180" format="image/gif" height="50">
1661
//                                                        xmlAttrs.put(WebMapContextTags.WIDTH, "0");
1662
//                                                        xmlAttrs.put(WebMapContextTags.HEIGHT, "0");
1663
//                                                        xmlAttrs.put(WebMapContextTags.FORMAT.toLowerCase(), "image/gif");
1664
//                                                        xml.openTag(WebMapContextTags.LEGEND_URL, xmlAttrs);
1665
//                                                        xmlAttrs.clear();
1666
//                                                                // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1667
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1668
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_HREF, "http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif");
1669
//                                                                xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1670
//                                                                // </OnlineResource>
1671
//                                                    // </LegendURL>
1672
//                                                        xml.closeTag();
1673
                                                // </Style>
1674
                                                xml.closeTag();
1675
                                        }
1676
                                // </StyleList>
1677
                                xml.closeTag();
1678
                                if (mapContextVersion.compareTo("1.0.0") > 0) {
1679
                                // <DimensionList>
1680
                                        xml.openTag(WebMapContextTags.DIMENSION_LIST);
1681
                                        // <Dimension>
1682
                                        // </Dimension>
1683
                                        xml.closeTag();
1684
                                // </DimensionList>
1685
                                }
1686
                        } else {
1687
                                xml.writeTag("ERROR", PluginServices.getText(this, "unsupported_map_context_version"));
1688
                        }
1689
                        // </Layer>
1690
                        xml.closeTag();
1691
                }
1692
                return xml.getXML();
1693
        }
1694

    
1695
        public ImageIcon getTocImageIcon() {
1696
                return new ImageIcon(getClass().getResource("image/icoLayer.png"));
1697
        }
1698

    
1699
        /*
1700
         *  (non-Javadoc)
1701
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1702
         */
1703
        public int[] getTileSize() {
1704
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1705
                return size;
1706
        }
1707

    
1708
        /*
1709
         *  (non-Javadoc)
1710
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1711
         */
1712
        public boolean isTiled() {
1713
                return mustTileDraw;
1714
        }
1715

    
1716
        public Image getImageLegend() {
1717
                try {
1718
                        if (wms == null)
1719
                                wms = getDriver();
1720
                        if (wms.hasLegendGraphic()) {
1721
                                wmsStatus.setOnlineResource((String) onlineResources
1722
                                                .get("GetLegendGraphic"));
1723
                                String path = getPathImage();// File legend =
1724
                                                                                                // getDriver().getLegendGraphic(wmsStatus,
1725
                                                                                                // layerQuery, null);
1726
                                Image img = null;
1727
                                if ((path != null) && (path.length() > 0))
1728
                                        img = new ImageIcon(path).getImage();
1729
                                return img;
1730
                        }
1731
                } catch (Exception e) {
1732
                }
1733
                return null;
1734
        }
1735

    
1736
        public String getPathImage() {
1737
                try {
1738
                        File legend = getDriver().getLegendGraphic(wmsStatus, layerQuery, null);
1739
                        return legend.getAbsolutePath();
1740
                }catch(Exception e){
1741
                        e.printStackTrace();
1742
                        return null;
1743
                }
1744
        }
1745

    
1746
        /* (non-Javadoc)
1747
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#newComposedLayer()
1748
         */
1749
        public ComposedLayer newComposedLayer() {
1750
                Preferences prefs = Preferences.userRoot().node("gvsig.wms");
1751

    
1752
                /*
1753
                 * from java.util.prefs import Preferences
1754
                 * prefs = Preferences.userRoot().node("gvsig.wms")
1755
                 * prefs.put("useComposedLayer","true")
1756
                 */
1757

    
1758
                String str = prefs.get("useComposedLayer","false");
1759
                Boolean useComposedLayer = Boolean.TRUE; // por defecto ya se usan
1760
                try {
1761
                        useComposedLayer = Boolean.valueOf(str);
1762
                } catch (Exception e) {
1763

    
1764
                }
1765
                if (useComposedLayer.booleanValue()) {
1766
                        return new ComposedLayerWMS();
1767
                } else {
1768
                        return null;
1769
                }
1770
        }
1771

    
1772
        /**
1773
         * @param styles
1774
         */
1775
        public Vector getStyles() {
1776
                return this.styles;
1777
        }
1778

    
1779

    
1780
        /*
1781
         * Checks if can make a single petition for the two layers to the server
1782
         * @see com.iver.cit.gvsig.fmap.layers.ComposedLayerWMS#canAdd(com.iver.cit.gvsig.fmap.layers.FLayer)
1783
         */
1784
        boolean isComposedLayerCompatible(FLayer layer) {
1785
                FLyrWMS aLayer;
1786

    
1787
                if (!(layer instanceof FLyrWMS)) {
1788
                        return false;
1789
                }
1790
                aLayer = (FLyrWMS)layer;
1791
                if (!this.getHost().equals(aLayer.getHost())) {
1792
                        return false;
1793
                }
1794
                if (!this.getFormat().equals(aLayer.getFormat())) {
1795
                        return false;
1796
                }
1797
                if (!this.getSRS().equals(aLayer.getSRS())) {
1798
                        return false;
1799
                }
1800
                if (this.getInfoLayerQuery() != null) {
1801
                        if (!this.getInfoLayerQuery().equals(aLayer.getInfoLayerQuery())) {
1802
                                return false;
1803
                        }
1804
                }else if (aLayer.getInfoLayerQuery() != null) {
1805
                        return false;
1806
                }
1807

    
1808

    
1809
                // isFixedSize es privado
1810
                if ((this.fixedSize != null) &&
1811
                                (aLayer.fixedSize!= null)) {
1812
                        if (this.fixedSize.equals(aLayer.fixedSize)) {
1813
                                return false;
1814
                        }
1815
                } else if ((this.fixedSize != null) != (aLayer.fixedSize != null)) {
1816
                        return false;
1817
                }
1818

    
1819
                // time elevation (dimensions)
1820
                if ((this.dimensions != null) &&
1821
                                (aLayer.dimensions != null)) {
1822
                        if (this.dimensions.size() != aLayer.dimensions.size()) {
1823
                                return false;
1824
                        } else {
1825
                                Iterator iter = this.dimensions.iterator();
1826
                                while (iter.hasNext()) {
1827
                                        if (!aLayer.dimensions.contains(iter.next())) {
1828
                                                return false;
1829
                                        }
1830
                                }
1831
                        }
1832

    
1833
                } else if ((this.dimensions != null) != (aLayer.dimensions != null)) {
1834
                        return false;
1835
                }
1836

    
1837
                return true;
1838
        }
1839

    
1840
        /*
1841
         * (non-Javadoc)
1842
         * @see org.gvsig.fmap.raster.layers.FLyrRasterSE#isActionEnabled(int)
1843
         */
1844
        public boolean isActionEnabled(int action) {
1845
                switch (action) {
1846
                        case IRasterLayerActions.ZOOM_PIXEL_RESOLUTION:
1847
                        case IRasterLayerActions.FLYRASTER_BAR_TOOLS:
1848
                        case IRasterLayerActions.BANDS_FILE_LIST:
1849
                        case IRasterLayerActions.COLOR_TABLE:
1850
                        case IRasterLayerActions.GEOLOCATION:
1851
                        case IRasterLayerActions.PANSHARPENING:
1852
                                return false;
1853
                }
1854

    
1855
                return super.isActionEnabled(action);
1856
        }
1857

    
1858
        /*
1859
         * (non-Javadoc)
1860
         * @see org.gvsig.fmap.raster.layers.FLyrRasterSE#getLegend()
1861
         */
1862
        public ILegend getLegend() {
1863
                return null;
1864
        }
1865

    
1866
        /*
1867
         * (non-Javadoc)
1868
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
1869
         */
1870
        public int[] getDataType(){
1871
                try {
1872
                        return dataset.getDataType();
1873
                } catch (NullPointerException e) {
1874
                        if(layerRaster != null)
1875
                                return layerRaster.getDataType();
1876
                        else
1877
                                return new int[]{IBuffer.TYPE_UNDEFINED};
1878
                }
1879
        }
1880

    
1881
        /*
1882
         * (non-Javadoc)
1883
         * @see org.gvsig.fmap.raster.layers.FLyrRasterSE#overviewsSupport()
1884
         */
1885
        public boolean overviewsSupport() {
1886
                return false;
1887
        }
1888
}