Statistics
| Revision:

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

History | View | Annotate | Download (61 KB)

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

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

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

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

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

    
121

    
122

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

    
160
    public URL                                                         host;
161
    public String                                                 m_Format;
162

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

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

    
198
        }
199

    
200
        public FLyrWMS(){
201
                super();
202
        }
203

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

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

    
232
                        WMSLayerNode wmsNode = drv.getLayer(sLayer);
233

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

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

    
266

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

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

    
296
            return (String)formats.get(0);
297
        }
298

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

    
319

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

    
330
                // Full extent
331
                xml.putProperty("fullExtent", StringUtilities.rect2String(fullExtent));
332

    
333
                // Host
334
                xml.putProperty("host", host.toExternalForm());
335

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

    
340
                // Part of the query containing the layer names
341
                xml.putProperty("layerQuery", layerQuery);
342

    
343
                // Format
344
                xml.putProperty("format", m_Format);
345

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

    
355
        // Transparency
356
        xml.putProperty("wms_transparency", wmsTransparency);
357

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

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

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

    
396
        // Queryable
397
        xml.putProperty("queryable", queryable);
398

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

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

    
423
                try {
424
                        host = new URL(xml.getStringProperty("host"));
425
                } catch (MalformedURLException e) {
426
                        throw new XMLException(e);
427
                }
428

    
429
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
430
                layerQuery = xml.getStringProperty("layerQuery");
431
                m_Format = xml.getStringProperty("format");
432
                m_SRS = xml.getStringProperty("srs");
433
        }
434

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

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

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

    
461
                // Part of the query containing the layer names
462
                layerQuery = xml.getStringProperty("layerQuery");
463

    
464
                // Format
465
                m_Format = xml.getStringProperty("format");
466

    
467
                // SRS
468
                m_SRS = xml.getStringProperty("srs");
469

    
470
                String claseStr = StatusLayerRaster.defaultClass;
471
                if (xml.contains("raster.class")) {
472
                        claseStr = xml.getStringProperty("raster.class");
473
                }
474

    
475
                // Transparency
476
        if (xml.contains("wms_transparency"))
477
            wmsTransparency = xml.getBooleanProperty("wms_transparency");
478

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

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

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

    
499
                dimensions.add(dims[i]);
500
            }
501
        }
502

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

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

    
518
        // fixedSize
519
        if (xml.contains("fixedSize")) {
520
                fixedSize = new Dimension(xml.getIntProperty("fixedWidth"),
521
                                                  xml.getIntProperty("fixedHeight"));
522
        }
523

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

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

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

    
579
                                int col = (int) p.getX() / maxTilePrintWidth;
580
                                int row = (int) p.getY() / maxTilePrintHeight;
581
                                int tileIndex = (row*nCols) + col;
582

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

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

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

    
666
                }
667
                catch (NoninvertibleTransformException e) {
668
                        NotificationManager.addError("NotinvertibleTransform", e);
669
                }
670
                return null;
671
        }
672
        
673
        /**
674
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent()
675
         */
676
        public Rectangle2D getFullExtent() {
677
                return fullExtent;
678
        }
679

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

    
701

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

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

    
770
        /**
771
         * Acciones que se realizan despu?s de asignar la fuente de datos a 
772
         * la capa raster.
773
         * 
774
         * @throws LoadLayerException
775
         */
776
        private void initializeRasterLayer(MultiRasterDataset[][] datasets, IBuffer[][] buf) throws LoadLayerException {
777
                if(this.filterList != null)
778
                        getRender().setFilterList(filterList);
779
                if(this.transparency != null)
780
                        getRender().setLastTransparency(transparency);
781
                if(this.renderBands != null)
782
                        getRender().setRenderBands(renderBands);
783
                if(datasets != null) {
784
                        String[][] names = new String[datasets.length][datasets[0].length];
785
                        for (int i = 0; i < datasets.length; i++) 
786
                                for (int j = 0; j < datasets[i].length; j++) 
787
                                        names[i][j] = datasets[i][j].getDataset(0)[0].getFName();
788
                        super.setLoadParams(names);                        
789
                }
790
                super.init();
791
                if(buf != null) {
792
                        int drawablesBandCount = layerRaster.getDataSource().getBands().getDrawableBandsCount();
793
                        IBuffer buff = ((CompositeDataset)dataset).generateBuffer(buf, drawablesBandCount);
794
                        getRender().setLastRenderBuffer(buff);
795
                }
796
        }
797
        
798
        private void drawFixedSize(Graphics2D g, ViewPort vp, Cancellable cancel, double scale) throws ReadDriverException, LoadLayerException {
799
                callCount++; // mess code, it is not unusual a wms server to response an error which is completely
800
                                         // temporal and the response is available if we retry requesting.
801
                                         //
802

    
803

    
804
                // This is the extent that will be requested
805
                Rectangle2D bBox = getFullExtent();
806
                MyCancellable c = new MyCancellable(cancel);
807

    
808
                try {
809
                        wmsStatus.setExtent( bBox );
810
                        wmsStatus.setFormat( m_Format );
811
                        wmsStatus.setHeight( fixedSize.height );
812
                        wmsStatus.setWidth( fixedSize.width );
813
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
814
                        wmsStatus.setSrs(m_SRS);
815
                        wmsStatus.setStyles(styles);
816
                        wmsStatus.setDimensions(dimensions);
817
                        wmsStatus.setTransparency(wmsTransparency);
818
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
819
                        File f = getDriver().getMap(wmsStatus, c);
820
                        if (f == null)
821
                                return;
822
                        String nameWorldFile = f.getPath() + getExtensionWorldFile();
823
                        com.iver.andami.Utilities.createTemp(nameWorldFile, this.getDataWorldFile(bBox, fixedSize));
824

    
825
                        IStatusRaster status = getStatus();
826
                        if(status!=null && firstLoad){
827
                                status.applyStatus(this);
828
                                firstLoad = false;
829
                        }
830

    
831
                        // And finally, obtain the extent intersecting the view and the BBox
832
                        // to draw to.
833
                        Rectangle2D extent = new Rectangle2D.Double();
834
                        Rectangle2D.intersect(vp.getAdjustedExtent(), bBox, extent);
835

    
836
                        ViewPortData vpData = new ViewPortData(
837
                                vp.getProjection(), new Extent(extent), fixedSize );
838
                        vpData.setMat(vp.getAffineTransform());
839

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

    
884
                                if (callCount == 1) { // mess code
885
                                        ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
886
                                        type.setLayerName(getName());
887
                                        try {
888
                                                type.setDriverName("WMS Driver");
889
                                        } catch (Exception e1) {
890
                                        }
891
                                        type.setHost(host);
892
                                        throw new ConnectionErrorLayerException(getName(),e);
893
//        azabala        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
894
                                } // mess code
895

    
896

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

    
918

    
919
                                } // mess code
920
                        }
921
                }
922
                callCount--; // mess code
923
        }
924

    
925
        /**
926
         * Carga y dibuja el raster usando la librer?a
927
         * @param filePath Ruta al fichero en disco
928
         * @param g Graphics2D
929
         * @param vp ViewPort
930
         * @param scale Escala para el draw
931
         * @param cancel Cancelaci?n para el draw
932
         * @throws ReadDriverException
933
         * @throws LoadLayerException
934
         */
935
        private void rasterProcess(String filePath, Graphics2D g, ViewPort vp, double scale, Cancellable cancel) throws ReadDriverException, LoadLayerException {
936
                //Cerramos el dataset asociado a la capa si est? abierto. 
937
                if(layerRaster != null) {
938
                        layerRaster.setRemoveRasterFlag(true);
939
                        layerRaster.getDataSource().close();
940
                }
941
                
942
                //Cargamos el dataset con el raster de disco. 
943
                layerRaster = FLyrRasterSE.createLayer("", filePath, vp.getProjection());
944
                layerRaster.getRender().setBufferFactory(layerRaster.getBufferFactory());
945
                                
946
                //Obtenemos la tabla de color del raster abierto ya que se le va a sustituir la lista
947
                //de filtros y el de tabla de color no queremos sustituirlo. 
948
                RasterFilterList rasterFilterList = layerRaster.getRender().getFilterList();
949
                ColorTableFilter ct = (ColorTableFilter)rasterFilterList.getFilterByBaseClass(ColorTableFilter.class);
950
                Object param = null;
951
                if(ct != null)
952
                        param = ct.getParam("colorTable");
953
                        
954
                //En caso de cargar un proyecto con XMLEntity se crean los filtros 
955
                if(filterArguments != null) {
956
                        RasterFilterList fl = new RasterFilterList();
957
                        fl.addParam("IStatistics", layerRaster.getDataSource().getStatistics());
958
                        fl.addParam("MultiRasterDataset", layerRaster.getDataSource());
959
                        fl.setInitDataType(layerRaster.getDataType()[0]);
960
                        RasterFilterListManager filterListManager = new RasterFilterListManager(fl);
961
                        filterListManager.createFilterListFromStrings(filterArguments);
962
                        filterArguments = null;
963
                        filterList = fl;
964
                }
965
                                
966
                //Como el raster se carga a cada zoom el render se crea nuevamente y la lista de
967
                //filtros siempre estar? vacia a cada visualizaci?n. Para evitarlo tenemos que
968
                //guardar la lista de filtro aplicada en la visualizaci?n anterior.
969
                if(this.filterList != null) {
970
                        //Si ten?a tabla de color le asignamos la original
971
                        if(param != null && param instanceof GridPalette) {
972
                                this.filterList.remove(ColorTableFilter.class);
973
                                RasterFilterListManager filterManager = new RasterFilterListManager(filterList);
974
                                ColorTableListManager ctm = new ColorTableListManager(filterManager);
975
                                ctm.addColorTableFilter((GridPalette)param);
976
                                filterList.move(ColorTableFilter.class, 0);
977
                                filterList.controlTypes();
978
                        }
979
                        layerRaster.getRender().setFilterList(filterList);
980
                }
981
                if(this.transparency != null)
982
                        layerRaster.getRender().setLastTransparency(transparency);
983
                if(this.renderBands != null)
984
                        layerRaster.getRender().setRenderBands(renderBands);
985
                
986
                //Dibujamos
987
                layerRaster.draw(null, g, vp, cancel, scale);
988
                                
989
                //La primera vez asignamos la lista de filtros asociada al renderizador. Guardamos una referencia
990
                //en esta clase para que a cada zoom no se pierda.
991
                if (this.filterList == null)
992
                        filterList = layerRaster.getRender().getFilterList();
993
                if (this.transparency == null)
994
                        transparency = layerRaster.getRender().getLastTransparency();
995
                if (this.renderBands == null)
996
                        renderBands = layerRaster.getRender().getRenderBands();
997
                
998
        }
999

    
1000
        /*
1001
         * (non-Javadoc)
1002
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderFilterList()
1003
         */
1004
        public RasterFilterList getRenderFilterList(){
1005
                return (filterList != null) ? filterList : getRender().getFilterList();
1006
        }
1007
        
1008
        /*
1009
         * (non-Javadoc)
1010
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderTransparency()
1011
         */
1012
        public GridTransparency getRenderTransparency() {
1013
                return (transparency != null) ? transparency : getRender().getLastTransparency();
1014
        }
1015
        
1016
        /*
1017
         * (non-Javadoc)
1018
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getRenderBands()
1019
         */
1020
        public int[] getRenderBands() {
1021
                return (renderBands != null) ? renderBands : getRender().getRenderBands();
1022
        }
1023
        
1024
        /**
1025
         * This is the method used to draw a tile in a WMS mosaic layer.
1026
         * @throws LoadLayerException
1027
         * @throws ReadDriverException
1028
         */
1029
        private void drawTile(Graphics2D g, ViewPort vp, Cancellable cancel, int tile, double scale) throws LoadLayerException, ReadDriverException {
1030
                callCount++;
1031
                // Compute the query geometry
1032
                // 1. Check if it is within borders
1033
                Rectangle2D extent = getFullExtent();
1034
        if ((vp.getAdjustedExtent().getMinX() > extent.getMaxX()) ||
1035
                (vp.getAdjustedExtent().getMinY() > extent.getMaxY()) ||
1036
                (vp.getAdjustedExtent().getMaxX() < extent.getMinX()) ||
1037
                (vp.getAdjustedExtent().getMaxY() < extent.getMinY())) {
1038
            return;
1039
        }
1040

    
1041
        // 2. Compute extent to be requested.
1042
        Rectangle2D bBox = new Rectangle2D.Double();
1043
        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
1044

    
1045
        // 3. Compute size in pixels
1046
        double scalex = vp.getAffineTransform().getScaleX();
1047
        double scaley = vp.getAffineTransform().getScaleY();
1048
        int wImg = (int) Math.ceil(Math.abs(bBox.getWidth() * scalex) + 1);
1049
        int hImg = (int) Math.ceil(Math.abs(bBox.getHeight() * scaley) + 1);
1050

    
1051
        Dimension sz = new Dimension(wImg, hImg);
1052

    
1053
        if ((wImg <= 0) || (hImg <= 0)) {
1054
            return;
1055
        }
1056
        MyCancellable c = new MyCancellable(cancel);
1057

    
1058
                try {
1059
//                        wImg = vp.getImageWidth();
1060
//                        hImg = vp.getImageHeight();
1061
                        sz = new Dimension(wImg, hImg);
1062
                        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
1063

    
1064

    
1065
                        wmsStatus.setExtent( bBox );
1066
                        wmsStatus.setFormat(m_Format);
1067
                        wmsStatus.setHeight( hImg );
1068
                        wmsStatus.setWidth( wImg );
1069
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
1070
                        wmsStatus.setSrs(m_SRS);
1071
                        wmsStatus.setStyles(styles);
1072
                        wmsStatus.setDimensions(dimensions);
1073
                        wmsStatus.setTransparency(wmsTransparency);
1074
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
1075

    
1076
                        // begin patch; Avoid to request too small tiles.
1077
                        // This generally occurs when printing
1078

    
1079
                        if (wImg < minTilePrintWidth) {
1080
                                double wScale = (double) minTilePrintWidth / wImg;
1081
                                wmsStatus.setWidth(minTilePrintWidth);
1082
                                Rectangle2D sExtent = wmsStatus.getExtent();
1083
                                Point2D initialPoint = new Point2D.Double(sExtent.getX(), sExtent.getY());
1084
                                sExtent.setRect(sExtent.getX()*wScale, sExtent.getY(), sExtent.getWidth()*wScale, sExtent.getHeight());
1085
                                if (!bBox.contains(initialPoint)) {
1086
                                        sExtent.setRect(sExtent.getX() - initialPoint.getX(), sExtent.getY(), sExtent.getWidth(), sExtent.getHeight());
1087
                                }
1088
                        }
1089

    
1090
                        if (hImg < minTilePrintHeight) {
1091
                                double hScale = (double) minTilePrintHeight / hImg;
1092
                                wmsStatus.setHeight(minTilePrintHeight);
1093
                                Rectangle2D sExtent = wmsStatus.getExtent();
1094
                                Point2D initialPoint = new Point2D.Double(sExtent.getX(), sExtent.getY());
1095
                                sExtent.setRect(sExtent.getX(), sExtent.getY()*hScale, sExtent.getWidth(), sExtent.getHeight()*hScale);
1096
                                if (!bBox.contains(initialPoint)) {
1097
                                        sExtent.setRect(sExtent.getX(), sExtent.getY() - initialPoint.getY(), sExtent.getWidth(), sExtent.getHeight());
1098
                                }
1099
                        }
1100

    
1101
                        // end patch
1102
                        File f = getDriver().getMap(wmsStatus, c);
1103
                        if (f == null)
1104
                                return;
1105
                        String nameWordFile = f.getPath() + getExtensionWorldFile();
1106
                        com.iver.andami.Utilities.createTemp(nameWordFile, this.getDataWorldFile(bBox, sz));
1107

    
1108
                        ViewPortData vpData = new ViewPortData(
1109
                                vp.getProjection(), new Extent(bBox), sz );
1110
                        vpData.setMat(vp.getAffineTransform());
1111

    
1112
                        String filePath = f.getAbsolutePath();
1113
                        visualStatus.fileNames[tile] = filePath;
1114
                        rasterProcess(filePath, g, vp, scale, cancel);
1115

    
1116
                } catch (ValidationException e) {
1117
                //azabala
1118
//                        if (!c.isCanceled())
1119
//                                throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
1120

    
1121
                        if (!c.isCanceled())
1122
                        {
1123
//                                UnknownResponseFormatExceptionType type =
1124
//                                        new UnknownResponseFormatExceptionType();
1125
//                                type.setLayerName(getName());
1126
//                                try {
1127
//                                        type.setDriverName("WMS Driver");
1128
//                                } catch (Exception e1) {
1129
//                                        e1.printStackTrace();
1130
//                                }
1131
//                                type.setFormat(m_Format);
1132
//                                type.setHost(host);
1133
//                                type.setProtocol("WMS");
1134
                                LoadLayerException exception = new LoadLayerException(getName(),e);
1135
                                throw exception;
1136
                        }
1137
//                } catch (UnsupportedVersionLayerException e) {
1138
//
1139
////                        if (!c.isCanceled())
1140
////                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
1141
//
1142
//                        if (!c.isCanceled()){
1143
//                                UnsuportedProtocolVersionExceptionType type =
1144
//                                        new UnsuportedProtocolVersionExceptionType();
1145
//                                type.setLayerName(getName());
1146
//                                try {
1147
//                                        type.setDriverName("WMS Driver");
1148
//                                } catch (Exception ex){
1149
//                                }
1150
//                                type.setUrl(host);
1151
//                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e, type);
1152
//                        }
1153
//
1154
                } catch (IOException e) {
1155
                        /*azabala
1156
                        if (!c.isCanceled())
1157
                                if (callCount<MAX_RETRY_TIMES) {
1158
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null);
1159
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error
1160
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0)
1161
                                        drawTile(g, vp, cancel);
1162
                                }
1163
                                if (callCount == 1) {
1164
                                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
1165
                                }
1166
                        */
1167
                        if (!c.isCanceled()){
1168
                                if (callCount<MAX_RETRY_TIMES) { // mess code
1169
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
1170
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
1171
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
1172

    
1173
                                        drawFixedSize(g, vp, cancel, scale); // mess code
1174
                                } // mess code
1175
                        }
1176
                        if (callCount == 1) { // mess code
1177
//                                ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
1178
//                                type.setLayerName(getName());
1179
//                                try {
1180
//                                        type.setDriverName("WMS Driver");
1181
//                                } catch (Exception e1) {}
1182
//                                type.setHost(host);
1183
                                throw new ConnectionErrorLayerException(getName(),e);
1184
                        }//if
1185
                } catch (WMSException e) {
1186
                        /*azabala
1187
                        if (!c.isCanceled()) {
1188
                                if (callCount<MAX_RETRY_TIMES) {
1189
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawTile() ] Failed in trying " + callCount + "/" + MAX_RETRY_TIMES +" \n", null);
1190
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error
1191
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0)
1192
                                        drawTile(g, vp, cancel);
1193
                                }
1194
                                if (callCount == 1) {
1195
                                        if (!isPrinting) {
1196
                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
1197
                                                this.setVisible(false);
1198
                                        }
1199
                                }
1200
                        }
1201
                        */
1202
                        if (!c.isCanceled()) {
1203
                                if (callCount<MAX_RETRY_TIMES) { // mess code
1204
                                        Logger.getAnonymousLogger().warning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n"); // mess code
1205
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
1206
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
1207
                                        drawTile(g, vp, cancel, tile, scale);
1208
                                } // mess code
1209
                                if (callCount == 1) { // mess code
1210
//                azabala                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
1211
                                        WMSDriverExceptionType type = new WMSDriverExceptionType();
1212
                                        type.setLayerName(getName());
1213
                                        try {
1214
                                                type.setDriverName("WMS Driver");
1215
                                        } catch (Exception e1) {
1216
                                        }
1217
                                        type.setWcsStatus(this.wmsStatus);
1218
                                        if (!isPrinting)
1219
                                                this.setVisible(false);
1220
                                        throw new LoadLayerException(getName(),e);
1221

    
1222

    
1223
                                } //if
1224
                        }//if
1225
                }//catch
1226
                callCount--;
1227
        }
1228

    
1229
        /**
1230
         * Obtiene la extensi?n del fichero de georreferenciaci?n
1231
         * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
1232
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
1233
         */
1234
        private String getExtensionWorldFile(){
1235
                String extWorldFile = ".wld";
1236
            if(m_Format.equals("image/tif") || m_Format.equals("image/tiff"))
1237
                    extWorldFile = ".tfw";
1238
            if(m_Format.equals("image/jpeg"))
1239
                    extWorldFile = ".jpgw";
1240
            return extWorldFile;
1241
        }
1242

    
1243
        /**
1244
         * Calcula el contenido del fichero de georreferenciaci?n de una imagen.
1245
         * @param bBox Tama?o y posici?n de la imagen (en coordenadas de usuario)
1246
         * @param sz Tama?o de la imagen en pixeles.
1247
         * @return el 'WorldFile', como String.
1248
         * @throws IOException
1249
         */
1250
        public String getDataWorldFile(Rectangle2D bBox, Dimension sz) throws IOException {
1251
                StringBuffer data = new StringBuffer();
1252
            data.append((bBox.getMaxX() - bBox.getMinX())/(sz.getWidth() - 1)+"\n");
1253
            data.append("0.0\n");
1254
            data.append("0.0\n");
1255
            data.append("-"+(bBox.getMaxY() - bBox.getMinY())/(sz.getHeight() - 1)+"\n");
1256
            data.append(""+bBox.getMinX()+"\n");
1257
            data.append(""+bBox.getMaxY()+"\n");
1258
            return data.toString();
1259
        }
1260

    
1261
        /**
1262
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D,
1263
         *                 com.iver.cit.gvsig.fmap.ViewPort,
1264
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
1265
         */
1266
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet properties)
1267
                throws ReadDriverException {
1268
                if (isVisible() && isWithinScale(scale)){
1269
                isPrinting = true;
1270
                if (!mustTilePrint) {
1271
                        draw(null, g, viewPort, cancel,scale);
1272
                } else {
1273
                // Para no pedir imagenes demasiado grandes, vamos
1274
                // a hacer lo mismo que hace EcwFile: chunkear.
1275
                // Llamamos a drawView con cuadraditos m?s peque?os
1276
                // del BufferedImage ni caso, cuando se imprime viene con null
1277

    
1278
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
1279
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
1280
                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
1281
                            // Parte que dibuja
1282
                            try {
1283
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
1284
                                drawTile(g, vp, cancel, tileNr, scale);
1285
                                } catch (NoninvertibleTransformException e) {
1286
                                        e.printStackTrace();
1287
                                } catch (LoadLayerException e) {
1288
                                        // TODO Auto-generated catch block
1289
                                        e.printStackTrace();
1290
                                }
1291
                }
1292
                }
1293
            isPrinting = false;
1294
                }
1295
        }
1296

    
1297
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale)
1298
                throws ReadDriverException {
1299
                draw(null, g, viewPort, cancel,scale);
1300
        }
1301

    
1302
        /**
1303
         * Devuelve el FMapWMSDriver.
1304
         *
1305
         * @return FMapWMSDriver
1306
         *
1307
         * @throws IllegalStateException
1308
         * @throws ValidationException
1309
         * @throws UnsupportedVersionLayerException
1310
         * @throws IOException
1311
         */
1312
        private FMapWMSDriver getDriver()
1313
                throws IllegalStateException, ValidationException,
1314
                        UnsupportedVersionLayerException, IOException {
1315
                return FMapWMSDriverFactory.getFMapDriverForURL(host);
1316
        }
1317

    
1318
        /**
1319
         * Devuelve el FMapWMSDriver.
1320
         *
1321
         * @return FMapWMSDriver
1322
         *
1323
         * @throws IllegalStateException
1324
         * @throws ValidationException
1325
         * @throws UnsupportedVersionLayerException
1326
         * @throws IOException
1327
         */
1328
        public void setDriver(FMapWMSDriver drv) {
1329
                wms = drv;
1330
        }
1331

    
1332
        /**
1333
         * Devuelve el URL.
1334
         *
1335
         * @return URL.
1336
         */
1337
        public URL getHost() {
1338
                return host;
1339
        }
1340

    
1341
        /**
1342
         * Inserta el URL.
1343
         *
1344
         * @param host URL.
1345
         */
1346
        public void setHost(URL host) {
1347
                this.host = host;
1348
        }
1349

    
1350
        /**
1351
         * Devuelve la informaci?n de la consulta.
1352
         *
1353
         * @return String.
1354
         */
1355
        public String getInfoLayerQuery() {
1356
                return infoLayerQuery;
1357
        }
1358

    
1359
        /**
1360
         * Inserta la informaci?n de la consulta.
1361
         *
1362
         * @param infoLayerQuery String.
1363
         */
1364
        public void setInfoLayerQuery(String infoLayerQuery) {
1365
                this.infoLayerQuery = infoLayerQuery;
1366
        }
1367

    
1368
        /**
1369
         * Devuelve la consulta.
1370
         *
1371
         * @return String.
1372
         */
1373
        public String getLayerQuery() {
1374
                return layerQuery;
1375
        }
1376

    
1377
        /**
1378
         * Inserta la consulta.
1379
         *
1380
         * @param layerQuery consulta.
1381
         */
1382
        public void setLayerQuery(String layerQuery) {
1383
                this.layerQuery = layerQuery;
1384
        }
1385

    
1386
        /**
1387
         * Devuelve el formato.
1388
         *
1389
         * @return Formato.
1390
         */
1391
        public String getFormat() {
1392
                return m_Format;
1393
        }
1394

    
1395
        /**
1396
         * Inserta el formato.
1397
         *
1398
         * @param format Formato.
1399
         */
1400
        public void setFormat(String format) {
1401
                m_Format = format;
1402
        }
1403

    
1404
        /**
1405
         * Devuelve el SRS.
1406
         *
1407
         * @return SRS.
1408
         */
1409
        public String getSRS() {
1410
                return m_SRS;
1411
        }
1412

    
1413
        /**
1414
         * Inserta el SRS.
1415
         *
1416
         * @param m_srs SRS.
1417
         */
1418
        public void setSRS(String m_srs) {
1419
                m_SRS = m_srs;
1420
                setProjection(CRSFactory.getCRS(getSRS()));
1421
        }
1422

    
1423
        /**
1424
         * Inserta la extensi?n total de la capa.
1425
         *
1426
         * @param fullExtent Rect?ngulo.
1427
         */
1428
        public void setFullExtent(Rectangle2D fullExtent) {
1429
                this.fullExtent = fullExtent;
1430
        }
1431

    
1432
        public HashMap getProperties() {
1433
                HashMap info = new HashMap();
1434
        String[] layerNames = getLayerQuery().split(",");
1435
        Vector layers = new Vector(layerNames.length);
1436
        try {
1437
            if(getDriver().connect(null)){
1438
                for (int i = 0; i < layerNames.length; i++) {
1439
                    layers.add(i, getDriver().getLayer(layerNames[i]));
1440
                }
1441
                info.put("name", getName());
1442
                info.put("selectedLayers", layers);
1443
                info.put("host", getHost());
1444
                info.put("srs", getSRS());
1445
                info.put("format", getFormat());
1446
                info.put("wmsTransparency", new Boolean(wmsTransparency));
1447
                info.put("styles", styles);
1448
                info.put("dimensions", dimensions);
1449
                info.put("fixedSize", fixedSize);
1450
                return info;
1451
            }
1452
        } catch (Exception e) {
1453
            e.printStackTrace();
1454
        }
1455
        return null;
1456
        }
1457

    
1458
        public double getMaxX() {
1459
                return visualStatus.maxX;
1460
        }
1461

    
1462
        public double getMaxY() {
1463
                return visualStatus.maxY;
1464
        }
1465

    
1466
        public double getMinX() {
1467
                return visualStatus.minX;
1468
        }
1469

    
1470
        public double getMinY() {
1471
                return visualStatus.minY;
1472
        }
1473

    
1474
    /**
1475
     * @return Returns the wmsTransparency.
1476
     */
1477
    public boolean isWmsTransparent() {
1478
        return wmsTransparency;
1479
    }
1480

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

    
1488
     /**
1489
     * @param styles
1490
     */
1491
    public void setStyles(Vector styles) {
1492
            this.styles = styles;
1493
    }
1494

    
1495
    /**
1496
     * Sets the dimension vector that is a list of key-value pairs containing
1497
     * the name of the dimension and the value for it
1498
     * @param dimensions
1499
     */
1500
    public void setDimensions(Vector dimensions) {
1501
        this.dimensions = dimensions;
1502
    }
1503

    
1504
    /**
1505
     * Sets the set of URLs that should be accessed for each operation performed
1506
     * to the server.
1507
     *
1508
     * @param onlineResources
1509
     */
1510
        public void setOnlineResources(Hashtable onlineResources) {
1511
                this.onlineResources = onlineResources;
1512
        }
1513

    
1514
    /**
1515
     * Gets the URL that should be accessed for an operation performed
1516
     * to the server.
1517
     *
1518
     * @param onlineResources
1519
     */
1520
        public String getOnlineResource(String operation) {
1521
                return ((String) onlineResources.get(operation));
1522
        }
1523

    
1524
        /**
1525
         * When a server is not fully featured and it only can serve constant map
1526
         * sizes this value must be set. It expresses the size in pixels (width, height)
1527
         * that the map will be requested.
1528
         * @param Dimension sz
1529
         */
1530
        public void setFixedSize(Dimension sz) {
1531
                fixedSize = sz;
1532
        }
1533

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

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

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

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

    
1586
                                        // <OnlineResource>
1587
                                        xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1588
                                        xmlAttrs.put(WebMapContextTags.XLINK_HREF, getHost().toString());
1589
                                        xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1590
                                        xmlAttrs.clear();
1591
                                        // </OnlineResource>
1592

    
1593
                                xml.closeTag();
1594
                                // </Server>
1595

    
1596
                                // <Name>
1597
                                xml.writeTag(WebMapContextTags.NAME, layer.getName().trim());
1598
                                // </Name>
1599

    
1600
                                // <Title>
1601
                                xml.writeTag(WebMapContextTags.TITLE, layer.getTitle().trim());
1602
                                //?xml.writeTag(WebMapContextTags.TITLE, getName().trim());
1603
                                // </Title>
1604

    
1605
                                // <Abstract>
1606
                                if (layer.getAbstract() != null)
1607
                                        xml.writeTag(WebMapContextTags.ABSTRACT, layer.getAbstract());
1608
                                // </Abstract>
1609

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

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

    
1634
                                // <StyleList>
1635
                                xml.openTag(WebMapContextTags.STYLE_LIST);
1636

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

    
1646
                                                                // <Name>
1647
                                                                xml.writeTag(WebMapContextTags.NAME, st.name);
1648
                                                                // </Name>
1649

    
1650
                                                                // <Title>
1651
                                                                xml.writeTag(WebMapContextTags.TITLE, st.title);
1652
                                                                // </Title>
1653

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

    
1661
                                                }
1662

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

    
1673
                                                        // <Title>
1674
                                                        xml.writeTag(WebMapContextTags.TITLE, "default");
1675
                                                        // </Title>
1676

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

    
1712
        public ImageIcon getTocImageIcon() {
1713
                return new ImageIcon(PluginServices.getPluginServices("com.iver.cit.gvsig.wms").getClassLoader().getResource("images/icoLayer.png"));
1714
        }
1715

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

    
1725
        /*
1726
         *  (non-Javadoc)
1727
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1728
         */
1729
        public boolean isTiled() {
1730
                return mustTileDraw;
1731
        }
1732

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

    
1753
        public String getPathImage() {
1754
                try {
1755
                        File legend = getDriver().getLegendGraphic(wmsStatus, layerQuery, null);
1756
                        return legend.getAbsolutePath();
1757
                }catch(Exception e){
1758
                        e.printStackTrace();
1759
                        return null;
1760
                }
1761
        }
1762

    
1763
        /* (non-Javadoc)
1764
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#newComposedLayer()
1765
         */
1766
        public ComposedLayer newComposedLayer() {
1767
                Preferences prefs = Preferences.userRoot().node("gvsig.wms");
1768
                 
1769
                String str = prefs.get("useComposedLayer","false");
1770
                Boolean useComposedLayer = Boolean.FALSE;
1771
                try {
1772
                        useComposedLayer = Boolean.valueOf(str);
1773
                } catch (Exception e) {
1774
                        
1775
                }
1776
                if (useComposedLayer.booleanValue()) {
1777
                        return new ComposedLayerWMS();
1778
                } else {
1779
                        return null;
1780
                }
1781
        }
1782

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

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

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

    
1864
                return super.isActionEnabled(action);
1865
        }
1866
    
1867
        /*
1868
         * (non-Javadoc)
1869
         * @see org.gvsig.fmap.raster.layers.FLyrRasterSE#getLegend()
1870
         */
1871
        public ILegend getLegend() {
1872
                return null;
1873
        }
1874
        
1875
        /*
1876
         * (non-Javadoc)
1877
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
1878
         */
1879
        public int[] getDataType(){
1880
                try {
1881
                        return dataset.getDataType();
1882
                } catch (NullPointerException e) {
1883
                        if(layerRaster != null)
1884
                                return layerRaster.getDataType();
1885
                        else
1886
                                return new int[]{IBuffer.TYPE_UNDEFINED};
1887
                }
1888
        }
1889
}