Statistics
| Revision:

svn-gvsig-desktop / branches / MULTITHREADING_DEVELOPMENT / extensions / extWMS / src / com / iver / cit / gvsig / fmap / layers / FLyrWMS.java @ 5327

History | View | Annotate | Download (42.7 KB)

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

    
43
import java.awt.Component;
44
import java.awt.Dimension;
45
import java.awt.Graphics2D;
46
import java.awt.Point;
47
import java.awt.Rectangle;
48
import java.awt.geom.AffineTransform;
49
import java.awt.geom.NoninvertibleTransformException;
50
import java.awt.geom.Point2D;
51
import java.awt.geom.Rectangle2D;
52
import java.awt.image.BufferedImage;
53
import java.awt.image.DataBuffer;
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.TimerTask;
66
import java.util.Vector;
67

    
68
import javax.swing.JOptionPane;
69
import javax.swing.SwingUtilities;
70

    
71
import org.cresques.geo.ViewPortData;
72
import org.cresques.io.GdalFile;
73
import org.cresques.io.GeoRasterFile;
74
import org.cresques.io.raster.RasterFilterStack;
75
import org.cresques.io.raster.RasterFilterStackManager;
76
import org.cresques.px.Extent;
77
import org.cresques.px.PxRaster;
78
import org.exolab.castor.xml.ValidationException;
79
import org.gvsig.remoteClient.utils.Utilities;
80
import org.gvsig.remoteClient.wms.WMSStatus;
81

    
82
import com.iver.andami.PluginServices;
83
import com.iver.andami.messages.NotificationManager;
84
import com.iver.cit.gvsig.fmap.DriverException;
85
import com.iver.cit.gvsig.fmap.ViewPort;
86
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
87
import com.iver.cit.gvsig.fmap.drivers.UnsupportedVersionException;
88
import com.iver.cit.gvsig.fmap.drivers.wms.ExperimentalAsynchronousFMapWMSDriver;
89
import com.iver.cit.gvsig.fmap.drivers.wms.FMapWMSDriver;
90
import com.iver.cit.gvsig.fmap.drivers.wms.FMapWMSDriverFactory;
91
import com.iver.cit.gvsig.fmap.drivers.wms.WMSException;
92
import com.iver.cit.gvsig.fmap.drivers.wms.WMSOperations;
93
import com.iver.cit.gvsig.fmap.layers.WMSLayerNode.FMapWMSStyle;
94
import com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint;
95
import com.iver.cit.gvsig.fmap.layers.layerOperations.StringXMLItem;
96
import com.iver.cit.gvsig.fmap.layers.layerOperations.XMLItem;
97
import com.iver.cit.gvsig.fmap.operations.Cancellable;
98
import com.iver.cit.gvsig.fmap.rendering.XmlBuilder;
99
import com.iver.cit.gvsig.wmc.WebMapContextTags;
100
import com.iver.utiles.StringUtilities;
101
import com.iver.utiles.XMLEntity;
102

    
103
/**
104
* FMap's WMS Layer class.
105
*
106
* @author Jaume Dominguez Faus
107
*                   Nacho Brodin
108
* 
109
*/
110
public class FLyrWMS extends FLyrDefault implements InfoByPoint, RasterOperations, WMSOperations {
111
        private boolean                                         isPrinting = false;
112
        private boolean                                         mustTileDraw = false;
113
        private boolean                                         mustTilePrint = true;
114
        private final int                                         maxTileDrawWidth = -1;
115
        private final int                                         maxTileDrawHeight = -1;
116
        private final int                                         maxTilePrintWidth = 1200;
117
        private final int                                         maxTilePrintHeight = 1200;
118
    
119
    public URL                                                         host;
120
    public String                                                 m_Format;
121
    
122
        private String                                                 m_SRS;
123
        private String                                                 layerQuery;
124
        private String                                                 infoLayerQuery;
125
//        private FMapWMSDriver                                 wms = null;
126
        private WMSStatus                                         wmsStatus = new WMSStatus();
127
        private Rectangle2D                                 fullExtent;
128
        private boolean                                                wmsTransparency;
129
    private Vector                                                 styles;
130
    private Vector                                                 dimensions;
131
        private StatusRasterInterface                status = null;
132
        private int                                                 posX = 0, posY = 0;
133
        private double                                                 posXWC = 0, posYWC = 0;
134
        private int                                                 r = 0, g = 0, b = 0;
135
        private GeoRasterFile                                 rasterFile = null;
136
        private PxRaster                                         raster = null;
137
        private RasterFilterStack                         filterStack = null;
138
        private boolean                                                firstLoad = false;
139
        private int                                                 transparency = -1;
140
        private int                                                 rband = 0, gband = 1, bband = 2;
141
        private RasterFilterStackManager        stackManager = null;
142
        private Hashtable                                         onlineResources = new Hashtable();
143
        private Dimension                                         fixedSize;
144
        private boolean                                         queryable = true;
145
        private VisualStatusWMS                                visualStatus = new VisualStatusWMS();
146
        
147
        public FLyrWMS(){
148
                super();
149
        }
150
        
151
        public FLyrWMS(Map args) throws DriverIOException{
152
                FMapWMSDriver drv = null;
153
                String host = (String)args.get("host");
154
                String sLayer = (String)args.get("layer");
155
                Rectangle2D fullExtent = (Rectangle2D)args.get("FullExtent");
156
                String sSRS = (String)args.get("SRS");
157
                String sFormat = (String)args.get("Format");
158
                String[] sLayers = sLayer.split(",");
159
                
160
                try {
161
                        this.setHost(new URL(host));
162
                } catch (MalformedURLException e) {
163
                        //e.printStackTrace();
164
                        throw new DriverIOException("Malformed host URL, '" + host + "' (" + e.toString() + ").");                        
165
                }
166
                try {
167
                        drv = this.getDriver();
168
                } catch (Exception e) {
169
                        // e.printStackTrace();
170
                        throw new DriverIOException("Can't get driver to host '" + host + "' (" + e.toString() + ").");                        
171
                }
172
                if( sFormat == null || sSRS == null || fullExtent == null ) {
173
                        if (!drv.connect())
174
                                throw new DriverIOException("Can't connect to host '" + host + "'."); 
175
                        
176
                        WMSLayerNode wmsNode = drv.getLayer(sLayer);
177
                                                        
178
                        if (wmsNode == null){
179
                                throw new DriverIOException("The server '" + host + "' doesn't has the layer '" + sLayer + "'.");
180
                        }                
181
                        if( sFormat == null ) {
182
                                sFormat = this.getGreatFormat(drv.getFormats());
183
                        }
184
                     if( sSRS == null ) {
185
                             sSRS = (String)wmsNode.getAllSrs().get(0);
186
                     }
187
                        if( fullExtent == null ) {
188
                                fullExtent = drv.getLayersExtent(sLayers,(String)wmsNode.getAllSrs().get(0));
189
                        }
190
                }
191
                
192
                                
193
                this.setFullExtent(fullExtent);
194
                this.setFormat(sFormat);
195
                this.setLayerQuery(sLayer);
196
                this.setInfoLayerQuery("");
197
                this.setSRS(sSRS);
198
                this.setName(sLayer);
199
        }
200
        
201
        /**
202
         * It choose the best format to load different maps if the server 
203
         * supports it. This format could be png, because it supports 
204
         * transparency.
205
         * @param formats
206
         * Arraywith all the formats supported by the server
207
         * @return
208
         * @author jorge piera llodra
209
         */        
210
        private String getGreatFormat(Vector formats){
211
            for (int i=0 ; i<formats.size() ; i++){
212
                String format = (String) formats.get(i);
213
                    if (format.equals("image/jpg")){
214
                    return format;
215
                    }
216
                    if (format.equals("image/jpeg")){
217
                    return format;
218
                    }
219
            }
220
                    
221
            return (String)formats.get(0);
222
        }
223
        
224
        /**
225
         * Clase que contiene los datos de visualizaci?n de WMS.
226
         * @author Nacho Brodin (brodin_ign@gva.es)
227
         */
228
        private class VisualStatusWMS{
229
                /**
230
                 * Ancho y alto de la imagen o del conjunto de tiles si los tiene. Coincide con 
231
                 * el ancho y alto del viewPort
232
                 */
233
                private        int                                                        width = 0, height = 0;
234
                private double                                                minX = 0D, minY = 0D, maxX = 0D, maxY = 0D;
235
                private int                                                 bandCount = 0;
236
                private int                                                        dataType = DataBuffer.TYPE_UNDEFINED;
237
        }
238
         
239

    
240
        /**
241
         * Devuelve el XMLEntity con la informaci?n necesaria para reproducir la
242
         * capa.
243
         *
244
         * @return XMLEntity.
245
         * @throws XMLException
246
         */
247
        public XMLEntity getXMLEntity() throws XMLException {
248
                XMLEntity xml = super.getXMLEntity();
249

    
250
                // Full extent
251
                xml.putProperty("fullExtent", StringUtilities.rect2String(fullExtent));
252
                
253
                // Host
254
                xml.putProperty("host", host.toExternalForm());
255
                
256
                // Part of the query that is not the host, or the
257
                // layer names, or other not listed bellow
258
                xml.putProperty("infoLayerQuery", infoLayerQuery);
259
                
260
                // Part of the query containing the layer names
261
                xml.putProperty("layerQuery", layerQuery);
262
                
263
                // Format
264
                xml.putProperty("format", m_Format);
265
                
266
                // SRS
267
                xml.putProperty("srs", m_SRS);
268
                if (status!=null)
269
                        status.getXMLEntity(xml, true, this);
270
                else{
271
                        status = new StatusLayerRaster();
272
                        status.getXMLEntity(xml, true, this);
273
                }
274
                
275
        // Transparency
276
        xml.putProperty("wms_transparency", wmsTransparency);
277
        
278
        // Styles
279
        if (styles!=null){
280
            String stylePr = "";
281
            for (int i = 0; i < styles.size(); i++) {
282
                stylePr += (String) styles.get(i);
283
                if (i<styles.size()-1)
284
                    stylePr += ",";
285
            }
286
            if (stylePr.endsWith(","))
287
                    stylePr += " ";
288
            xml.putProperty("styles", stylePr);
289
        }
290
        
291
        // Dimensions 
292
        if (dimensions!=null){
293
            String dim = "";
294
            for (int i = 0; i < dimensions.size(); i++) {
295
                dim += (String) dimensions.get(i);
296
                if (i<dimensions.size()-1)
297
                    dim += ",";
298
            }
299
            if (dim.endsWith(","))
300
                    dim += " ";
301
            xml.putProperty("dimensions", dim);
302
        }
303
        
304
        // OnlineResources
305
        Iterator it = onlineResources.keySet().iterator();
306
        String strOnlines = "";
307
        while (it.hasNext()) {
308
                String key = (String) it.next();
309
                String value = (String) onlineResources.get(key);
310
                strOnlines = key+"~##SEP2##~"+value;
311
                if (it.hasNext())
312
                        strOnlines += "~##SEP1##~";
313
        }
314
        xml.putProperty("onlineResources", strOnlines);
315
        
316
        // Queryable
317
        xml.putProperty("queryable", queryable);
318
        
319
        // fixedSize
320
        if (isSizeFixed()) {
321
                xml.putProperty("fixedSize", true);
322
                xml.putProperty("fixedWidth", fixedSize.width);
323
                xml.putProperty("fixedHeight", fixedSize.height);
324
        }
325
        return xml;
326
        }
327

    
328
        /**
329
         * A partir del XMLEntity reproduce la capa.
330
         *
331
         * @param xml XMLEntity
332
         *
333
         * @throws XMLException
334
         * @throws DriverException
335
         * @throws DriverIOException
336
         */
337
        public void setXMLEntity03(XMLEntity xml)
338
                throws XMLException {
339
                super.setXMLEntity(xml);
340
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty(
341
                                        "fullExtent"));
342

    
343
                try {
344
                        host = new URL(xml.getStringProperty("host"));
345
                } catch (MalformedURLException e) {
346
                        throw new XMLException(e);
347
                }
348

    
349
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
350
                layerQuery = xml.getStringProperty("layerQuery");
351
                m_Format = xml.getStringProperty("format");
352
                m_SRS = xml.getStringProperty("srs");
353
        }
354

    
355
        /**
356
         * A partir del XMLEntity reproduce la capa.
357
         *
358
         * @param xml XMLEntity
359
         *
360
         * @throws XMLException
361
         * @throws DriverException
362
         * @throws DriverIOException
363
         */
364
        public void setXMLEntity(XMLEntity xml)
365
                throws XMLException {
366
                super.setXMLEntity(xml);
367
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty(
368
                                        "fullExtent"));
369
                
370
                // Host
371
                try {
372
                        host = new URL(xml.getStringProperty("host"));
373
                } catch (MalformedURLException e) {
374
                        throw new XMLException(e);
375
                }
376

    
377
                // Part of the query that is not the host, or the
378
                // layer names, or other not listed bellow
379
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
380

    
381
                // Part of the query containing the layer names
382
                layerQuery = xml.getStringProperty("layerQuery");
383
                
384
                // Format
385
                m_Format = xml.getStringProperty("format");
386
                
387
                // SRS
388
                m_SRS = xml.getStringProperty("srs");
389
                
390
                String claseStr = StatusLayerRaster.defaultClass;
391
                if (xml.contains("raster.class")) {
392
                        claseStr = xml.getStringProperty("raster.class");
393
                }
394
                
395
                // Transparency
396
        if (xml.contains("wms_transparency"))
397
            wmsTransparency = xml.getBooleanProperty("wms_transparency");
398
        
399
        // Styles
400
        if (xml.contains("styles")){
401
            styles = new Vector();
402
            String[] stl = xml.getStringProperty("styles").split(",");
403
            
404
            for (int i = 0; i < stl.length; i++) {
405
                    if (stl[i].equals(" "))
406
                            stl[i]="";
407
                styles.add(stl[i]);
408
            }
409
        }
410
        
411
        // Dimensions
412
        if (xml.contains("dimensions")){
413
            dimensions = new Vector();
414
            String[] dims = xml.getStringProperty("dimensions").split(",");
415
            for (int i = 0; i < dims.length; i++){
416
                    if (dims[i].equals(" "))
417
                            dims[i]="";
418
                
419
                dimensions.add(dims[i]);
420
            }
421
        }
422
        
423
        // OnlineResources
424
        if (xml.contains("onlineResources")) {
425
                String[] operations = xml.getStringProperty("onlineResources").split("~##SEP1##~");
426
                for (int i = 0; i < operations.length; i++) {
427
                                String[] resources = operations[i].split("~##SEP2##~");
428
                                if (resources.length==2 && resources[1]!="")
429
                                        onlineResources.put(resources[0], resources[1]);
430
                        }
431
        }
432
        
433
        // Queryable
434
        queryable = true; // let's assume that the layer is queryable by default
435
        if (xml.contains("queryable"))
436
                queryable = xml.getBooleanProperty("queryable");
437
        
438
        // fixedSize
439
        if (xml.contains("fixedSize")) {
440
                fixedSize = new Dimension(xml.getIntProperty("fixedWidth"), 
441
                                                  xml.getIntProperty("fixedHeight"));
442
        }
443
        
444
                if(status!=null)
445
                        status.setXMLEntity(xml, this);
446
                else{
447
                        if(claseStr!=null && !claseStr.equals("")){
448
                                try{
449
                                        Class clase = Class.forName(claseStr);
450
                                        Constructor constr = clase.getConstructor(null);
451
                                        status = (StatusRasterInterface)constr.newInstance(null);
452
                                        if(status!=null)
453
                                                status.setXMLEntity(xml, this);
454
                                }catch(ClassNotFoundException exc){
455
                                        exc.printStackTrace();
456
                                }catch(InstantiationException exc){
457
                                        exc.printStackTrace();
458
                                }catch(IllegalAccessException exc){
459
                                        exc.printStackTrace();
460
                                }catch(NoSuchMethodException exc){
461
                                        exc.printStackTrace();
462
                                }catch(InvocationTargetException exc){
463
                                        exc.printStackTrace();
464
                                }                                        
465
                        }
466
                }
467
                firstLoad = true;
468
        }
469

    
470
        public XMLItem[] getInfo(Point p, double tolerance) throws DriverException {
471
                XMLItem[] item =  new XMLItem[1];
472
                try {                        
473
                        if (queryable)
474
                        {
475
                                //TODO
476
                                // check if there are layers which are not queryable
477
                                ViewPort viewPort = getFMap().getViewPort();
478

    
479
                                Point tiledPoint = new Point((int) p.getX() % maxTilePrintWidth, (int) p.getY() % maxTilePrintHeight);
480
                                Rectangle rect = new Rectangle(0, 0, viewPort.getImageWidth() - 1, viewPort.getImageHeight() - 1);
481
                                Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, rect);
482
                                tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
483
                                int nCols = tiles.getNumCols();
484

    
485
                                int col = (int) p.getX() / maxTilePrintWidth;
486
                                int row = (int) p.getY() / maxTilePrintHeight;
487
                                int tileIndex = (row*nCols) + col;
488
                                
489
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileIndex);
490
                                wmsStatus.setExtent(vp.getExtent());
491
                                wmsStatus.setHeight(vp.getImageHeight());
492
                                wmsStatus.setWidth(vp.getImageWidth());
493
                                wmsStatus.setOnlineResource((String) onlineResources.get("GetFeatureInfo"));
494
                                item[0] = new StringXMLItem(new String(getDriver()
495
                                                .getFeatureInfo(wmsStatus, (int) tiledPoint.getX(), (int) tiledPoint.getY(), Integer.MAX_VALUE)),this); 
496
                                return item;
497
                        }
498
                        else
499
                        {
500
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
501
                                                PluginServices.getText(this, "wms_not_queryable"));
502
                                item[0] =  new StringXMLItem("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><info></info>",this);
503
                                return item;
504
                        }
505
                } catch (WMSException  e) {
506
                        item[0] = new StringXMLItem("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><exception>" +
507
                        e.getMessage() + "</exception>", this);
508
                        return item;
509
                } catch (ValidationException e) {
510
                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
511
                } catch (UnsupportedVersionException e) {
512
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
513
                } catch (IOException e) {
514
                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
515
                } catch (NoninvertibleTransformException e) {
516
                        NotificationManager.addError("NotinvertibleTransform", e);
517
                }
518
                return null;
519
        }
520

    
521
        /**
522
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent()
523
         */
524
        public Rectangle2D getFullExtent() {
525
                return fullExtent;
526
        }
527

    
528
        /**
529
         * 
530
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#draw(java.awt.image.BufferedImage,
531
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
532
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
533
         */
534
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
535
                        Cancellable cancel,double scale) throws DriverException {
536
                
537
                if (isWithinScale(scale)){
538
                        Point2D p = viewPort.getOffset();
539
                        // p will be (0, 0) when drawing a view or other when painting onto
540
                        // the Layout.
541
                        visualStatus.width =  viewPort.getImageWidth();
542
                        visualStatus.height =  viewPort.getImageHeight();
543
                        visualStatus.minX = viewPort.getAdjustedExtent().getMinX();
544
                        visualStatus.minY = viewPort.getAdjustedExtent().getMinY();
545
                        visualStatus.maxX = viewPort.getAdjustedExtent().getMaxX();
546
                        visualStatus.maxY = viewPort.getAdjustedExtent().getMaxY();
547
                        if (isSizeFixed()) {
548
                                // This condition handles those situations in which the server can
549
                                // only give static extent and resolution maps despite we need
550
                                // a specific BBOX and pixel WIDTH and HEIGHT
551
                                drawFixedSize(g, viewPort, cancel);
552

    
553
                        } else {
554
                                Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), viewPort.getImageWidth() - 1, viewPort.getImageHeight() - 1);
555
                                Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, r);
556
                                tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
557
                                for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
558
                                        // drawing part
559
                                        try {
560
                                                ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
561
                                                drawTile(g, vp, cancel);
562
                                        } catch (NoninvertibleTransformException e) {
563
                                                e.printStackTrace();
564
                                        }
565
                                }
566
                        }
567
                }
568
        }
569
        
570
        private void drawFixedSize(Graphics2D g, ViewPort vp, Cancellable cancel) throws DriverException {
571
                // This is the extent that will be requested
572
                Rectangle2D bBox = getFullExtent();
573
                
574
                try {                        
575
                        wmsStatus.setExtent( bBox );
576
                        wmsStatus.setFormat( m_Format );
577
                        wmsStatus.setHeight( fixedSize.height );
578
                        wmsStatus.setWidth( fixedSize.width );
579
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
580
                        wmsStatus.setSrs(m_SRS);
581
                        wmsStatus.setStyles(styles);
582
                        wmsStatus.setDimensions(dimensions);
583
                        wmsStatus.setTransparency(wmsTransparency);
584
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
585
                        
586
                        getDriver().getMap(wmsStatus);
587
                        SwingUtilities.invokeAndWait(getDriver());
588
                        File f = getDriver().getFile();
589
                        String nameWorldFile = f.getPath() + getExtensionWorldFile();
590
                        com.iver.andami.Utilities.createTemp(nameWorldFile, this.getDataWorldFile(bBox, fixedSize));
591
                        
592
                        if(status!=null && firstLoad){
593
                                status.applyStatus(this);
594
                                firstLoad = false;
595
                        }
596
                        
597
                        // And finally, obtain the extent intersecting the view and the BBox
598
                        // to draw to.
599
                        Rectangle2D extent = new Rectangle2D.Double();
600
                        Rectangle2D.intersect(vp.getAdjustedExtent(), bBox, extent);
601
                        
602
                        ViewPortData vpData = new ViewPortData(
603
                                vp.getProjection(), new Extent(extent), fixedSize );
604
                        vpData.setMat(vp.getAffineTransform());
605

    
606
                        rasterProcess(g, vpData, f);
607
                        
608
                } catch (ValidationException e) {
609
                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
610
                } catch (UnsupportedVersionException e) {
611
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
612
                } catch (IOException e) {
613
                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
614
                } catch (IllegalStateException e) {
615
                        e.printStackTrace();
616
                } catch (InterruptedException e) {
617
                        e.printStackTrace();
618
                } catch (InvocationTargetException e) {
619
                        e.printStackTrace();
620
                }
621
                
622
                
623
        }
624
        
625
        /**
626
         * This is the method used to draw a tile in a WMS mosaic layer.
627
         */
628
        private void drawTile(Graphics2D g, ViewPort vp, Cancellable cancel) throws DriverException {
629

    
630
                // Compute the query geometry 
631
                // 1. Check if it is within borders
632
                Rectangle2D extent = getFullExtent();
633
        if ((vp.getExtent().getMinX() > extent.getMaxX()) ||
634
                (vp.getExtent().getMinY() > extent.getMaxY()) ||
635
                (vp.getExtent().getMaxX() < extent.getMinX()) ||
636
                (vp.getExtent().getMaxY() < extent.getMinY())) {
637
            return;
638
        }
639
        
640
        // 2. Compute extent to be requested.
641
        Rectangle2D bBox = new Rectangle2D.Double();
642
        Rectangle2D.intersect(vp.getExtent(), extent, bBox);
643
        
644
        // 3. Compute size in pixels
645
        double scalex = vp.getAffineTransform().getScaleX(); 
646
        double scaley = vp.getAffineTransform().getScaleY(); 
647
        int wImg = (int) Math.ceil(Math.abs(bBox.getWidth() * scalex) + 1);
648
        int hImg = (int) Math.ceil(Math.abs(bBox.getHeight() * scaley) + 1);
649
        Dimension sz = new Dimension(wImg, hImg);
650

    
651
        if ((wImg <= 0) || (hImg <= 0)) {
652
            return;
653
        }
654
                
655
                try {                        
656
                        wmsStatus.setExtent( bBox );
657
                        wmsStatus.setFormat(m_Format);
658
                        wmsStatus.setHeight( hImg );
659
                        wmsStatus.setWidth( wImg );
660
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
661
                        wmsStatus.setSrs(m_SRS);
662
                        wmsStatus.setStyles(styles);
663
                        wmsStatus.setDimensions(dimensions);
664
                        wmsStatus.setTransparency(wmsTransparency);
665
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
666
                        
667
                        getDriver().getMap(wmsStatus);
668
                        
669
                        SwingUtilities.invokeAndWait(getDriver());
670
                        
671
                        File f = getDriver().getFile();
672
                        String nameWordFile = f.getPath() + getExtensionWorldFile();
673
                        com.iver.andami.Utilities.createTemp(nameWordFile, this.getDataWorldFile(bBox, sz));
674
                        
675
                        if(status!=null && firstLoad){
676
                                status.applyStatus(this);
677
                                firstLoad = false;
678
                        }
679
                        ViewPortData vpData = new ViewPortData(
680
                                vp.getProjection(), new Extent(bBox), sz );
681
                        vpData.setMat(vp.getAffineTransform());
682

    
683
                        rasterProcess(g, vpData, f);
684
                                        
685
                } catch (ValidationException e) {
686
                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
687
                } catch (UnsupportedVersionException e) {
688
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
689
                } catch (IOException e) {
690
                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
691
                } catch (IllegalStateException e) {
692
                        e.printStackTrace();
693
                } catch (InterruptedException e) {
694
                        e.printStackTrace();
695
                } catch (InvocationTargetException e) {
696
                        e.printStackTrace();
697
                        System.err.println(e.getCause());
698
                }
699
                
700
        }
701

    
702
        /**
703
         * Obtiene la extensi?n del fichero de georreferenciaci?n
704
         * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
705
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld 
706
         */
707
        private String getExtensionWorldFile(){
708
                String extWorldFile = ".wld";
709
            if(m_Format.equals("image/tif") || m_Format.equals("image/tiff"))
710
                    extWorldFile = ".tfw";
711
            if(m_Format.equals("image/jpeg"))
712
                    extWorldFile = ".jpgw";
713
            return extWorldFile;
714
        }
715
        
716
        /**
717
         * Calcula el contenido del fichero de georreferenciaci?n de una imagen.
718
         * @param bBox Tama?o y posici?n de la imagen (en coordenadas de usuario)
719
         * @param sz Tama?o de la imagen en pixeles.
720
         * @return el 'WorldFile', como String.
721
         * @throws IOException
722
         */
723
        public String getDataWorldFile(Rectangle2D bBox, Dimension sz) throws IOException {
724
                StringBuffer data = new StringBuffer();
725
            data.append((bBox.getMaxX() - bBox.getMinX())/(sz.getWidth() - 1)+"\n");
726
            data.append("0.0\n");
727
            data.append("0.0\n");
728
            data.append((bBox.getMaxY() - bBox.getMinY())/(sz.getHeight() - 1)+"\n");
729
            data.append(""+bBox.getMinX()+"\n");
730
            data.append(""+bBox.getMinY()+"\n");
731
            return data.toString();
732
        }
733
                
734
        /**
735
         * Dibuja una imagen usando PxRaster
736
         * @param g        Graphics2D en el que hay que dibujar.
737
         * @param vpData Par?metros de visualizaci?n
738
         * @param file La imagen en cuesti?n.
739
         */
740
        private void rasterProcess(Graphics2D g, ViewPortData vpData, File file) {
741
                
742
                //Creamos el PxRaster        
743
                rasterFile = new GdalFile(vpData.getProjection(), file.getAbsolutePath());
744
                raster = new PxRaster(rasterFile, null, rasterFile.getExtent());
745
                
746
                //Recuperamos la pila de filtros si ya hubiese sido cargado antes
747
                if(this.filterStack!=null)
748
                        raster.filterStack = this.filterStack;
749
                
750
                raster.setTransparency(false);
751
                                                
752
                //Asignamos transparencia y orden de bandas
753
                if(this.transparency==-1 && !firstLoad);
754
                else
755
                        raster.setTransparency(this.transparency);
756
                
757
                raster.setBand(GeoRasterFile.RED_BAND,rband);
758
                raster.setBand(GeoRasterFile.GREEN_BAND, gband);
759
                raster.setBand(GeoRasterFile.BLUE_BAND, bband);
760
        
761
                //Despues del primer pxRaster asignamos el stackManager guardado para los siguientes.
762
                //Con esto conseguimos asignar los cambios que se hayan producido desde el cuadro de 
763
                //propiedades cuando creamos un nuevo pxRaster
764
                if(this.stackManager != null)
765
                        raster.setStackManager(this.stackManager); 
766
                
767
                if(visualStatus != null){
768
                        visualStatus.bandCount = raster.getBandCount();
769
                        visualStatus.dataType = raster.getDataType();
770
                }
771

    
772
                raster.draw(g, vpData);
773
                
774
                //En el primer pxRaster de una imagen obtenemos el Stack Manager para poder modificarlo
775
                //si queremos desde las propiedades
776
                
777
                if(this.stackManager == null)
778
                        this.stackManager = raster.getStackManager(); 
779
                
780
                if(this.filterStack == null)
781
                        this.filterStack = raster.filterStack;
782
                
783
                //rasterFile.close();
784
        }
785
        
786
        /**
787
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D,
788
         *                 com.iver.cit.gvsig.fmap.ViewPort,
789
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
790
         */
791
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale)
792
        throws DriverException {
793
                if (isVisible() && isWithinScale(scale)){        
794
                        isPrinting = true;
795
                        if (!mustTilePrint) {
796
                                draw(null, g, viewPort, cancel,scale);
797
                        } else {
798
                                // Para no pedir imagenes demasiado grandes, vamos
799
                                // a hacer lo mismo que hace EcwFile: chunkear.
800
                                // Llamamos a drawView con cuadraditos m?s peque?os
801
                                // del BufferedImage ni caso, cuando se imprime viene con null
802
                                
803
                                Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipRect());
804
                                tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
805
                                for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
806
                                        // Parte que dibuja
807
                                        try {
808
                                                ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
809
                                                drawTile(g, vp, cancel);
810
                                        } catch (NoninvertibleTransformException e) {
811
                                                e.printStackTrace();
812
                                        }
813
                                }
814
                        }
815
                        isPrinting = false;
816
                }
817
        }
818

    
819
        
820
        /**
821
         * Devuelve el FMapWMSDriver.
822
         *
823
         * @return FMapWMSDriver
824
         *
825
         * @throws IllegalStateException
826
         * @throws ValidationException
827
         * @throws UnsupportedVersionException
828
         * @throws IOException
829
         */
830
        private ExperimentalAsynchronousFMapWMSDriver getDriver()
831
                throws IllegalStateException, ValidationException, 
832
                        UnsupportedVersionException, IOException {
833
                ExperimentalAsynchronousFMapWMSDriver drv = FMapWMSDriverFactory.getDriverForHost(host);
834
                drv.addListener(this);
835
//                if (wms == null) {
836
//                        wms = FMapWMSDriverFactory.getDriverForHost(host); 
837
//                        System.out.println("********** capa afegeix el listener");
838
//                        wms.addListener(this);
839
//                }
840
//
841
//                return wms;
842
                return drv;
843
        }
844

    
845
        /**
846
         * Devuelve el URL.
847
         *
848
         * @return URL.
849
         */
850
        public URL getHost() {
851
                return host;
852
        }
853

    
854
        /**
855
         * Inserta el URL.
856
         *
857
         * @param host URL.
858
         */
859
        public void setHost(URL host) {
860
                this.host = host;
861
        }
862

    
863
        /**
864
         * Devuelve la informaci?n de la consulta.
865
         *
866
         * @return String.
867
         */
868
        public String getInfoLayerQuery() {
869
                return infoLayerQuery;
870
        }
871

    
872
        /**
873
         * Inserta la informaci?n de la consulta.
874
         *
875
         * @param infoLayerQuery String.
876
         */
877
        public void setInfoLayerQuery(String infoLayerQuery) {
878
                this.infoLayerQuery = infoLayerQuery;
879
        }
880

    
881
        /**
882
         * Devuelve la consulta.
883
         *
884
         * @return String.
885
         */
886
        public String getLayerQuery() {
887
                return layerQuery;
888
        }
889

    
890
        /**
891
         * Inserta la consulta.
892
         *
893
         * @param layerQuery consulta.
894
         */
895
        public void setLayerQuery(String layerQuery) {
896
                this.layerQuery = layerQuery;
897
        }
898

    
899
        /**
900
         * Devuelve el formato.
901
         *
902
         * @return Formato.
903
         */
904
        public String getFormat() {
905
                return m_Format;
906
        }
907

    
908
        /**
909
         * Inserta el formato.
910
         *
911
         * @param format Formato.
912
         */
913
        public void setFormat(String format) {
914
                m_Format = format;
915
        }
916

    
917
        /**
918
         * Devuelve el SRS.
919
         *
920
         * @return SRS.
921
         */
922
        public String getSRS() {
923
                return m_SRS;
924
        }
925

    
926
        /**
927
         * Inserta el SRS.
928
         *
929
         * @param m_srs SRS.
930
         */
931
        public void setSRS(String m_srs) {
932
                m_SRS = m_srs;
933
        }
934

    
935
        /**
936
         * Inserta la extensi?n total de la capa.
937
         *
938
         * @param fullExtent Rect?ngulo.
939
         */
940
        public void setFullExtent(Rectangle2D fullExtent) {
941
                this.fullExtent = fullExtent;
942
        }
943
        
944
        public HashMap getProperties() {
945
                HashMap info = new HashMap();
946
        String[] layerNames = getLayerQuery().split(",");
947
        Vector layers = new Vector(layerNames.length);
948
        try {
949
            if(getDriver().connect()){
950
                for (int i = 0; i < layerNames.length; i++) {
951
                    layers.add(i, getDriver().getLayer(layerNames[i]));
952
                }
953
                info.put("name", getName());
954
                info.put("selectedLayers", layers);
955
                info.put("host", getHost());
956
                info.put("srs", getSRS());
957
                info.put("format", getFormat());
958
                info.put("wmsTransparency", new Boolean(wmsTransparency));
959
                info.put("styles", styles);
960
                info.put("dimensions", dimensions);
961
                info.put("fixedSize", fixedSize);
962
                return info;
963
            }
964
        } catch (Exception e) {
965
            e.printStackTrace();
966
        }
967
        return null;
968
        }
969
        
970
        /**
971
         * Asignar el estado del raster
972
         * @param status
973
         */
974
        public void setStatus(StatusRasterInterface status){
975
                this.status = status;
976
        }
977
        
978
        /**
979
         * Obtiene el estado del raster
980
         * @return
981
         */
982
        public StatusRasterInterface getStatus(){
983
                return this.status;
984
        }
985
        
986
        /* (non-Javadoc)
987
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getAttributes()
988
         */
989
        public ArrayList getAttributes() {
990
                if(rasterFile != null){
991
                        ArrayList attr = new ArrayList();
992
                        String dataType = "Byte";
993
                        if (rasterFile.getDataType() == DataBuffer.TYPE_BYTE) dataType = "Byte";
994
                        else if (visualStatus.dataType == DataBuffer.TYPE_SHORT)
995
                                dataType = "Short";
996
                        else if (visualStatus.dataType == DataBuffer.TYPE_USHORT)
997
                                dataType = "Unsigned Short";
998
                        else if (visualStatus.dataType == DataBuffer.TYPE_INT)
999
                                dataType = "Integer";
1000
                        else if (visualStatus.dataType == DataBuffer.TYPE_FLOAT)
1001
                                dataType = "Float";
1002
                        else if (visualStatus.dataType == DataBuffer.TYPE_DOUBLE)
1003
                                dataType = "Double";
1004
                        else
1005
                                dataType = "Unknown";
1006

    
1007
                        Object [][] a = {
1008
                                {"Filename",rasterFile.getName().substring(rasterFile.getName().lastIndexOf("/")+1, rasterFile.getName().length())},
1009
                                {"Filesize",new Long(0)},
1010
                                {"Width",new Integer((int)this.getWidth())},
1011
                                {"Height", new Integer((int)this.getHeight())},
1012
                                {"Bands", new Integer(visualStatus.bandCount)},
1013
                                {"BandDataType", dataType}
1014
                        };
1015
                        for (int i=0; i<a.length; i++)
1016
                                attr.add(a[i]);
1017

    
1018
                        return attr;
1019
                }
1020
                return  null;
1021
        }
1022
        
1023
        /* (non-Javadoc)
1024
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getFilterStack()
1025
         */
1026
        public RasterFilterStack getFilterStack() {
1027
                if(raster!=null)
1028
                        return raster.filterStack;
1029
                return null;
1030
        }
1031
        /* (non-Javadoc)
1032
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getHeight()
1033
         */
1034
        public double getHeight() {
1035
                return visualStatus.height;
1036
        }
1037
        
1038
        /* (non-Javadoc)
1039
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxX()
1040
         */
1041
        public double getMaxX() {
1042
                return visualStatus.maxX;
1043
        }
1044
        
1045
        /* (non-Javadoc)
1046
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxY()
1047
         */
1048
        public double getMaxY() {
1049
                return visualStatus.maxY;
1050
        }
1051
        
1052
        /* (non-Javadoc)
1053
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinX()
1054
         */
1055
        public double getMinX() {
1056
                return visualStatus.minX;
1057
        }
1058
        
1059
        /* (non-Javadoc)
1060
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinY()
1061
         */
1062
        public double getMinY() {
1063
                return visualStatus.minY;
1064
        }
1065
        /* (non-Javadoc)
1066
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getPixel(double, double)
1067
         */
1068
        public int[] getPixel(double wcx, double wcy) {
1069
                if(getPxRaster() != null)
1070
                        return getPxRaster().getPixel(wcx, wcy);
1071
        return null;
1072
        }
1073
        /* (non-Javadoc)
1074
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getSource()
1075
         */
1076
        public RasterAdapter getSource() {
1077
                return null;
1078
        }
1079
        /* (non-Javadoc)
1080
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getWidth()
1081
         */
1082
        public double getWidth() {
1083
                return visualStatus.width;
1084
        }
1085
        /* (non-Javadoc)
1086
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setBand(int, int)
1087
         */
1088
        public void setBand(int flag, int nBand) {
1089
                switch(flag){
1090
                case GeoRasterFile.RED_BAND:setBandR(nBand);break;
1091
                case GeoRasterFile.GREEN_BAND:setBandG(nBand);break;
1092
                case GeoRasterFile.BLUE_BAND:setBandB(nBand);break;
1093
                }
1094
        }
1095
        /* (non-Javadoc)
1096
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setFilterStack(org.cresques.io.raster.RasterFilterStack)
1097
         */
1098
        public void setFilterStack(RasterFilterStack stack) {
1099
                this.filterStack = stack;
1100
        }
1101
        /* (non-Javadoc)
1102
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPos(int, int)
1103
         */
1104
        public void setPos(int x, int y) {
1105
                this.posX = x;
1106
                this.posY = y;
1107
        }
1108
        
1109
        /* (non-Javadoc)
1110
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPosWC(double, double)
1111
         */
1112
        public void setPosWC(double x, double y) {
1113
                this.posXWC = x;
1114
                this.posYWC = y;
1115
        }
1116
        
1117
        /* (non-Javadoc)
1118
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setRGB(int, int, int)
1119
         */
1120
        public void setRGB(int r, int g, int b) {
1121
                this.r = r;
1122
                this.g = g;
1123
                this.b = b;
1124
        }
1125
        /* (non-Javadoc)
1126
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setSource(com.iver.cit.gvsig.fmap.layers.RasterAdapter)
1127
         */
1128
        public void setSource(RasterAdapter ra) {
1129
        }
1130
        /**
1131
         * @return Returns the raster.
1132
         */
1133
        public PxRaster getPxRaster() {
1134
                return raster;
1135
        }
1136
        /**
1137
         * @return Returns the rasterFile.
1138
         */
1139
        public GeoRasterFile getGeoRasterFile() {
1140
                return rasterFile;
1141
        }
1142
        
1143
        public void setTransparency(int trans) {
1144
                this.transparency = trans;
1145
        }
1146
        
1147
        /**
1148
         * Sets the R-band.
1149
         * 
1150
         * Asigna la banda R.
1151
         * @param r
1152
         */
1153
        public void setBandR(int r){
1154
                this.rband = r;
1155
        }
1156
        
1157
        /**
1158
         * Sets the G-band.
1159
         * 
1160
         * Asigna la banda G
1161
         * @param g
1162
         */
1163
        public void setBandG(int g){
1164
                this.gband = g;
1165
        }
1166
        
1167
        /**
1168
         * Sets the B-band.
1169
         * 
1170
         * Asigna la banda B
1171
         * @param b
1172
         */
1173
        public void setBandB(int b){
1174
                this.bband = b;
1175
        }
1176

    
1177
    /**
1178
     * @return Returns the wmsTransparency.
1179
     */
1180
    public boolean isWmsTransparent() {
1181
        return wmsTransparency;
1182
    }
1183

    
1184
    /**
1185
     * @param wmsTransparency The wmsTransparency to set.
1186
     */
1187
    public void setWmsTransparency(boolean wmsTransparency) {
1188
        this.wmsTransparency = wmsTransparency;
1189
    }
1190

    
1191
     /**
1192
     * @param styles
1193
     */
1194
    public void setStyles(Vector styles) {
1195
            //laura:
1196
            //layer query is built with the layer in reverse order
1197
            // so here we build the styles upside-down.
1198
            if (styles != null)
1199
            {
1200
                    this.styles = new Vector();
1201
                    for(int i = styles.size()-1; i>=0; i--)
1202
                    {
1203
                            this.styles.add(styles.elementAt(i));
1204
                    }
1205
            }
1206
    }
1207
    
1208
    /**
1209
     * Sets the dimension vector that is a list of key-value pairs containing
1210
     * the name of the dimension and the value for it
1211
     * @param dimensions
1212
     */
1213
    public void setDimensions(Vector dimensions) {
1214
        this.dimensions = dimensions;
1215
    }
1216

    
1217
    /**
1218
     * Sets the set of URLs that should be accessed for each operation performed
1219
     * to the server.
1220
     * 
1221
     * @param onlineResources
1222
     */
1223
        public void setOnlineResources(Hashtable onlineResources) {
1224
                this.onlineResources = onlineResources;
1225
        }
1226
        
1227
        /**
1228
         * When a server is not fully featured and it only can serve constant map
1229
         * sizes this value must be set. It expresses the size in pixels (width, height)
1230
         * that the map will be requested.
1231
         * @param Dimension sz
1232
         */
1233
        public void setFixedSize(Dimension sz) {
1234
                fixedSize = sz;
1235
        }
1236
        
1237
        /**
1238
         * Tells whether if this layer must deal with the server with the constant-size
1239
         * limitations or not.
1240
         * @return boolean.
1241
         */
1242
        private boolean isSizeFixed() {
1243
                return fixedSize != null && fixedSize.getWidth() > 0 && fixedSize.getHeight() > 0;
1244
        }
1245

    
1246
        /**
1247
         * If it is true, this layer accepts GetFeatureInfo operations. This WMS operations
1248
         * maps to FMap's infoByPoint(p) operation.
1249
         * @param b
1250
         */
1251
        public void setQueryable(boolean b) {
1252
                queryable = b;
1253
        }
1254

    
1255
        /**
1256
         * Creates the part of a OGC's MapContext document that would describe this
1257
         * layer(s).
1258
         * @param version, The desired version of the resulting document. (1.1.0)
1259
         * @return String containing the xml.
1260
         * @throws UnsupportedVersionException 
1261
         */
1262
        public String toMapContext(String mapContextVersion) {
1263
                XmlBuilder xml = new XmlBuilder();
1264
                FMapWMSDriver drv;
1265
                try {
1266
                        drv = getDriver();
1267
                        drv.connect();
1268
                } catch (Exception e) {
1269
                        return xml.toString();
1270
                } 
1271
                String[] layerNames = getLayerQuery().split(",");
1272
                for (int i = 0; i < layerNames.length; i++) {
1273
                        WMSLayerNode layer = drv.getLayer(layerNames[i]);
1274
                        HashMap xmlAttrs = new HashMap();
1275
                        
1276
                        // <Layer>
1277
                        xmlAttrs.put(WebMapContextTags.HIDDEN, !isVisible()+"");
1278
                        xmlAttrs.put(WebMapContextTags.QUERYABLE, queryable+"");
1279
                        xml.openTag(WebMapContextTags.LAYER);
1280
                        if (mapContextVersion.equals("1.1.0") || mapContextVersion.equals("1.0.0")) {
1281
                                // <Server>
1282
                                xmlAttrs.put(WebMapContextTags.SERVICE, WebMapContextTags.WMS);
1283
                                xmlAttrs.put(WebMapContextTags.VERSION, drv.getVersion());
1284
                                xmlAttrs.put(WebMapContextTags.SERVER_TITLE, drv.getServiceTitle());
1285
                                xml.openTag(WebMapContextTags.SERVER, xmlAttrs);
1286
                                xmlAttrs.clear();
1287
                                
1288
                                        // <OnlineResource>
1289
                                        xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1290
                                        xmlAttrs.put(WebMapContextTags.XLINK_HREF, getHost().toString());
1291
                                        xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1292
                                        xmlAttrs.clear();
1293
                                        // </OnlineResource>
1294
                                        
1295
                                xml.closeTag();
1296
                                // </Server>
1297
                                
1298
                                // <Name>
1299
                                xml.writeTag(WebMapContextTags.NAME, layer.getName().trim());
1300
                                // </Name>
1301
                                
1302
                                // <Title>
1303
                                xml.writeTag(WebMapContextTags.TITLE, getName().trim());
1304
                                // </Title>
1305
                                
1306
                                // <Abstract>
1307
                                if (layer.getAbstract() != null)
1308
                                        xml.writeTag(WebMapContextTags.ABSTRACT, layer.getAbstract());
1309
                                // </Abstract>
1310
                                
1311
                                // <SRS> (a list of available SRS for the enclosing layer)
1312
                                String[] strings = (String[]) layer.getAllSrs().toArray(new String[0]);
1313
                                String mySRS = strings[0];
1314
                                for (int j = 1; j < strings.length; j++) {
1315
                                        mySRS += ","+strings[j];
1316
                                }
1317
                                xml.writeTag(WebMapContextTags.SRS, mySRS);
1318
                                // </SRS>
1319
                                
1320
                                // <FormatList>
1321
                                xml.openTag(WebMapContextTags.FORMAT_LIST);
1322
                                        strings = (String[]) drv.getFormats().toArray(new String[0]);
1323
                                        for (int j = 0; j < strings.length; j++) {
1324
                    // <Format>
1325
                                                String str = strings[j].trim();
1326
                                                if (str.equals(getFormat()))
1327
                                                        xml.writeTag(WebMapContextTags.FORMAT, str, WebMapContextTags.CURRENT, "1");
1328
                                                else
1329
                                                        xml.writeTag(WebMapContextTags.FORMAT, str);
1330
                    // </Format>        
1331
                                        }
1332
                                xml.closeTag();
1333
                                // </FormatList>
1334
                                
1335
                                // <StyleList>
1336
                                if (layer.getStyles().size()>0) {
1337
                                        xml.openTag(WebMapContextTags.STYLE_LIST);
1338
                                        for (int j = 0; j < layer.getStyles().size(); j++) {
1339
                                                // <Style>
1340
                                                FMapWMSStyle st = (FMapWMSStyle) layer.getStyles().get(i);
1341
                                                if (st.equals(layer.getSelectedStyle()))
1342
                                                        xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1343
                                                xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1344
                                                
1345
                                                        // <Name>
1346
                                                        xml.writeTag(WebMapContextTags.NAME, st.name);
1347
                                                        // </Name>
1348
                                                        
1349
                                                        // <Title>
1350
                                                        xml.writeTag(WebMapContextTags.TITLE, st.title);
1351
                                                        // </Title>
1352
                                                        
1353
                                                        // <LegendURL width="180" format="image/gif" height="50">
1354
                                                                // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1355
                                                                // </OnlineResource>
1356
                                                        // </LegendURL>
1357
                                                xml.closeTag();
1358
                                                // </Style>
1359
                                                
1360
                                        }
1361
                                        xml.closeTag();
1362
                                }
1363
                                // </StyleList>
1364
                                if (mapContextVersion.compareTo("1.0.0") > 0) {
1365
                                // <DimensionList>
1366
                                        xml.openTag(WebMapContextTags.DIMENSION_LIST);
1367
                                        // <Dimension>
1368
                                        // </Dimension>
1369
                                        xml.closeTag();
1370
                                // </DimensionList>
1371
                                }
1372
                        } else {
1373
                                xml.writeTag("ERROR", PluginServices.getText(this, "unsupported_map_context_version"));
1374
                        }
1375
                        // </Layer>
1376
                        xml.closeTag();
1377
                }
1378
                return xml.getXML();
1379
        }
1380
        
1381
        private class MyTimerTask extends TimerTask {
1382
                private Cancellable cancel;
1383
                
1384
                public MyTimerTask(Cancellable cancel) {
1385
                        super();
1386
                        this.cancel = cancel;
1387
                }
1388
                
1389
                public void run() {
1390
                        while (!cancel.isCanceled()) {}
1391
                        try {
1392
                                getDriver().cancel(WMSOperations.GET_MAP);
1393
                        } catch (IllegalStateException e) {
1394
                                // TODO Auto-generated catch block
1395
                                e.printStackTrace();
1396
                        } catch (ValidationException e) {
1397
                                // TODO Auto-generated catch block
1398
                                e.printStackTrace();
1399
                        } catch (UnsupportedVersionException e) {
1400
                                // TODO Auto-generated catch block
1401
                                e.printStackTrace();
1402
                        } catch (IOException e) {
1403
                                // TODO Auto-generated catch block
1404
                                e.printStackTrace();
1405
                        }
1406
                }
1407
        }
1408

    
1409
        /* This is unuseful until the layers will hold its own ImageBuffer */
1410
        public void getCapabilities(int eventType, String message) { /* Nothing */ }
1411
        public void getFeatureInfo(int eventType, String message)  { /* Nothing */ }
1412
        public void getMap(int eventType, File mapFile, String message) {
1413
                /*File f = mapFile;
1414
                Graphics2D g = dProperties.graphics;
1415
                ViewPort vp = dProperties.viewPort;
1416
                Rectangle2D bBox = dProperties.bBox;
1417
                Dimension sz = dProperties.sz;
1418
                String nameWorldFile = f.getPath() + getExtensionWorldFile();
1419
                try {
1420
                        com.iver.andami.Utilities.createTemp(nameWorldFile, this.getDataWorldFile(bBox, sz));
1421
                } catch (IOException e) {
1422
                        e.printStackTrace();
1423
                        NotificationManager.addError(PluginServices.getText(this, "failed_creating_world_file"), e);
1424
                }
1425
                
1426
                if(status!=null && firstLoad){
1427
                        status.applyStatus(this);
1428
                        firstLoad = false;
1429
                }
1430
                
1431
                // And finally, obtain the extent intersecting the view and the BBox
1432
                // to draw to.
1433
                Rectangle2D extent = new Rectangle2D.Double();
1434
                Rectangle2D.intersect(vp.getAdjustedExtent(), bBox, extent);
1435
                
1436
                ViewPortData vpData = new ViewPortData(
1437
                        vp.getProjection(), new Extent(extent), fixedSize );
1438
                vpData.setMat(vp.getAffineTransform());
1439

1440
                rasterProcess(g, vpData, f);*/
1441
        }
1442
}