Statistics
| Revision:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
552
                        } else {
553
                                Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), viewPort.getImageWidth() - 1, viewPort.getImageHeight() - 1);
554
                                Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, r);
555
                                tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
556
                                for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
557
                                        // drawing part
558
                                        try {
559
                                                ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
560
                                                drawTile(g, vp, cancel);
561
                                        } catch (NoninvertibleTransformException e) {
562
                                                e.printStackTrace();
563
                                        }
564
                                }
565
                        }
566
                }
567
        }
568
        
569
        private void drawFixedSize(Graphics2D g, ViewPort vp, Cancellable cancel) throws DriverException {
570
                // This is the extent that will be requested
571
                Rectangle2D bBox = getFullExtent();
572
                
573
                try {                        
574
                        wmsStatus.setExtent( bBox );
575
                        wmsStatus.setFormat( m_Format );
576
                        wmsStatus.setHeight( fixedSize.height );
577
                        wmsStatus.setWidth( fixedSize.width );
578
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
579
                        wmsStatus.setSrs(m_SRS);
580
                        wmsStatus.setStyles(styles);
581
                        wmsStatus.setDimensions(dimensions);
582
                        wmsStatus.setTransparency(wmsTransparency);
583
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
584
                        
585
                        
586
                        dProperties.bBox = bBox;
587
                        dProperties.graphics = g;
588
                        dProperties.sz = fixedSize;
589
                        dProperties.viewPort = vp;
590
                        getDriver().getMap(wmsStatus);
591
//                        String nameWorldFile = f.getPath() + getExtensionWorldFile();
592
//                        com.iver.andami.Utilities.createTemp(nameWorldFile, this.getDataWorldFile(bBox, fixedSize));
593
//                        
594
//                        if(status!=null && firstLoad){
595
//                                status.applyStatus(this);
596
//                                firstLoad = false;
597
//                        }
598
//                        
599
//                        // And finally, obtain the extent intersecting the view and the BBox
600
//                        // to draw to.
601
//                        Rectangle2D extent = new Rectangle2D.Double();
602
//                        Rectangle2D.intersect(vp.getAdjustedExtent(), bBox, extent);
603
//                        
604
//                        ViewPortData vpData = new ViewPortData(
605
//                                vp.getProjection(), new Extent(extent), fixedSize );
606
//                        vpData.setMat(vp.getAffineTransform());
607
//
608
//                        rasterProcess(g, vpData, f);
609
                        
610
                } catch (ValidationException e) {
611
                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
612
                } catch (UnsupportedVersionException e) {
613
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
614
                } catch (IOException e) {
615
                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
616
                } catch (WMSException e) {
617
            JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
618
                        this.setVisible(false);
619
                }
620
                
621
                
622
        }
623
        
624
        /**
625
         * This is the method used to draw a tile in a WMS mosaic layer.
626
         */
627
        private void drawTile(Graphics2D g, ViewPort vp, Cancellable cancel) throws DriverException {
628

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

    
650
        if ((wImg <= 0) || (hImg <= 0)) {
651
            return;
652
        }
653
                
654
                try {                        
655
                        wmsStatus.setExtent( bBox );
656
                        wmsStatus.setFormat(m_Format);
657
                        wmsStatus.setHeight( hImg );
658
                        wmsStatus.setWidth( wImg );
659
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
660
                        wmsStatus.setSrs(m_SRS);
661
                        wmsStatus.setStyles(styles);
662
                        wmsStatus.setDimensions(dimensions);
663
                        wmsStatus.setTransparency(wmsTransparency);
664
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
665
                        
666
                        
667
                        dProperties.bBox = bBox;
668
                        dProperties.graphics = g;
669
                        dProperties.sz = sz;
670
                        dProperties.viewPort = vp;
671
                        getDriver().getMap(wmsStatus);
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 (WMSException e) {
692
            JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
693
                        this.setVisible(false);
694
                }
695
                
696
        }
697

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

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

    
815
        /**
816
         * Devuelve el FMapWMSDriver.
817
         *
818
         * @return FMapWMSDriver
819
         *
820
         * @throws IllegalStateException
821
         * @throws ValidationException
822
         * @throws UnsupportedVersionException
823
         * @throws IOException
824
         */
825
        private FMapWMSDriver getDriver()
826
                throws IllegalStateException, ValidationException, 
827
                        UnsupportedVersionException, IOException {
828
                if (wms == null) {
829
                        wms = FMapWMSDriverFactory.getDriverForHost(host); 
830
                        wms.addListener(this);
831
                }
832

    
833
                return wms;
834
        }
835
        
836
        /**
837
         * Devuelve el FMapWMSDriver.
838
         *
839
         * @return FMapWMSDriver
840
         *
841
         * @throws IllegalStateException
842
         * @throws ValidationException
843
         * @throws UnsupportedVersionException
844
         * @throws IOException
845
         */
846
        public void setDriver(FMapWMSDriver drv) {
847
                wms = drv;
848
        }
849

    
850
        /**
851
         * Devuelve el URL.
852
         *
853
         * @return URL.
854
         */
855
        public URL getHost() {
856
                return host;
857
        }
858

    
859
        /**
860
         * Inserta el URL.
861
         *
862
         * @param host URL.
863
         */
864
        public void setHost(URL host) {
865
                this.host = host;
866
        }
867

    
868
        /**
869
         * Devuelve la informaci?n de la consulta.
870
         *
871
         * @return String.
872
         */
873
        public String getInfoLayerQuery() {
874
                return infoLayerQuery;
875
        }
876

    
877
        /**
878
         * Inserta la informaci?n de la consulta.
879
         *
880
         * @param infoLayerQuery String.
881
         */
882
        public void setInfoLayerQuery(String infoLayerQuery) {
883
                this.infoLayerQuery = infoLayerQuery;
884
        }
885

    
886
        /**
887
         * Devuelve la consulta.
888
         *
889
         * @return String.
890
         */
891
        public String getLayerQuery() {
892
                return layerQuery;
893
        }
894

    
895
        /**
896
         * Inserta la consulta.
897
         *
898
         * @param layerQuery consulta.
899
         */
900
        public void setLayerQuery(String layerQuery) {
901
                this.layerQuery = layerQuery;
902
        }
903

    
904
        /**
905
         * Devuelve el formato.
906
         *
907
         * @return Formato.
908
         */
909
        public String getFormat() {
910
                return m_Format;
911
        }
912

    
913
        /**
914
         * Inserta el formato.
915
         *
916
         * @param format Formato.
917
         */
918
        public void setFormat(String format) {
919
                m_Format = format;
920
        }
921

    
922
        /**
923
         * Devuelve el SRS.
924
         *
925
         * @return SRS.
926
         */
927
        public String getSRS() {
928
                return m_SRS;
929
        }
930

    
931
        /**
932
         * Inserta el SRS.
933
         *
934
         * @param m_srs SRS.
935
         */
936
        public void setSRS(String m_srs) {
937
                m_SRS = m_srs;
938
        }
939

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

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

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

    
1182
    /**
1183
     * @return Returns the wmsTransparency.
1184
     */
1185
    public boolean isWmsTransparent() {
1186
        return wmsTransparency;
1187
    }
1188

    
1189
    /**
1190
     * @param wmsTransparency The wmsTransparency to set.
1191
     */
1192
    public void setWmsTransparency(boolean wmsTransparency) {
1193
        this.wmsTransparency = wmsTransparency;
1194
    }
1195

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

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

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

    
1260
        /**
1261
         * Creates the part of a OGC's MapContext document that would describe this
1262
         * layer(s).
1263
         * @param version, The desired version of the resulting document. (1.1.0)
1264
         * @return String containing the xml.
1265
         * @throws UnsupportedVersionException 
1266
         */
1267
        public String toMapContext(String mapContextVersion) {
1268
                XmlBuilder xml = new XmlBuilder();
1269
                FMapWMSDriver drv;
1270
                try {
1271
                        drv = getDriver();
1272
                        drv.connect();
1273
                } catch (Exception e) {
1274
                        return xml.toString();
1275
                } 
1276
                String[] layerNames = getLayerQuery().split(",");
1277
                for (int i = 0; i < layerNames.length; i++) {
1278
                        WMSLayerNode layer = drv.getLayer(layerNames[i]);
1279
                        HashMap xmlAttrs = new HashMap();
1280
                        
1281
                        // <Layer>
1282
                        xmlAttrs.put(WebMapContextTags.HIDDEN, !isVisible()+"");
1283
                        xmlAttrs.put(WebMapContextTags.QUERYABLE, queryable+"");
1284
                        xml.openTag(WebMapContextTags.LAYER);
1285
                        if (mapContextVersion.equals("1.1.0") || mapContextVersion.equals("1.0.0")) {
1286
                                // <Server>
1287
                                xmlAttrs.put(WebMapContextTags.SERVICE, WebMapContextTags.WMS);
1288
                                xmlAttrs.put(WebMapContextTags.VERSION, drv.getVersion());
1289
                                xmlAttrs.put(WebMapContextTags.SERVER_TITLE, drv.getServiceTitle());
1290
                                xml.openTag(WebMapContextTags.SERVER, xmlAttrs);
1291
                                xmlAttrs.clear();
1292
                                
1293
                                        // <OnlineResource>
1294
                                        xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1295
                                        xmlAttrs.put(WebMapContextTags.XLINK_HREF, getHost().toString());
1296
                                        xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1297
                                        xmlAttrs.clear();
1298
                                        // </OnlineResource>
1299
                                        
1300
                                xml.closeTag();
1301
                                // </Server>
1302
                                
1303
                                // <Name>
1304
                                xml.writeTag(WebMapContextTags.NAME, layer.getName().trim());
1305
                                // </Name>
1306
                                
1307
                                // <Title>
1308
                                xml.writeTag(WebMapContextTags.TITLE, getName().trim());
1309
                                // </Title>
1310
                                
1311
                                // <Abstract>
1312
                                if (layer.getAbstract() != null)
1313
                                        xml.writeTag(WebMapContextTags.ABSTRACT, layer.getAbstract());
1314
                                // </Abstract>
1315
                                
1316
                                // <SRS> (a list of available SRS for the enclosing layer)
1317
                                String[] strings = (String[]) layer.getAllSrs().toArray(new String[0]);
1318
                                String mySRS = strings[0];
1319
                                for (int j = 1; j < strings.length; j++) {
1320
                                        mySRS += ","+strings[j];
1321
                                }
1322
                                xml.writeTag(WebMapContextTags.SRS, mySRS);
1323
                                // </SRS>
1324
                                
1325
                                // <FormatList>
1326
                                xml.openTag(WebMapContextTags.FORMAT_LIST);
1327
                                        strings = (String[]) drv.getFormats().toArray(new String[0]);
1328
                                        for (int j = 0; j < strings.length; j++) {
1329
                    // <Format>
1330
                                                String str = strings[j].trim();
1331
                                                if (str.equals(getFormat()))
1332
                                                        xml.writeTag(WebMapContextTags.FORMAT, str, WebMapContextTags.CURRENT, "1");
1333
                                                else
1334
                                                        xml.writeTag(WebMapContextTags.FORMAT, str);
1335
                    // </Format>        
1336
                                        }
1337
                                xml.closeTag();
1338
                                // </FormatList>
1339
                                
1340
                                // <StyleList>
1341
                                if (layer.getStyles().size()>0) {
1342
                                        xml.openTag(WebMapContextTags.STYLE_LIST);
1343
                                        for (int j = 0; j < layer.getStyles().size(); j++) {
1344
                                                // <Style>
1345
                                                FMapWMSStyle st = (FMapWMSStyle) layer.getStyles().get(i);
1346
                                                if (st.equals(layer.getSelectedStyle()))
1347
                                                        xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1348
                                                xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1349
                                                
1350
                                                        // <Name>
1351
                                                        xml.writeTag(WebMapContextTags.NAME, st.name);
1352
                                                        // </Name>
1353
                                                        
1354
                                                        // <Title>
1355
                                                        xml.writeTag(WebMapContextTags.TITLE, st.title);
1356
                                                        // </Title>
1357
                                                        
1358
                                                        // <LegendURL width="180" format="image/gif" height="50">
1359
                                                                // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1360
                                                                // </OnlineResource>
1361
                                                        // </LegendURL>
1362
                                                xml.closeTag();
1363
                                                // </Style>
1364
                                                
1365
                                        }
1366
                                        xml.closeTag();
1367
                                }
1368
                                // </StyleList>
1369
                                if (mapContextVersion.compareTo("1.0.0") > 0) {
1370
                                // <DimensionList>
1371
                                        xml.openTag(WebMapContextTags.DIMENSION_LIST);
1372
                                        // <Dimension>
1373
                                        // </Dimension>
1374
                                        xml.closeTag();
1375
                                // </DimensionList>
1376
                                }
1377
                        } else {
1378
                                xml.writeTag("ERROR", PluginServices.getText(this, "unsupported_map_context_version"));
1379
                        }
1380
                        // </Layer>
1381
                        xml.closeTag();
1382
                }
1383
                return xml.getXML();
1384
        }
1385
        
1386
        private class MyTimerTask extends TimerTask {
1387
                private Cancellable cancel;
1388
                
1389
                public MyTimerTask(Cancellable cancel) {
1390
                        super();
1391
                        this.cancel = cancel;
1392
                }
1393
                
1394
                public void run() {
1395
                        while (!cancel.isCanceled()) {}
1396
                        try {
1397
                                getDriver().cancel(WMSOperations.GET_MAP);
1398
                        } catch (IllegalStateException e) {
1399
                                // TODO Auto-generated catch block
1400
                                e.printStackTrace();
1401
                        } catch (ValidationException e) {
1402
                                // TODO Auto-generated catch block
1403
                                e.printStackTrace();
1404
                        } catch (UnsupportedVersionException e) {
1405
                                // TODO Auto-generated catch block
1406
                                e.printStackTrace();
1407
                        } catch (IOException e) {
1408
                                // TODO Auto-generated catch block
1409
                                e.printStackTrace();
1410
                        }
1411
                }
1412
        }
1413
        
1414
        private class DrawingProperties {
1415
                Graphics2D graphics;
1416
                Rectangle2D bBox;
1417
                Dimension sz;
1418
                ViewPort viewPort;
1419
        }
1420
        
1421
        public void getCapabilities(int eventType, String message) { /* Nothing */ }
1422
        public void getFeatureInfo(int eventType, String message)  { /* Nothing */ }
1423
        public void getMap(int eventType, File mapFile, String message) {
1424
                System.out.println("getMap at the layer");
1425
                File f = mapFile;
1426
                Graphics2D g = dProperties.graphics;
1427
                ViewPort vp = dProperties.viewPort;
1428
                Rectangle2D bBox = dProperties.bBox;
1429
                
1430
                String nameWorldFile = f.getPath() + getExtensionWorldFile();
1431
                try {
1432
                        com.iver.andami.Utilities.createTemp(nameWorldFile, this.getDataWorldFile(bBox, fixedSize));
1433
                } catch (IOException e) {
1434
                        NotificationManager.addError(PluginServices.getText(this, "failed_creating_world_file"), e);
1435
                }
1436
                
1437
                if(status!=null && firstLoad){
1438
                        status.applyStatus(this);
1439
                        firstLoad = false;
1440
                }
1441
                
1442
                // And finally, obtain the extent intersecting the view and the BBox
1443
                // to draw to.
1444
                Rectangle2D extent = new Rectangle2D.Double();
1445
                Rectangle2D.intersect(vp.getAdjustedExtent(), bBox, extent);
1446
                
1447
                ViewPortData vpData = new ViewPortData(
1448
                        vp.getProjection(), new Extent(extent), fixedSize );
1449
                vpData.setMat(vp.getAffineTransform());
1450

    
1451
                rasterProcess(g, vpData, f);
1452
        }
1453
}