Statistics
| Revision:

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

History | View | Annotate | Download (60.3 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.ref.WeakReference;
57
import java.lang.reflect.Constructor;
58
import java.lang.reflect.InvocationTargetException;
59
import java.net.MalformedURLException;
60
import java.net.URL;
61
import java.util.ArrayList;
62
import java.util.HashMap;
63
import java.util.Hashtable;
64
import java.util.Iterator;
65
import java.util.List;
66
import java.util.Map;
67
import java.util.Vector;
68
import java.util.logging.Logger;
69
import java.util.prefs.Preferences;
70

    
71
import javax.print.attribute.PrintRequestAttributeSet;
72
import javax.swing.ImageIcon;
73
import javax.swing.JOptionPane;
74

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

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

    
127

    
128

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

    
166
        public URL                                                         host;
167
        public String                                                 m_Format;
168

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

    
192
        private List                                                disableUpdateDrawVersion;
193

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

    
209
        }
210

    
211
        public FLyrWMS(){
212
                super();
213
                this.updateDrawVersion();
214
        }
215

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

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

    
245
                        WMSLayerNode wmsNode = drv.getLayer(sLayer);
246

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

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

    
279

    
280
                this.setFullExtent(fullExtent);
281
                this.setFormat(sFormat);
282
                this.setLayerQuery(sLayer);
283
                this.setInfoLayerQuery("");
284
                this.setSRS(sSRS);
285
                this.setName(sLayer);
286
                this.setOnlineResources(drv.getOnlineResources());
287
                load();
288
        }
289

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

    
309
                        return (String)formats.get(0);
310
        }
311

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

    
330
        }
331

    
332

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

    
343
                // Full extent
344
                xml.putProperty("fullExtent", StringUtilities.rect2String(fullExtent));
345

    
346
                // Host
347
                xml.putProperty("host", host.toExternalForm());
348

    
349
                // Part of the query that is not the host, or the
350
                // layer names, or other not listed bellow
351
                xml.putProperty("infoLayerQuery", infoLayerQuery);
352

    
353
                // Part of the query containing the layer names
354
                xml.putProperty("layerQuery", layerQuery);
355

    
356
                // Format
357
                xml.putProperty("format", m_Format);
358

    
359
                // SRS
360
                xml.putProperty("srs", m_SRS);
361
                if (status!=null)
362
                        status.getXMLEntity(xml, true, this);
363
                else{
364
                        status = new StatusLayerRaster();
365
                        status.getXMLEntity(xml, true, this);
366
                }
367

    
368
                                // Transparency
369
                                xml.putProperty("wms_transparency", wmsTransparency);
370

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

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

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

    
409
                                // Queryable
410
                                xml.putProperty("queryable", queryable);
411

    
412
                                // fixedSize
413
                                if (isSizeFixed()) {
414
                                        xml.putProperty("fixedSize", true);
415
                                        xml.putProperty("fixedWidth", fixedSize.width);
416
                                        xml.putProperty("fixedHeight", fixedSize.height);
417
                                }
418
                                return xml;
419
        }
420

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

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

    
442
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
443
                layerQuery = xml.getStringProperty("layerQuery");
444
                m_Format = xml.getStringProperty("format");
445
                m_SRS = xml.getStringProperty("srs");
446
        }
447

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

    
463
                // Host
464
                try {
465
                        host = new URL(xml.getStringProperty("host"));
466
                } catch (MalformedURLException e) {
467
                        throw new XMLException(e);
468
                }
469

    
470
                // Part of the query that is not the host, or the
471
                // layer names, or other not listed bellow
472
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
473

    
474
                // Part of the query containing the layer names
475
                layerQuery = xml.getStringProperty("layerQuery");
476

    
477
                // Format
478
                m_Format = xml.getStringProperty("format");
479

    
480
                // SRS
481
                m_SRS = xml.getStringProperty("srs");
482

    
483
                String claseStr = StatusLayerRaster.defaultClass;
484
                if (xml.contains("raster.class")) {
485
                        claseStr = xml.getStringProperty("raster.class");
486
                }
487

    
488
                // Transparency
489
                                if (xml.contains("wms_transparency"))
490
                                                wmsTransparency = xml.getBooleanProperty("wms_transparency");
491

    
492
                                // Styles
493
                                if (xml.contains("styles")){
494
                                                styles = new Vector();
495
                                                String[] stl = xml.getStringProperty("styles").split(",");
496

    
497
                                                for (int i = 0; i < stl.length; i++) {
498
                                                        if (stl[i].equals(" "))
499
                                                                stl[i]="";
500
                                                                styles.add(stl[i]);
501
                                                }
502
                                }
503

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

    
512
                                                                dimensions.add(dims[i]);
513
                                                }
514
                                }
515

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

    
526
                                // Queryable
527
                                queryable = true; // let's assume that the layer is queryable by default
528
                                if (xml.contains("queryable"))
529
                                        queryable = xml.getBooleanProperty("queryable");
530

    
531
                                // fixedSize
532
                                if (xml.contains("fixedSize")) {
533
                                        fixedSize = new Dimension(xml.getIntProperty("fixedWidth"),
534
                                                                                                                                xml.getIntProperty("fixedHeight"));
535
                                }
536

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

    
568
        /**
569
         * @throws ReadDriverException
570
         * @throws LoadLayerException
571
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(com.iver.cit.gvsig.fmap.operations.QueriedPoint)
572
         */
573
        public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancellable) throws ReadDriverException {
574
                XMLItem[] item = new XMLItem[1];
575
                try {
576
                        if (queryable)         {
577
                                //TODO
578
                                // check if there are layers which are not queryable
579
                                ViewPort viewPort = getMapContext().getViewPort();
580

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

    
587
                                int col = (int) p.getX() / maxTilePrintWidth;
588
                                int row = (int) p.getY() / maxTilePrintHeight;
589
                                int tileIndex = (row*nCols) + col;
590

    
591
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileIndex);
592
                                wmsStatus.setExtent(vp.getAdjustedExtent());
593
                                wmsStatus.setHeight(vp.getImageHeight());
594
                                wmsStatus.setWidth(vp.getImageWidth());
595
                                wmsStatus.setOnlineResource((String) onlineResources.get("GetFeatureInfo"));
596

    
597

    
598
                                wmsStatus.setFormat( m_Format );
599
                                wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
600
                                wmsStatus.setSrs(m_SRS);
601
                                wmsStatus.setStyles(styles);
602
                                wmsStatus.setDimensions(dimensions);
603
                                wmsStatus.setTransparency(wmsTransparency);
604
                                wmsStatus.setSrs(m_SRS);
605
                                MyCancellable c = new MyCancellable(cancellable);
606
                                try {
607
                                        item[0] = new StringXMLItem(new String(getDriver()
608
                                                        .getFeatureInfo(wmsStatus, (int) tiledPoint.getX(), (int) tiledPoint.getY(), Integer.MAX_VALUE, c)),this);
609
                                } catch (UnsupportedVersionLayerException e) {
610
                                        throw new ReadDriverException(FMapWMSDriver.class.getName()+"::"+getName()+" - UnsupportedVersionLayerException", e);
611
                                } catch (IllegalStateException e) {
612
                                        throw new ReadDriverException(FMapWMSDriver.class.getName()+"::"+getName()+" - IllegalStateException", e);
613
                                }
614
                                return item;
615
                        }
616
                        else
617
                        {
618
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),this.getName() + " " +
619
                                                PluginServices.getText(this,"layer_not_queryable"));
620
                                item[0] =  new StringXMLItem("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><info></info>",this);
621
                                return item;
622
                                //return null;
623
                        }
624
                } catch (WMSException  e) {
625
                        item[0] = new StringXMLItem("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><exception>" +
626
                        e.getMessage() + "</exception>", this);
627
                        return item;
628
                } catch (ValidationException e) {
629
                        throw new ReadDriverException(FMapWMSDriver.class.getName()+"::"+getName()+" - ValidationException", e);
630
                } catch (IOException e) {
631
                        throw new ReadDriverException(FMapWMSDriver.class.getName()+"::"+getName()+" - IOException", e);
632
                } catch (NoninvertibleTransformException e) {
633
                        NotificationManager.addError("NotinvertibleTransform", e);
634
                }
635
                return null;
636
        }
637

    
638
        /*
639
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent()
640
         */
641
        public Rectangle2D getFullExtent() {
642
                return fullExtent;
643
        }
644

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

    
666

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

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

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

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

    
776

    
777
                // This is the extent that will be requested
778
                Rectangle2D bBox = getFullExtent();
779
                MyCancellable c = new MyCancellable(cancel);
780

    
781
                try {
782
                        wmsStatus.setExtent( bBox );
783
                        wmsStatus.setFormat( m_Format );
784
                        wmsStatus.setHeight( fixedSize.height );
785
                        wmsStatus.setWidth( fixedSize.width );
786
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
787
                        wmsStatus.setSrs(m_SRS);
788
                        wmsStatus.setStyles(styles);
789
                        wmsStatus.setDimensions(dimensions);
790
                        wmsStatus.setTransparency(wmsTransparency);
791
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
792
                        File f = getDriver().getMap(wmsStatus, c);
793
                        if (f == null)
794
                                return;
795
                        String nameWorldFile = f.getPath() + getExtensionWorldFile();
796
                        com.iver.andami.Utilities.createTemp(nameWorldFile, this.getDataWorldFile(bBox, fixedSize));
797

    
798
                        IStatusRaster status = getStatus();
799
                        if(status!=null && firstLoad){
800
                                try {
801
                                        status.applyStatus(this);
802
                                } catch (NotSupportedExtensionException e) {
803
                                        throw new ReadDriverException("", e);
804
                                } catch (RasterDriverException e) {
805
                                        throw new ReadDriverException("", e);
806
                                } catch (FilterTypeException e) {
807
                                        throw new ReadDriverException("", e);
808
                                }
809
                                firstLoad = false;
810
                        }
811

    
812
                        // And finally, obtain the extent intersecting the view and the BBox
813
                        // to draw to.
814
                        Rectangle2D extent = new Rectangle2D.Double();
815
                        Rectangle2D.intersect(vp.getAdjustedExtent(), bBox, extent);
816

    
817
                        ViewPortData vpData = new ViewPortData(
818
                                vp.getProjection(), new Extent(extent), fixedSize );
819
                        vpData.setMat(vp.getAffineTransform());
820

    
821
                        String filePath = f.getAbsolutePath();
822
                        visualStatus.fileNames[0] = filePath;
823

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

    
844
                                if (callCount == 1) { // mess code
845
                                        ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
846
                                        type.setLayerName(getName());
847
                                        try {
848
                                                type.setDriverName("WMS Driver");
849
                                        } catch (Exception e1) {
850
                                        }
851
                                        type.setHost(host);
852
                                        throw new ConnectionErrorLayerException(getName(),e);
853
                                } // mess code
854

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

    
868

    
869
                                } // mess code
870
                        }
871
                }
872
                callCount--; // mess code
873
        }
874

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

    
892
                //Cargamos el dataset con el raster de disco.
893
                layerRaster = FLyrRasterSE.createLayer("", filePath, vp.getProjection());
894
                layerRaster.getRender().setBufferFactory(layerRaster.getBufferFactory());
895
                layerRaster.setNoDataValue(getNoDataValue());
896
                layerRaster.setNoDataType(getNoDataType());
897

    
898
                //Obtenemos la tabla de color del raster abierto ya que se le va a sustituir la lista
899
                //de filtros y el de tabla de color no queremos sustituirlo.
900
                RasterFilterList rasterFilterList = layerRaster.getRender().getFilterList();
901
                ColorTableFilter ct = (ColorTableFilter)rasterFilterList.getFilterByBaseClass(ColorTableFilter.class);
902
                Object param = null;
903
                if(ct != null)
904
                        param = ct.getParam("colorTable");
905

    
906
                //En caso de cargar un proyecto con XMLEntity se crean los filtros
907
                if(filterArguments != null) {
908
                        RasterFilterList fl = new RasterFilterList();
909
                        fl.addEnvParam("IStatistics", layerRaster.getDataSource().getStatistics());
910
                        fl.addEnvParam("MultiRasterDataset", layerRaster.getDataSource());
911
                        fl.setInitDataType(layerRaster.getDataType()[0]);
912
                        RasterFilterListManager filterListManager = new RasterFilterListManager(fl);
913
                        filterListManager.createFilterListFromStrings(filterArguments);
914
                        filterArguments = null;
915
                        filterList = fl;
916
                }
917

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

    
940
                //Dibujamos
941
                disableUpdateDrawVersion();
942
                layerRaster.draw(null, g, vp, cancel, scale);
943
                enableUpdateDrawVersion();
944

    
945
                //La primera vez asignamos la lista de filtros asociada al renderizador. Guardamos una referencia
946
                //en esta clase para que a cada zoom no se pierda.
947
                if (this.filterList == null)
948
                        filterList = layerRaster.getRender().getFilterList();
949
                if (this.transparency == null)
950
                        transparency = layerRaster.getRender().getLastTransparency();
951
                if (this.renderBands == null)
952
                        renderBands = layerRaster.getRender().getRenderBands();
953

    
954
        }
955

    
956
        /*
957
         * (non-Javadoc)
958
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderFilterList()
959
         */
960
        public RasterFilterList getRenderFilterList(){
961
                return (filterList != null) ? filterList : getRender().getFilterList();
962
        }
963

    
964
        /*
965
         * (non-Javadoc)
966
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderFilterList(org.gvsig.raster.grid.filter.RasterFilterList)
967
         */
968
        public void setRenderFilterList(RasterFilterList filterList) {
969
                if (filterList == this.filterList){
970
                        return;
971
                }
972
                this.filterList = filterList;
973
                this.updateDrawVersion();
974
                super.getRender().setFilterList(filterList);
975
        }
976

    
977
        /*
978
         * (non-Javadoc)
979
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderTransparency()
980
         */
981
        public GridTransparency getRenderTransparency() {
982
                return (transparency != null) ? transparency : getRender().getLastTransparency();
983
        }
984

    
985
        /*
986
         * (non-Javadoc)
987
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getRenderBands()
988
         */
989
        public int[] getRenderBands() {
990
                return (renderBands != null) ? renderBands : getRender().getRenderBands();
991
        }
992

    
993
        /*
994
         * (non-Javadoc)
995
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderBands(int[])
996
         */
997
        public void setRenderBands(int[] renderBands) {
998
                //TODO: Comprobar si hay cambios
999
                this.renderBands = renderBands;
1000
                this.updateDrawVersion();
1001
                getRender().setRenderBands(renderBands);
1002
        }
1003

    
1004
        /**
1005
         * This is the method used to draw a tile in a WMS mosaic layer.
1006
         * @throws LoadLayerException
1007
         * @throws ReadDriverException
1008
         * @return true when a tile has been painted
1009
         */
1010
        private boolean drawTile(Graphics2D g, ViewPort vp, Cancellable cancel, int tile, double scale) throws LoadLayerException, ReadDriverException {
1011
                callCount++;
1012
                // Compute the query geometry
1013
                // 1. Check if it is within borders
1014
                Rectangle2D extent = getFullExtent();
1015
                                if ((vp.getAdjustedExtent().getMinX() > extent.getMaxX()) ||
1016
                                                                (vp.getAdjustedExtent().getMinY() > extent.getMaxY()) ||
1017
                                                                (vp.getAdjustedExtent().getMaxX() < extent.getMinX()) ||
1018
                                                                (vp.getAdjustedExtent().getMaxY() < extent.getMinY())) {
1019
                                                return false;
1020
                                }
1021

    
1022
                                // 2. Compute extent to be requested.
1023
                                Rectangle2D bBox = new Rectangle2D.Double();
1024
                                Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
1025

    
1026
                                // 3. Compute size in pixels
1027
                                double scalex = vp.getAffineTransform().getScaleX();
1028
                                double scaley = vp.getAffineTransform().getScaleY();
1029
                                int wImg = (int) Math.ceil(Math.abs(bBox.getWidth() * scalex) + 1);
1030
                                int hImg = (int) Math.ceil(Math.abs(bBox.getHeight() * scaley) + 1);
1031

    
1032
                                Dimension sz = new Dimension(wImg, hImg);
1033

    
1034
                                if ((wImg <= 0) || (hImg <= 0)) {
1035
                                                return false;
1036
                                }
1037
                                MyCancellable c = new MyCancellable(cancel);
1038

    
1039
                try {
1040
                        sz = new Dimension(wImg, hImg);
1041
                        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
1042

    
1043

    
1044
                        wmsStatus.setExtent( bBox );
1045
                        wmsStatus.setFormat(m_Format);
1046
                        wmsStatus.setHeight( hImg );
1047
                        wmsStatus.setWidth( wImg );
1048
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
1049
                        wmsStatus.setSrs(m_SRS);
1050
                        wmsStatus.setStyles(styles);
1051
                        wmsStatus.setDimensions(dimensions);
1052
                        wmsStatus.setTransparency(wmsTransparency);
1053
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
1054

    
1055
                        // begin patch; Avoid to request too small tiles.
1056
                        // This generally occurs when printing
1057

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

    
1069
                        if (hImg < minTilePrintHeight) {
1070
                                double hScale = (double) minTilePrintHeight / hImg;
1071
                                wmsStatus.setHeight(minTilePrintHeight);
1072
                                Rectangle2D sExtent = wmsStatus.getExtent();
1073
                                Point2D initialPoint = new Point2D.Double(sExtent.getX(), sExtent.getY());
1074
                                sExtent.setRect(sExtent.getX(), sExtent.getY()*hScale, sExtent.getWidth(), sExtent.getHeight()*hScale);
1075
                                if (!bBox.contains(initialPoint)) {
1076
                                        sExtent.setRect(sExtent.getX(), sExtent.getY() - initialPoint.getY(), sExtent.getWidth(), sExtent.getHeight());
1077
                                }
1078
                        }
1079

    
1080
                        // end patch
1081
                        File f = getDriver().getMap(wmsStatus, c);
1082
                        if (f == null)
1083
                                return false;
1084
                        String nameWordFile = f.getPath() + getExtensionWorldFile();
1085
                        com.iver.andami.Utilities.createTemp(nameWordFile, this.getDataWorldFile(bBox, sz));
1086

    
1087
                        ViewPortData vpData = new ViewPortData(
1088
                                vp.getProjection(), new Extent(bBox), sz );
1089
                        vpData.setMat(vp.getAffineTransform());
1090

    
1091
                        String filePath = f.getAbsolutePath();
1092
                        visualStatus.fileNames[tile] = filePath;
1093
                        try {
1094
                                rasterProcess(filePath, g, vp, scale, cancel);
1095
//                                this.updateDrawVersion();
1096
                        } catch (FilterTypeException e) {
1097
                        }
1098

    
1099
                } catch (ValidationException e) {
1100
                        if (!c.isCanceled())
1101
                        {
1102
                                LoadLayerException exception = new LoadLayerException(getName(),e);
1103
                                throw exception;
1104
                        }
1105
                } catch (IOException e) {
1106
                        if (!c.isCanceled()){
1107
                                if (callCount<MAX_RETRY_TIMES) { // mess code
1108
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
1109
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
1110
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
1111

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

    
1139

    
1140
                                } //if
1141
                        }//if
1142
                }//catch
1143
                callCount--;
1144
                return true;
1145
        }
1146

    
1147
        /**
1148
         * Obtiene la extensi?n del fichero de georreferenciaci?n
1149
         * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
1150
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
1151
         */
1152
        private String getExtensionWorldFile(){
1153
                String extWorldFile = ".wld";
1154
                        if(m_Format.equals("image/tif") || m_Format.equals("image/tiff"))
1155
                                extWorldFile = ".tfw";
1156
                        if(m_Format.equals("image/jpeg"))
1157
                                extWorldFile = ".jpgw";
1158
                        return extWorldFile;
1159
        }
1160

    
1161
        /**
1162
         * Calcula el contenido del fichero de georreferenciaci?n de una imagen.
1163
         * @param bBox Tama?o y posici?n de la imagen (en coordenadas de usuario)
1164
         * @param sz Tama?o de la imagen en pixeles.
1165
         * @return el 'WorldFile', como String.
1166
         * @throws IOException
1167
         */
1168
        public String getDataWorldFile(Rectangle2D bBox, Dimension sz) throws IOException {
1169
                StringBuffer data = new StringBuffer();
1170
                        data.append((bBox.getMaxX() - bBox.getMinX())/(sz.getWidth() - 1)+"\n");
1171
                        data.append("0.0\n");
1172
                        data.append("0.0\n");
1173
                        data.append("-"+(bBox.getMaxY() - bBox.getMinY())/(sz.getHeight() - 1)+"\n");
1174
                        data.append(""+bBox.getMinX()+"\n");
1175
                        data.append(""+bBox.getMaxY()+"\n");
1176
                        return data.toString();
1177
        }
1178

    
1179
        /**
1180
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D,
1181
         *                 com.iver.cit.gvsig.fmap.ViewPort,
1182
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
1183
         */
1184
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet properties)
1185
                throws ReadDriverException {
1186
                if (isVisible() && isWithinScale(scale)){
1187
                isPrinting = true;
1188
                if (!mustTilePrint) {
1189
                        draw(null, g, viewPort, cancel,scale);
1190
                } else {
1191
                                        // Para no pedir imagenes demasiado grandes, vamos
1192
                                        // a hacer lo mismo que hace EcwFile: chunkear.
1193
                                        // Llamamos a drawView con cuadraditos m?s peque?os
1194
                                        // del BufferedImage ni caso, cuando se imprime viene con null
1195

    
1196
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
1197
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
1198
                        visualStatus.fileNames = new String[tiles.getNumTiles()];
1199
                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
1200
                                        // Parte que dibuja
1201
                                        try {
1202
                                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
1203
                                                        drawTile(g, vp, cancel, tileNr, scale);
1204
                                } catch (NoninvertibleTransformException e) {
1205
                                        e.printStackTrace();
1206
                                } catch (LoadLayerException e) {
1207
                                        // TODO Auto-generated catch block
1208
                                        e.printStackTrace();
1209
                                }
1210
                                        }
1211
                }
1212
                        isPrinting = false;
1213
                }
1214
        }
1215

    
1216
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale)
1217
                throws ReadDriverException {
1218
                draw(null, g, viewPort, cancel,scale);
1219
        }
1220

    
1221
        /**
1222
         * Devuelve el FMapWMSDriver.
1223
         *
1224
         * @return FMapWMSDriver
1225
         *
1226
         * @throws IllegalStateException
1227
         * @throws ValidationException
1228
         * @throws UnsupportedVersionLayerException
1229
         * @throws IOException
1230
         */
1231
        public FMapWMSDriver getDriver()
1232
                throws IllegalStateException, ValidationException,
1233
                        UnsupportedVersionLayerException, IOException {
1234
                return FMapWMSDriverFactory.getFMapDriverForURL(host);
1235
        }
1236

    
1237
        /**
1238
         * Devuelve el FMapWMSDriver.
1239
         *
1240
         * @return FMapWMSDriver
1241
         *
1242
         * @throws IllegalStateException
1243
         * @throws ValidationException
1244
         * @throws UnsupportedVersionLayerException
1245
         * @throws IOException
1246
         */
1247
        public void setDriver(FMapWMSDriver drv) {
1248
                //TODO: Comprobar cambio
1249
                wms = drv;
1250
                this.updateDrawVersion();
1251
        }
1252

    
1253
        /**
1254
         * Devuelve el URL.
1255
         *
1256
         * @return URL.
1257
         */
1258
        public URL getHost() {
1259
                return host;
1260
        }
1261

    
1262
        /**
1263
         * Inserta el URL.
1264
         *
1265
         * @param host URL.
1266
         */
1267
        public void setHost(URL host) {
1268
                if (this.host == host){
1269
                        return;
1270
                }
1271
                if (this.host != null && this.fullExtent.equals(host)){
1272
                        return;
1273
                }
1274

    
1275
                this.host = host;
1276
                this.updateDrawVersion();
1277
        }
1278

    
1279
        /**
1280
         * Devuelve la informaci?n de la consulta.
1281
         *
1282
         * @return String.
1283
         */
1284
        public String getInfoLayerQuery() {
1285
                return infoLayerQuery;
1286
        }
1287

    
1288
        /**
1289
         * Inserta la informaci?n de la consulta.
1290
         *
1291
         * @param infoLayerQuery String.
1292
         */
1293
        public void setInfoLayerQuery(String infoLayerQuery) {
1294
                this.infoLayerQuery = infoLayerQuery;
1295
        }
1296

    
1297
        /**
1298
         * Devuelve la consulta.
1299
         *
1300
         * @return String.
1301
         */
1302
        public String getLayerQuery() {
1303
                return layerQuery;
1304
        }
1305

    
1306
        /**
1307
         * Inserta la consulta.
1308
         *
1309
         * @param layerQuery consulta.
1310
         */
1311
        public void setLayerQuery(String layerQuery) {
1312
                if (this.layerQuery == layerQuery){
1313
                        return;
1314
                }
1315
                if (this.layerQuery != null && this.layerQuery.equals(layerQuery)){
1316
                        return;
1317
                }
1318

    
1319
                this.layerQuery = layerQuery;
1320
                this.updateDrawVersion();
1321
        }
1322

    
1323
        /**
1324
         * Devuelve el formato.
1325
         *
1326
         * @return Formato.
1327
         */
1328
        public String getFormat() {
1329
                return m_Format;
1330
        }
1331

    
1332
        /**
1333
         * Inserta el formato.
1334
         *
1335
         * @param format Formato.
1336
         */
1337
        public void setFormat(String format) {
1338
                if (this.m_Format == format){
1339
                        return;
1340
                }
1341
                if (this.m_Format != null && this.m_Format.equals(format)){
1342
                        return;
1343
                }
1344
                m_Format = format;
1345
                this.updateDrawVersion();
1346
        }
1347

    
1348
        /**
1349
         * Devuelve el SRS.
1350
         *
1351
         * @return SRS.
1352
         */
1353
        public String getSRS() {
1354
                return m_SRS;
1355
        }
1356

    
1357
        /**
1358
         * Inserta el SRS.
1359
         *
1360
         * @param m_srs SRS.
1361
         */
1362
        public void setSRS(String m_srs) {
1363
                if (m_SRS == m_srs){
1364
                        return;
1365
                }
1366
                if (m_SRS != null && m_SRS.equals(m_srs)){
1367
                        return;
1368
                }
1369
                m_SRS = m_srs;
1370
                this.updateDrawVersion();
1371
                setProjection(CRSFactory.getCRS(getSRS()));
1372
        }
1373

    
1374
        /**
1375
         * Inserta la extensi?n total de la capa.
1376
         *
1377
         * @param fullExtent Rect?ngulo.
1378
         */
1379
        public void setFullExtent(Rectangle2D fullExtent) {
1380
                if (this.fullExtent == fullExtent){
1381
                        return;
1382
                }
1383
                if (this.fullExtent != null && this.fullExtent.equals(fullExtent)){
1384
                        return;
1385
                }
1386

    
1387
                this.fullExtent = fullExtent;
1388
                this.updateDrawVersion();
1389
        }
1390

    
1391
        public HashMap getProperties() {
1392
                HashMap info = new HashMap();
1393
                                String[] layerNames = getLayerQuery().split(",");
1394
                                Vector layers = new Vector(layerNames.length);
1395
                                try {
1396
                                                if(getDriver().connect(null)){
1397
                                                                for (int i = 0; i < layerNames.length; i++) {
1398
                                                                                layers.add(i, getDriver().getLayer(layerNames[i]));
1399
                                                                }
1400
                                                                info.put("name", getName());
1401
                                                                info.put("selectedLayers", layers);
1402
                                                                info.put("host", getHost());
1403
                                                                info.put("srs", getSRS());
1404
                                                                info.put("format", getFormat());
1405
                                                                info.put("wmsTransparency", new Boolean(wmsTransparency));
1406
                                                                info.put("styles", styles);
1407
                                                                info.put("dimensions", dimensions);
1408
                                                                info.put("fixedSize", fixedSize);
1409
                                                                return info;
1410
                                                }
1411
                                } catch (Exception e) {
1412
                                                e.printStackTrace();
1413
                                }
1414
                                return null;
1415
        }
1416

    
1417
        public double getMaxX() {
1418
                return visualStatus.maxX;
1419
        }
1420

    
1421
        public double getMaxY() {
1422
                return visualStatus.maxY;
1423
        }
1424

    
1425
        public double getMinX() {
1426
                return visualStatus.minX;
1427
        }
1428

    
1429
        public double getMinY() {
1430
                return visualStatus.minY;
1431
        }
1432

    
1433
                /**
1434
                 * @return Returns the wmsTransparency.
1435
                 */
1436
                public boolean isWmsTransparent() {
1437
                                return wmsTransparency;
1438
                }
1439

    
1440
                /**
1441
                 * @param wmsTransparency The wmsTransparency to set.
1442
                 */
1443
                public void setWmsTransparency(boolean wmsTransparency) {
1444
                        if (this.wmsTransparency == wmsTransparency){
1445
                                return;
1446
                        }
1447
                        this.wmsTransparency = wmsTransparency;
1448
                        this.updateDrawVersion();
1449
                }
1450

    
1451
                 /**
1452
                 * @param styles
1453
                 */
1454
                public void setStyles(Vector styles) {
1455
                    if (this.styles == styles){
1456
                            return;
1457
                    }
1458
                    if (this.styles != null && styles != null ){
1459
                            if (this.styles.containsAll(styles) && this.styles.size() ==styles.size()){
1460
                                    return;
1461
                            }
1462
                    }
1463
                    this.styles = styles;
1464
                    this.updateDrawVersion();
1465
                }
1466

    
1467
                /**
1468
                 * Sets the dimension vector that is a list of key-value pairs containing
1469
                 * the name of the dimension and the value for it
1470
                 * @param dimensions
1471
                 */
1472
                public void setDimensions(Vector dimensions) {
1473
                        if (this.dimensions == dimensions){
1474
                                return;
1475
                        }
1476
                        if (this.dimensions != null && dimensions != null ){
1477
                                if (this.dimensions.containsAll(dimensions) && this.dimensions.size() ==dimensions.size()){
1478
                                        return;
1479
                                }
1480
                        }
1481
                        this.dimensions = dimensions;
1482
                        this.updateDrawVersion();
1483
                }
1484

    
1485
                /**
1486
                 * Sets the set of URLs that should be accessed for each operation performed
1487
                 * to the server.
1488
                 *
1489
                 * @param onlineResources
1490
                 */
1491
        public void setOnlineResources(Hashtable onlineResources) {
1492
            if (this.onlineResources == onlineResources){
1493
                    return;
1494
            }
1495
            if (this.onlineResources != null && this.onlineResources.equals(onlineResources)){
1496
                    return;
1497
            }
1498

    
1499
                this.onlineResources = onlineResources;
1500
                this.updateDrawVersion();
1501
        }
1502

    
1503
                /**
1504
                 * Gets the URL that should be accessed for an operation performed
1505
                 * to the server.
1506
                 *
1507
                 * @param onlineResources
1508
                 */
1509
        public String getOnlineResource(String operation) {
1510
                return ((String) onlineResources.get(operation));
1511
        }
1512

    
1513
        /**
1514
         * When a server is not fully featured and it only can serve constant map
1515
         * sizes this value must be set. It expresses the size in pixels (width, height)
1516
         * that the map will be requested.
1517
         * @param Dimension sz
1518
         */
1519
        public void setFixedSize(Dimension sz) {
1520
                if (this.fixedSize == sz){
1521
                        return;
1522
                }
1523
                if (this.fixedSize != null && this.fixedSize.equals(sz)){
1524
                        return;
1525
                }
1526
                fixedSize = sz;
1527
                this.updateDrawVersion();
1528
        }
1529

    
1530
        /**
1531
         * Tells whether if this layer must deal with the server with the constant-size
1532
         * limitations or not.
1533
         * @return boolean.
1534
         */
1535
        private boolean isSizeFixed() {
1536
                return fixedSize != null && fixedSize.getWidth() > 0 && fixedSize.getHeight() > 0;
1537
        }
1538

    
1539
        /**
1540
         * If it is true, this layer accepts GetFeatureInfo operations. This WMS operations
1541
         * maps to FMap's infoByPoint(p) operation.
1542
         * @param b
1543
         */
1544
        public void setQueryable(boolean b) {
1545
                queryable = b;
1546
        }
1547

    
1548
        /**
1549
         * Creates the part of a OGC's MapContext document that would describe this
1550
         * layer(s).
1551
         * @param version, The desired version of the resulting document. (1.1.0)
1552
         * @return String containing the xml.
1553
         * @throws UnsupportedVersionLayerException
1554
         */
1555
        public String toMapContext(String mapContextVersion) {
1556
                XmlBuilder xml = new XmlBuilder();
1557
                FMapWMSDriver drv;
1558
                try {
1559
                        drv = getDriver();
1560
                } catch (Exception e) {
1561
                        return xml.toString();
1562
                }
1563
                String[] layerNames = getLayerQuery().split(",");
1564
                String[] styleNames = (String[]) styles.toArray(new String[0]);
1565
                for (int i = 0; i < layerNames.length; i++) {
1566
                        WMSLayerNode layer = drv.getLayer(layerNames[i]);
1567
                        HashMap xmlAttrs = new HashMap();
1568

    
1569
                        // <Layer>
1570
                        xmlAttrs.put(WebMapContextTags.HIDDEN, !isVisible()+"");
1571
                        xmlAttrs.put(WebMapContextTags.QUERYABLE, queryable+"");
1572
                        xml.openTag(WebMapContextTags.LAYER, xmlAttrs);
1573
                        xmlAttrs.clear();
1574
                        if (mapContextVersion.equals("1.1.0") || mapContextVersion.equals("1.0.0")) {
1575
                                // <Server>
1576
                                xmlAttrs.put(WebMapContextTags.SERVICE, WebMapContextTags.WMS);
1577
                                xmlAttrs.put(WebMapContextTags.VERSION, drv.getVersion());
1578
                                xmlAttrs.put(WebMapContextTags.SERVER_TITLE, drv.getServiceTitle());
1579
                                xml.openTag(WebMapContextTags.SERVER, xmlAttrs);
1580
                                xmlAttrs.clear();
1581

    
1582
                                        // <OnlineResource>
1583
                                        xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1584
                                        xmlAttrs.put(WebMapContextTags.XLINK_HREF, getHost().toString());
1585
                                        xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1586
                                        xmlAttrs.clear();
1587
                                        // </OnlineResource>
1588

    
1589
                                xml.closeTag();
1590
                                // </Server>
1591

    
1592
                                // <Name>
1593
                                xml.writeTag(WebMapContextTags.NAME, layer.getName().trim());
1594
                                // </Name>
1595

    
1596
                                // <Title>
1597
                                xml.writeTag(WebMapContextTags.TITLE, layer.getTitle().trim());
1598
                                //?xml.writeTag(WebMapContextTags.TITLE, getName().trim());
1599
                                // </Title>
1600

    
1601
                                // <Abstract>
1602
                                if (layer.getAbstract() != null)
1603
                                        xml.writeTag(WebMapContextTags.ABSTRACT, layer.getAbstract());
1604
                                // </Abstract>
1605

    
1606
                                // <SRS> (a list of available SRS for the enclosing layer)
1607
                                String[] strings = (String[]) layer.getAllSrs().toArray(new String[0]);
1608
                                String mySRS = strings[0];
1609
                                for (int j = 1; j < strings.length; j++) {
1610
                                        mySRS += ","+strings[j];
1611
                                }
1612
                                xml.writeTag(WebMapContextTags.SRS, mySRS);
1613
                                // </SRS>
1614

    
1615
                                // <FormatList>
1616
                                xml.openTag(WebMapContextTags.FORMAT_LIST);
1617
                                        strings = (String[]) drv.getFormats().toArray(new String[0]);
1618
                                        for (int j = 0; j < strings.length; j++) {
1619
                                                                                // <Format>
1620
                                                String str = strings[j].trim();
1621
                                                if (str.equals(getFormat()))
1622
                                                        xml.writeTag(WebMapContextTags.FORMAT, str, WebMapContextTags.CURRENT, "1");
1623
                                                else
1624
                                                        xml.writeTag(WebMapContextTags.FORMAT, str);
1625
                                                                                // </Format>
1626
                                        }
1627
                                xml.closeTag();
1628
                                // </FormatList>
1629

    
1630
                                // <StyleList>
1631
                                xml.openTag(WebMapContextTags.STYLE_LIST);
1632

    
1633
                                        if (layer.getStyles().size()>0) {
1634
                                                for (int j = 0; j < layer.getStyles().size(); j++) {
1635
                                                        // <Style>
1636
                                                        FMapWMSStyle st = (FMapWMSStyle) layer.getStyles().get(j);
1637
                                                        if (st.name.equals(styleNames[i]))
1638
                                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1639
                                                        xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1640
                                                        xmlAttrs.clear();
1641

    
1642
                                                                // <Name>
1643
                                                                xml.writeTag(WebMapContextTags.NAME, st.name);
1644
                                                                // </Name>
1645

    
1646
                                                                // <Title>
1647
                                                                xml.writeTag(WebMapContextTags.TITLE, st.title);
1648
                                                                // </Title>
1649

    
1650
                                                                // <LegendURL width="180" format="image/gif" height="50">
1651
                                                                        // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1652
                                                                        // </OnlineResource>
1653
                                                                // </LegendURL>
1654
                                                        xml.closeTag();
1655
                                                        // </Style>
1656

    
1657
                                                }
1658

    
1659
                                        } else {
1660
                                                // Create fake style (for compatibility issues)
1661
                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1662
                                                // <Style>
1663
                                                xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1664
                                                        xmlAttrs.clear();
1665
                                                        // <Name>
1666
                                                        xml.writeTag(WebMapContextTags.NAME, "default");
1667
                                                        // </Name>
1668

    
1669
                                                        // <Title>
1670
                                                        xml.writeTag(WebMapContextTags.TITLE, "default");
1671
                                                        // </Title>
1672

    
1673
//                                                        // <LegendURL width="180" format="image/gif" height="50">
1674
//                                                        xmlAttrs.put(WebMapContextTags.WIDTH, "0");
1675
//                                                        xmlAttrs.put(WebMapContextTags.HEIGHT, "0");
1676
//                                                        xmlAttrs.put(WebMapContextTags.FORMAT.toLowerCase(), "image/gif");
1677
//                                                        xml.openTag(WebMapContextTags.LEGEND_URL, xmlAttrs);
1678
//                                                        xmlAttrs.clear();
1679
//                                                                // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1680
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1681
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_HREF, "http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif");
1682
//                                                                xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1683
//                                                                // </OnlineResource>
1684
//                                                    // </LegendURL>
1685
//                                                        xml.closeTag();
1686
                                                // </Style>
1687
                                                xml.closeTag();
1688
                                        }
1689
                                // </StyleList>
1690
                                xml.closeTag();
1691
                                if (mapContextVersion.compareTo("1.0.0") > 0) {
1692
                                // <DimensionList>
1693
                                        xml.openTag(WebMapContextTags.DIMENSION_LIST);
1694
                                        // <Dimension>
1695
                                        // </Dimension>
1696
                                        xml.closeTag();
1697
                                // </DimensionList>
1698
                                }
1699
                        } else {
1700
                                xml.writeTag("ERROR", PluginServices.getText(this, "unsupported_map_context_version"));
1701
                        }
1702
                        // </Layer>
1703
                        xml.closeTag();
1704
                }
1705
                return xml.getXML();
1706
        }
1707

    
1708
        public ImageIcon getTocImageIcon() {
1709
                return new ImageIcon(getClass().getResource("image/icon-layer-wms.png"));
1710
        }
1711

    
1712
        /*
1713
         *  (non-Javadoc)
1714
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1715
         */
1716
        public int[] getTileSize() {
1717
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1718
                return size;
1719
        }
1720

    
1721
        /*
1722
         *  (non-Javadoc)
1723
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1724
         */
1725
        public boolean isTiled() {
1726
                return mustTileDraw;
1727
        }
1728

    
1729
        public Image getImageLegend() {
1730
                try {
1731
                        if (wms == null)
1732
                                wms = getDriver();
1733
                        if (wms.hasLegendGraphic()) {
1734
                                wmsStatus.setOnlineResource((String) onlineResources
1735
                                                .get("GetLegendGraphic"));
1736
                                String path = getPathImage();// File legend =
1737
                                                                                                // getDriver().getLegendGraphic(wmsStatus,
1738
                                                                                                // layerQuery, null);
1739
                                Image img = null;
1740
                                if ((path != null) && (path.length() > 0))
1741
                                        img = new ImageIcon(path).getImage();
1742
                                return img;
1743
                        }
1744
                } catch (Exception e) {
1745
                }
1746
                return null;
1747
        }
1748

    
1749
        public String getPathImage() {
1750
                try {
1751
                        File legend = getDriver().getLegendGraphic(wmsStatus, layerQuery, null);
1752
                        return legend.getAbsolutePath();
1753
                }catch(Exception e){
1754
                        e.printStackTrace();
1755
                        return null;
1756
                }
1757
        }
1758

    
1759
        /* (non-Javadoc)
1760
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#newComposedLayer()
1761
         */
1762
        public ComposedLayer newComposedLayer() {
1763
                Preferences prefs = Preferences.userRoot().node("gvsig.wms");
1764

    
1765
                /*
1766
                 * from java.util.prefs import Preferences
1767
                 * prefs = Preferences.userRoot().node("gvsig.wms")
1768
                 * prefs.put("useComposedLayer","true")
1769
                 */
1770

    
1771
                String str = prefs.get("useComposedLayer","false");
1772
                Boolean useComposedLayer = Boolean.TRUE; // por defecto ya se usan
1773
                try {
1774
                        useComposedLayer = Boolean.valueOf(str);
1775
                } catch (Exception e) {
1776

    
1777
                }
1778
                if (useComposedLayer.booleanValue()) {
1779
                        return new ComposedLayerWMS();
1780
                } else {
1781
                        return null;
1782
                }
1783
        }
1784

    
1785
        /**
1786
         * @param styles
1787
         */
1788
        public Vector getStyles() {
1789
                return this.styles;
1790
        }
1791

    
1792

    
1793
        /*
1794
         * Checks if can make a single petition for the two layers to the server
1795
         * @see com.iver.cit.gvsig.fmap.layers.ComposedLayerWMS#canAdd(com.iver.cit.gvsig.fmap.layers.FLayer)
1796
         */
1797
        boolean isComposedLayerCompatible(FLayer layer) {
1798
                FLyrWMS aLayer;
1799

    
1800
                if (!(layer instanceof FLyrWMS)) {
1801
                        return false;
1802
                }
1803
                aLayer = (FLyrWMS)layer;
1804
                if (!this.getHost().equals(aLayer.getHost())) {
1805
                        return false;
1806
                }
1807
                if (!this.getFormat().equals(aLayer.getFormat())) {
1808
                        return false;
1809
                }
1810
                if (!this.getSRS().equals(aLayer.getSRS())) {
1811
                        return false;
1812
                }
1813
                if (this.getInfoLayerQuery() != null) {
1814
                        if (!this.getInfoLayerQuery().equals(aLayer.getInfoLayerQuery())) {
1815
                                return false;
1816
                        }
1817
                }else if (aLayer.getInfoLayerQuery() != null) {
1818
                        return false;
1819
                }
1820

    
1821

    
1822
                // isFixedSize es privado
1823
                if ((this.fixedSize != null) &&
1824
                                (aLayer.fixedSize!= null)) {
1825
                        if (this.fixedSize.equals(aLayer.fixedSize)) {
1826
                                return false;
1827
                        }
1828
                } else if ((this.fixedSize != null) != (aLayer.fixedSize != null)) {
1829
                        return false;
1830
                }
1831

    
1832
                // time elevation (dimensions)
1833
                if ((this.dimensions != null) &&
1834
                                (aLayer.dimensions != null)) {
1835
                        if (this.dimensions.size() != aLayer.dimensions.size()) {
1836
                                return false;
1837
                        } else {
1838
                                Iterator iter = this.dimensions.iterator();
1839
                                while (iter.hasNext()) {
1840
                                        if (!aLayer.dimensions.contains(iter.next())) {
1841
                                                return false;
1842
                                        }
1843
                                }
1844
                        }
1845

    
1846
                } else if ((this.dimensions != null) != (aLayer.dimensions != null)) {
1847
                        return false;
1848
                }
1849

    
1850
                return true;
1851
        }
1852

    
1853
        /*
1854
         * (non-Javadoc)
1855
         * @see org.gvsig.fmap.raster.layers.FLyrRasterSE#isActionEnabled(int)
1856
         */
1857
        public boolean isActionEnabled(int action) {
1858
                switch (action) {
1859
                        case IRasterLayerActions.ZOOM_PIXEL_RESOLUTION:
1860
                        case IRasterLayerActions.FLYRASTER_BAR_TOOLS:
1861
                        case IRasterLayerActions.BANDS_FILE_LIST:
1862
                        case IRasterLayerActions.COLOR_TABLE:
1863
                        case IRasterLayerActions.GEOLOCATION:
1864
                        case IRasterLayerActions.PANSHARPENING:
1865
                        case IRasterLayerActions.SAVE_COLORINTERP:
1866
                                return false;
1867
                }
1868

    
1869
                return super.isActionEnabled(action);
1870
        }
1871

    
1872
        /*
1873
         * (non-Javadoc)
1874
         * @see org.gvsig.fmap.raster.layers.FLyrRasterSE#getLegend()
1875
         */
1876
        public ILegend getLegend() {
1877
                return null;
1878
        }
1879

    
1880
        /*
1881
         * (non-Javadoc)
1882
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
1883
         */
1884
        public int[] getDataType(){
1885
                try {
1886
                        return dataset.getDataType();
1887
                } catch (NullPointerException e) {
1888
                        if(layerRaster != null)
1889
                                return layerRaster.getDataType();
1890
                        else
1891
                                return new int[]{IBuffer.TYPE_UNDEFINED};
1892
                }
1893
        }
1894

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

    
1903
        protected void updateDrawVersion() {
1904
                if (this.disableUpdateDrawVersion != null){
1905

    
1906
                        Thread curThread = Thread.currentThread();
1907

    
1908
                        Thread aThread;
1909

    
1910
                        Iterator iter = this.disableUpdateDrawVersion.iterator();
1911
                        while (iter.hasNext()){
1912
                                aThread = (Thread) ((WeakReference)iter.next()).get();
1913
                                if (aThread == null){
1914
                                        iter.remove();
1915
                                } else if(aThread.equals(curThread)){
1916
                                        return;
1917
                                }
1918
                        }
1919
                }
1920
//                Exception ex = new Exception();
1921
//                ex.printStackTrace();
1922
                super.updateDrawVersion();
1923
        }
1924

    
1925
        protected void disableUpdateDrawVersion(){
1926
                if (this.disableUpdateDrawVersion == null){
1927
                        this.disableUpdateDrawVersion = new ArrayList();
1928
                }
1929
                this.disableUpdateDrawVersion.add(new WeakReference(Thread.currentThread()));
1930
        }
1931

    
1932
        protected void enableUpdateDrawVersion(){
1933
                if (this.disableUpdateDrawVersion == null){
1934
                        return;
1935
                }
1936

    
1937
                Thread curThread = Thread.currentThread();
1938

    
1939
                Thread aThread;
1940

    
1941

    
1942
                Iterator iter = this.disableUpdateDrawVersion.iterator();
1943
                while (iter.hasNext()){
1944
                        aThread = (Thread) ((WeakReference)iter.next()).get();
1945
                        if (aThread == null){
1946
                                iter.remove();
1947
                        } else if(aThread.equals(curThread)){
1948
                                iter.remove();
1949
                                break;
1950
                        }
1951
                }
1952

    
1953
        }
1954

    
1955
}