Statistics
| Revision:

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

History | View | Annotate | Download (60 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
                                }
681

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

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

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

    
772

    
773
                // This is the extent that will be requested
774
                Rectangle2D bBox = getFullExtent();
775
                MyCancellable c = new MyCancellable(cancel);
776

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

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

    
808
                        // And finally, obtain the extent intersecting the view and the BBox
809
                        // to draw to.
810
                        Rectangle2D extent = new Rectangle2D.Double();
811
                        Rectangle2D.intersect(vp.getAdjustedExtent(), bBox, extent);
812

    
813
                        ViewPortData vpData = new ViewPortData(
814
                                vp.getProjection(), new Extent(extent), fixedSize );
815
                        vpData.setMat(vp.getAffineTransform());
816

    
817
                        String filePath = f.getAbsolutePath();
818
                        visualStatus.fileNames[0] = filePath;
819

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

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

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

    
864

    
865
                                } // mess code
866
                        }
867
                }
868
                callCount--; // mess code
869
        }
870

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

    
888
                //Cargamos el dataset con el raster de disco.
889
                layerRaster = FLyrRasterSE.createLayer("", filePath, vp.getProjection());
890
                layerRaster.getRender().setBufferFactory(layerRaster.getBufferFactory());
891
                layerRaster.setNoDataValue(getNoDataValue());
892
                layerRaster.setNoDataType(getNoDataType());
893

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

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

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

    
936
                //Dibujamos
937
                disableUpdateDrawVersion();
938
                layerRaster.draw(null, g, vp, cancel, scale);
939
                enableUpdateDrawVersion();
940

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

    
950
        }
951

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

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

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

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

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

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

    
1018
                                // 2. Compute extent to be requested.
1019
                                Rectangle2D bBox = new Rectangle2D.Double();
1020
                                Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
1021

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

    
1028
                                Dimension sz = new Dimension(wImg, hImg);
1029

    
1030
                                if ((wImg <= 0) || (hImg <= 0)) {
1031
                                                return false;
1032
                                }
1033
                                MyCancellable c = new MyCancellable(cancel);
1034

    
1035
                try {
1036
                        sz = new Dimension(wImg, hImg);
1037
                        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
1038

    
1039

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

    
1051
                        // begin patch; Avoid to request too small tiles.
1052
                        // This generally occurs when printing
1053

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

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

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

    
1083
                        ViewPortData vpData = new ViewPortData(
1084
                                vp.getProjection(), new Extent(bBox), sz );
1085
                        vpData.setMat(vp.getAffineTransform());
1086

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

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

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

    
1135

    
1136
                                } //if
1137
                        }//if
1138
                }//catch
1139
                callCount--;
1140
                return true;
1141
        }
1142

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

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

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

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

    
1211
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale)
1212
                throws ReadDriverException {
1213
                draw(null, g, viewPort, cancel,scale);
1214
        }
1215

    
1216
        /**
1217
         * Devuelve el FMapWMSDriver.
1218
         *
1219
         * @return FMapWMSDriver
1220
         *
1221
         * @throws IllegalStateException
1222
         * @throws ValidationException
1223
         * @throws UnsupportedVersionLayerException
1224
         * @throws IOException
1225
         */
1226
        public FMapWMSDriver getDriver()
1227
                throws IllegalStateException, ValidationException,
1228
                        UnsupportedVersionLayerException, IOException {
1229
                return FMapWMSDriverFactory.getFMapDriverForURL(host);
1230
        }
1231

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

    
1248
        /**
1249
         * Devuelve el URL.
1250
         *
1251
         * @return URL.
1252
         */
1253
        public URL getHost() {
1254
                return host;
1255
        }
1256

    
1257
        /**
1258
         * Inserta el URL.
1259
         *
1260
         * @param host URL.
1261
         */
1262
        public void setHost(URL host) {
1263
                if (this.host == host){
1264
                        return;
1265
                }
1266
                if (this.host != null && this.fullExtent.equals(host)){
1267
                        return;
1268
                }
1269

    
1270
                this.host = host;
1271
                this.updateDrawVersion();
1272
        }
1273

    
1274
        /**
1275
         * Devuelve la informaci?n de la consulta.
1276
         *
1277
         * @return String.
1278
         */
1279
        public String getInfoLayerQuery() {
1280
                return infoLayerQuery;
1281
        }
1282

    
1283
        /**
1284
         * Inserta la informaci?n de la consulta.
1285
         *
1286
         * @param infoLayerQuery String.
1287
         */
1288
        public void setInfoLayerQuery(String infoLayerQuery) {
1289
                this.infoLayerQuery = infoLayerQuery;
1290
        }
1291

    
1292
        /**
1293
         * Devuelve la consulta.
1294
         *
1295
         * @return String.
1296
         */
1297
        public String getLayerQuery() {
1298
                return layerQuery;
1299
        }
1300

    
1301
        /**
1302
         * Inserta la consulta.
1303
         *
1304
         * @param layerQuery consulta.
1305
         */
1306
        public void setLayerQuery(String layerQuery) {
1307
                if (this.layerQuery == layerQuery){
1308
                        return;
1309
                }
1310
                if (this.layerQuery != null && this.layerQuery.equals(layerQuery)){
1311
                        return;
1312
                }
1313

    
1314
                this.layerQuery = layerQuery;
1315
                this.updateDrawVersion();
1316
        }
1317

    
1318
        /**
1319
         * Devuelve el formato.
1320
         *
1321
         * @return Formato.
1322
         */
1323
        public String getFormat() {
1324
                return m_Format;
1325
        }
1326

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

    
1343
        /**
1344
         * Devuelve el SRS.
1345
         *
1346
         * @return SRS.
1347
         */
1348
        public String getSRS() {
1349
                return m_SRS;
1350
        }
1351

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

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

    
1382
                this.fullExtent = fullExtent;
1383
                this.updateDrawVersion();
1384
        }
1385

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

    
1412
        public double getMaxX() {
1413
                return visualStatus.maxX;
1414
        }
1415

    
1416
        public double getMaxY() {
1417
                return visualStatus.maxY;
1418
        }
1419

    
1420
        public double getMinX() {
1421
                return visualStatus.minX;
1422
        }
1423

    
1424
        public double getMinY() {
1425
                return visualStatus.minY;
1426
        }
1427

    
1428
                /**
1429
                 * @return Returns the wmsTransparency.
1430
                 */
1431
                public boolean isWmsTransparent() {
1432
                                return wmsTransparency;
1433
                }
1434

    
1435
                /**
1436
                 * @param wmsTransparency The wmsTransparency to set.
1437
                 */
1438
                public void setWmsTransparency(boolean wmsTransparency) {
1439
                        if (this.wmsTransparency == wmsTransparency){
1440
                                return;
1441
                        }
1442
                        this.wmsTransparency = wmsTransparency;
1443
                        this.updateDrawVersion();
1444
                }
1445

    
1446
                 /**
1447
                 * @param styles
1448
                 */
1449
                public void setStyles(Vector styles) {
1450
                    if (this.styles == styles){
1451
                            return;
1452
                    }
1453
                    if (this.styles != null && styles != null ){
1454
                            if (this.styles.containsAll(styles) && this.styles.size() ==styles.size()){
1455
                                    return;
1456
                            }
1457
                    }
1458
                    this.styles = styles;
1459
                    this.updateDrawVersion();
1460
                }
1461

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

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

    
1494
                this.onlineResources = onlineResources;
1495
                this.updateDrawVersion();
1496
        }
1497

    
1498
                /**
1499
                 * Gets the URL that should be accessed for an operation performed
1500
                 * to the server.
1501
                 *
1502
                 * @param onlineResources
1503
                 */
1504
        public String getOnlineResource(String operation) {
1505
                return ((String) onlineResources.get(operation));
1506
        }
1507

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

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

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

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

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

    
1577
                                        // <OnlineResource>
1578
                                        xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1579
                                        xmlAttrs.put(WebMapContextTags.XLINK_HREF, getHost().toString());
1580
                                        xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1581
                                        xmlAttrs.clear();
1582
                                        // </OnlineResource>
1583

    
1584
                                xml.closeTag();
1585
                                // </Server>
1586

    
1587
                                // <Name>
1588
                                xml.writeTag(WebMapContextTags.NAME, layer.getName().trim());
1589
                                // </Name>
1590

    
1591
                                // <Title>
1592
                                xml.writeTag(WebMapContextTags.TITLE, layer.getTitle().trim());
1593
                                //?xml.writeTag(WebMapContextTags.TITLE, getName().trim());
1594
                                // </Title>
1595

    
1596
                                // <Abstract>
1597
                                if (layer.getAbstract() != null)
1598
                                        xml.writeTag(WebMapContextTags.ABSTRACT, layer.getAbstract());
1599
                                // </Abstract>
1600

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

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

    
1625
                                // <StyleList>
1626
                                xml.openTag(WebMapContextTags.STYLE_LIST);
1627

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

    
1637
                                                                // <Name>
1638
                                                                xml.writeTag(WebMapContextTags.NAME, st.name);
1639
                                                                // </Name>
1640

    
1641
                                                                // <Title>
1642
                                                                xml.writeTag(WebMapContextTags.TITLE, st.title);
1643
                                                                // </Title>
1644

    
1645
                                                                // <LegendURL width="180" format="image/gif" height="50">
1646
                                                                        // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1647
                                                                        // </OnlineResource>
1648
                                                                // </LegendURL>
1649
                                                        xml.closeTag();
1650
                                                        // </Style>
1651

    
1652
                                                }
1653

    
1654
                                        } else {
1655
                                                // Create fake style (for compatibility issues)
1656
                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1657
                                                // <Style>
1658
                                                xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1659
                                                        xmlAttrs.clear();
1660
                                                        // <Name>
1661
                                                        xml.writeTag(WebMapContextTags.NAME, "default");
1662
                                                        // </Name>
1663

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

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

    
1703
        public ImageIcon getTocImageIcon() {
1704
                return new ImageIcon(getClass().getResource("image/icoLayer.png"));
1705
        }
1706

    
1707
        /*
1708
         *  (non-Javadoc)
1709
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1710
         */
1711
        public int[] getTileSize() {
1712
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1713
                return size;
1714
        }
1715

    
1716
        /*
1717
         *  (non-Javadoc)
1718
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1719
         */
1720
        public boolean isTiled() {
1721
                return mustTileDraw;
1722
        }
1723

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

    
1744
        public String getPathImage() {
1745
                try {
1746
                        File legend = getDriver().getLegendGraphic(wmsStatus, layerQuery, null);
1747
                        return legend.getAbsolutePath();
1748
                }catch(Exception e){
1749
                        e.printStackTrace();
1750
                        return null;
1751
                }
1752
        }
1753

    
1754
        /* (non-Javadoc)
1755
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#newComposedLayer()
1756
         */
1757
        public ComposedLayer newComposedLayer() {
1758
                Preferences prefs = Preferences.userRoot().node("gvsig.wms");
1759

    
1760
                /*
1761
                 * from java.util.prefs import Preferences
1762
                 * prefs = Preferences.userRoot().node("gvsig.wms")
1763
                 * prefs.put("useComposedLayer","true")
1764
                 */
1765

    
1766
                String str = prefs.get("useComposedLayer","false");
1767
                Boolean useComposedLayer = Boolean.TRUE; // por defecto ya se usan
1768
                try {
1769
                        useComposedLayer = Boolean.valueOf(str);
1770
                } catch (Exception e) {
1771

    
1772
                }
1773
                if (useComposedLayer.booleanValue()) {
1774
                        return new ComposedLayerWMS();
1775
                } else {
1776
                        return null;
1777
                }
1778
        }
1779

    
1780
        /**
1781
         * @param styles
1782
         */
1783
        public Vector getStyles() {
1784
                return this.styles;
1785
        }
1786

    
1787

    
1788
        /*
1789
         * Checks if can make a single petition for the two layers to the server
1790
         * @see com.iver.cit.gvsig.fmap.layers.ComposedLayerWMS#canAdd(com.iver.cit.gvsig.fmap.layers.FLayer)
1791
         */
1792
        boolean isComposedLayerCompatible(FLayer layer) {
1793
                FLyrWMS aLayer;
1794

    
1795
                if (!(layer instanceof FLyrWMS)) {
1796
                        return false;
1797
                }
1798
                aLayer = (FLyrWMS)layer;
1799
                if (!this.getHost().equals(aLayer.getHost())) {
1800
                        return false;
1801
                }
1802
                if (!this.getFormat().equals(aLayer.getFormat())) {
1803
                        return false;
1804
                }
1805
                if (!this.getSRS().equals(aLayer.getSRS())) {
1806
                        return false;
1807
                }
1808
                if (this.getInfoLayerQuery() != null) {
1809
                        if (!this.getInfoLayerQuery().equals(aLayer.getInfoLayerQuery())) {
1810
                                return false;
1811
                        }
1812
                }else if (aLayer.getInfoLayerQuery() != null) {
1813
                        return false;
1814
                }
1815

    
1816

    
1817
                // isFixedSize es privado
1818
                if ((this.fixedSize != null) &&
1819
                                (aLayer.fixedSize!= null)) {
1820
                        if (this.fixedSize.equals(aLayer.fixedSize)) {
1821
                                return false;
1822
                        }
1823
                } else if ((this.fixedSize != null) != (aLayer.fixedSize != null)) {
1824
                        return false;
1825
                }
1826

    
1827
                // time elevation (dimensions)
1828
                if ((this.dimensions != null) &&
1829
                                (aLayer.dimensions != null)) {
1830
                        if (this.dimensions.size() != aLayer.dimensions.size()) {
1831
                                return false;
1832
                        } else {
1833
                                Iterator iter = this.dimensions.iterator();
1834
                                while (iter.hasNext()) {
1835
                                        if (!aLayer.dimensions.contains(iter.next())) {
1836
                                                return false;
1837
                                        }
1838
                                }
1839
                        }
1840

    
1841
                } else if ((this.dimensions != null) != (aLayer.dimensions != null)) {
1842
                        return false;
1843
                }
1844

    
1845
                return true;
1846
        }
1847

    
1848
        /*
1849
         * (non-Javadoc)
1850
         * @see org.gvsig.fmap.raster.layers.FLyrRasterSE#isActionEnabled(int)
1851
         */
1852
        public boolean isActionEnabled(int action) {
1853
                switch (action) {
1854
                        case IRasterLayerActions.ZOOM_PIXEL_RESOLUTION:
1855
                        case IRasterLayerActions.FLYRASTER_BAR_TOOLS:
1856
                        case IRasterLayerActions.BANDS_FILE_LIST:
1857
                        case IRasterLayerActions.COLOR_TABLE:
1858
                        case IRasterLayerActions.GEOLOCATION:
1859
                        case IRasterLayerActions.PANSHARPENING:
1860
                                return false;
1861
                }
1862

    
1863
                return super.isActionEnabled(action);
1864
        }
1865

    
1866
        /*
1867
         * (non-Javadoc)
1868
         * @see org.gvsig.fmap.raster.layers.FLyrRasterSE#getLegend()
1869
         */
1870
        public ILegend getLegend() {
1871
                return null;
1872
        }
1873

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

    
1889
        /*
1890
         * (non-Javadoc)
1891
         * @see org.gvsig.fmap.raster.layers.FLyrRasterSE#overviewsSupport()
1892
         */
1893
        public boolean overviewsSupport() {
1894
                return false;
1895
        }
1896

    
1897
        protected void updateDrawVersion() {
1898
                if (this.disableUpdateDrawVersion != null){
1899

    
1900
                        Thread curThread = Thread.currentThread();
1901

    
1902
                        Thread aThread;
1903

    
1904
                        Iterator iter = this.disableUpdateDrawVersion.iterator();
1905
                        while (iter.hasNext()){
1906
                                aThread = (Thread) ((WeakReference)iter.next()).get();
1907
                                if (aThread == null){
1908
                                        iter.remove();
1909
                                } else if(aThread.equals(curThread)){
1910
                                        return;
1911
                                }
1912
                        }
1913
                }
1914
//                Exception ex = new Exception();
1915
//                ex.printStackTrace();
1916
                super.updateDrawVersion();
1917
        }
1918

    
1919
        protected void disableUpdateDrawVersion(){
1920
                if (this.disableUpdateDrawVersion == null){
1921
                        this.disableUpdateDrawVersion = new ArrayList();
1922
                }
1923
                this.disableUpdateDrawVersion.add(new WeakReference(Thread.currentThread()));
1924
        }
1925

    
1926
        protected void enableUpdateDrawVersion(){
1927
                if (this.disableUpdateDrawVersion == null){
1928
                        return;
1929
                }
1930

    
1931
                Thread curThread = Thread.currentThread();
1932

    
1933
                Thread aThread;
1934

    
1935

    
1936
                Iterator iter = this.disableUpdateDrawVersion.iterator();
1937
                while (iter.hasNext()){
1938
                        aThread = (Thread) ((WeakReference)iter.next()).get();
1939
                        if (aThread == null){
1940
                                iter.remove();
1941
                        } else if(aThread.equals(curThread)){
1942
                                iter.remove();
1943
                                break;
1944
                        }
1945
                }
1946

    
1947
        }
1948

    
1949
}