Statistics
| Revision:

root / branches / MULTITHREADING_DEVELOPMENT / extensions / extWMS / src / com / iver / cit / gvsig / fmap / layers / FLyrWMS.java @ 5393

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.Color;
44
import java.awt.Component;
45
import java.awt.Dimension;
46
import java.awt.Graphics2D;
47
import java.awt.Point;
48
import java.awt.Rectangle;
49
import java.awt.geom.AffineTransform;
50
import java.awt.geom.NoninvertibleTransformException;
51
import java.awt.geom.Point2D;
52
import java.awt.geom.Rectangle2D;
53
import java.awt.image.BufferedImage;
54
import java.awt.image.DataBuffer;
55
import java.io.File;
56
import java.io.IOException;
57
import java.lang.reflect.Constructor;
58
import java.lang.reflect.InvocationTargetException;
59
import java.net.MalformedURLException;
60
import java.net.URL;
61
import java.util.ArrayList;
62
import java.util.HashMap;
63
import java.util.Hashtable;
64
import java.util.Iterator;
65
import java.util.Map;
66
import java.util.Timer;
67
import java.util.TimerTask;
68
import java.util.Vector;
69

    
70
import javax.swing.JOptionPane;
71
import javax.swing.SwingUtilities;
72

    
73
import org.cresques.geo.ViewPortData;
74
import org.cresques.io.GdalFile;
75
import org.cresques.io.GeoRasterFile;
76
import org.cresques.io.raster.RasterFilterStack;
77
import org.cresques.io.raster.RasterFilterStackManager;
78
import org.cresques.px.Extent;
79
import org.cresques.px.PxRaster;
80
import org.exolab.castor.xml.ValidationException;
81
import org.gvsig.remoteClient.taskplanning.ICancellable;
82
import org.gvsig.remoteClient.taskplanning.retrieving.URLRetrieveTask;
83
import org.gvsig.remoteClient.utils.Utilities;
84
import org.gvsig.remoteClient.wms.WMSStatus;
85

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

    
107
/**
108
* FMap's WMS Layer class.
109
*
110
* @author Jaume Dominguez Faus
111
*                   Nacho Brodin
112
* 
113
*/
114
public class FLyrWMS extends FLyrDefault implements InfoByPoint, RasterOperations, WMSOperations {
115
        private boolean                                         isPrinting = false;
116
        private boolean                                         mustTileDraw = false;
117
        private boolean                                         mustTilePrint = true;
118
        private final int                                         maxTileDrawWidth = -1;
119
        private final int                                         maxTileDrawHeight = -1;
120
        private final int                                         maxTilePrintWidth = 1200;
121
        private final int                                         maxTilePrintHeight = 1200;
122
    
123
    public URL                                                         host;
124
    public String                                                 m_Format;
125
    
126
        private String                                                 m_SRS;
127
        private String                                                 layerQuery;
128
        private String                                                 infoLayerQuery;
129
//        private FMapWMSDriver                                 wms = null;
130
        private WMSStatus                                         wmsStatus = new WMSStatus();
131
        private Rectangle2D                                 fullExtent;
132
        private boolean                                                wmsTransparency;
133
    private Vector                                                 styles;
134
    private Vector                                                 dimensions;
135
        private StatusRasterInterface                status = null;
136
        private int                                                 posX = 0, posY = 0;
137
        private double                                                 posXWC = 0, posYWC = 0;
138
        private int                                                 r = 0, g = 0, b = 0;
139
        private GeoRasterFile                                 rasterFile = null;
140
        private PxRaster                                         raster = null;
141
        private RasterFilterStack                         filterStack = null;
142
        private boolean                                                firstLoad = false;
143
        private int                                                 transparency = -1;
144
        private int                                                 rband = 0, gband = 1, bband = 2;
145
        private RasterFilterStackManager        stackManager = null;
146
        private Hashtable                                         onlineResources = new Hashtable();
147
        private Dimension                                         fixedSize;
148
        private boolean                                         queryable = true;
149
        private VisualStatusWMS                                visualStatus = new VisualStatusWMS();
150
        private final long                                         latency = 1000; // milliseconds
151
        
152
        private class MyCancellable implements ICancellable
153
        {
154

    
155
                private Cancellable original;
156
                public MyCancellable(Cancellable cancelOriginal)
157
                {
158
                        this.original = cancelOriginal;
159
                }
160
                public boolean isCanceled() {
161
                        return original.isCanceled();
162
                }
163
                
164
        }
165
        
166
        public FLyrWMS(){
167
                super();
168
        }
169
        
170
        public FLyrWMS(Map args) throws DriverIOException{
171
                FMapWMSDriver drv = null;
172
                String host = (String)args.get("host");
173
                String sLayer = (String)args.get("layer");
174
                Rectangle2D fullExtent = (Rectangle2D)args.get("FullExtent");
175
                String sSRS = (String)args.get("SRS");
176
                String sFormat = (String)args.get("Format");
177
                String[] sLayers = sLayer.split(",");
178
                
179
                try {
180
                        this.setHost(new URL(host));
181
                } catch (MalformedURLException e) {
182
                        //e.printStackTrace();
183
                        throw new DriverIOException("Malformed host URL, '" + host + "' (" + e.toString() + ").");                        
184
                }
185
                try {
186
                        drv = this.getDriver();
187
                } catch (Exception e) {
188
                        // e.printStackTrace();
189
                        throw new DriverIOException("Can't get driver to host '" + host + "' (" + e.toString() + ").");                        
190
                }
191
                if( sFormat == null || sSRS == null || fullExtent == null ) {
192
                        if (!drv.connect())
193
                                throw new DriverIOException("Can't connect to host '" + host + "'."); 
194
                        
195
                        WMSLayerNode wmsNode = drv.getLayer(sLayer);
196
                                                        
197
                        if (wmsNode == null){
198
                                throw new DriverIOException("The server '" + host + "' doesn't has the layer '" + sLayer + "'.");
199
                        }                
200
                        if( sFormat == null ) {
201
                                sFormat = this.getGreatFormat(drv.getFormats());
202
                        }
203
                     if( sSRS == null ) {
204
                             sSRS = (String)wmsNode.getAllSrs().get(0);
205
                     }
206
                        if( fullExtent == null ) {
207
                                fullExtent = drv.getLayersExtent(sLayers,(String)wmsNode.getAllSrs().get(0));
208
                        }
209
                }
210
                
211
                                
212
                this.setFullExtent(fullExtent);
213
                this.setFormat(sFormat);
214
                this.setLayerQuery(sLayer);
215
                this.setInfoLayerQuery("");
216
                this.setSRS(sSRS);
217
                this.setName(sLayer);
218
        }
219
        
220
        /**
221
         * It choose the best format to load different maps if the server 
222
         * supports it. This format could be png, because it supports 
223
         * transparency.
224
         * @param formats
225
         * Arraywith all the formats supported by the server
226
         * @return
227
         * @author jorge piera llodra
228
         */        
229
        private String getGreatFormat(Vector formats){
230
            for (int i=0 ; i<formats.size() ; i++){
231
                String format = (String) formats.get(i);
232
                    if (format.equals("image/jpg")){
233
                    return format;
234
                    }
235
                    if (format.equals("image/jpeg")){
236
                    return format;
237
                    }
238
            }
239
                    
240
            return (String)formats.get(0);
241
        }
242
        
243
        /**
244
         * Clase que contiene los datos de visualizaci?n de WMS.
245
         * @author Nacho Brodin (brodin_ign@gva.es)
246
         */
247
        private class VisualStatusWMS{
248
                /**
249
                 * Ancho y alto de la imagen o del conjunto de tiles si los tiene. Coincide con 
250
                 * el ancho y alto del viewPort
251
                 */
252
                private        int                                                        width = 0, height = 0;
253
                private double                                                minX = 0D, minY = 0D, maxX = 0D, maxY = 0D;
254
                private int                                                 bandCount = 0;
255
                private int                                                        dataType = DataBuffer.TYPE_UNDEFINED;
256
        }
257
         
258

    
259
        /**
260
         * Devuelve el XMLEntity con la informaci?n necesaria para reproducir la
261
         * capa.
262
         *
263
         * @return XMLEntity.
264
         * @throws XMLException
265
         */
266
        public XMLEntity getXMLEntity() throws XMLException {
267
                XMLEntity xml = super.getXMLEntity();
268

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

    
347
        /**
348
         * A partir del XMLEntity reproduce la capa.
349
         *
350
         * @param xml XMLEntity
351
         *
352
         * @throws XMLException
353
         * @throws DriverException
354
         * @throws DriverIOException
355
         */
356
        public void setXMLEntity03(XMLEntity xml)
357
                throws XMLException {
358
                super.setXMLEntity(xml);
359
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty(
360
                                        "fullExtent"));
361

    
362
                try {
363
                        host = new URL(xml.getStringProperty("host"));
364
                } catch (MalformedURLException e) {
365
                        throw new XMLException(e);
366
                }
367

    
368
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
369
                layerQuery = xml.getStringProperty("layerQuery");
370
                m_Format = xml.getStringProperty("format");
371
                m_SRS = xml.getStringProperty("srs");
372
        }
373

    
374
        /**
375
         * A partir del XMLEntity reproduce la capa.
376
         *
377
         * @param xml XMLEntity
378
         *
379
         * @throws XMLException
380
         * @throws DriverException
381
         * @throws DriverIOException
382
         */
383
        public void setXMLEntity(XMLEntity xml)
384
                throws XMLException {
385
                super.setXMLEntity(xml);
386
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty(
387
                                        "fullExtent"));
388
                
389
                // Host
390
                try {
391
                        host = new URL(xml.getStringProperty("host"));
392
                } catch (MalformedURLException e) {
393
                        throw new XMLException(e);
394
                }
395

    
396
                // Part of the query that is not the host, or the
397
                // layer names, or other not listed bellow
398
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
399

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

    
489
        public XMLItem[] getInfo(Point p, double tolerance) throws DriverException {
490
                XMLItem[] item =  new XMLItem[1];
491
                try {                        
492
                        if (queryable)
493
                        {
494
                                //TODO
495
                                // check if there are layers which are not queryable
496
                                ViewPort viewPort = getFMap().getViewPort();
497

    
498
                                Point tiledPoint = new Point((int) p.getX() % maxTilePrintWidth, (int) p.getY() % maxTilePrintHeight);
499
                                Rectangle rect = new Rectangle(0, 0, viewPort.getImageWidth() - 1, viewPort.getImageHeight() - 1);
500
                                Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, rect);
501
                                tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
502
                                int nCols = tiles.getNumCols();
503

    
504
                                int col = (int) p.getX() / maxTilePrintWidth;
505
                                int row = (int) p.getY() / maxTilePrintHeight;
506
                                int tileIndex = (row*nCols) + col;
507
                                
508
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileIndex);
509
                                wmsStatus.setExtent(vp.getExtent());
510
                                wmsStatus.setHeight(vp.getImageHeight());
511
                                wmsStatus.setWidth(vp.getImageWidth());
512
                                wmsStatus.setOnlineResource((String) onlineResources.get("GetFeatureInfo"));
513
                                item[0] = new StringXMLItem(new String(getDriver()
514
                                                .getFeatureInfo(wmsStatus, (int) tiledPoint.getX(), (int) tiledPoint.getY(), Integer.MAX_VALUE)),this); 
515
                                return item;
516
                        }
517
                        else
518
                        {
519
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
520
                                                PluginServices.getText(this, "wms_not_queryable"));
521
                                item[0] =  new StringXMLItem("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><info></info>",this);
522
                                return item;
523
                        }
524
                } catch (WMSException  e) {
525
                        item[0] = new StringXMLItem("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><exception>" +
526
                        e.getMessage() + "</exception>", this);
527
                        return item;
528
                } catch (ValidationException e) {
529
                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
530
                } catch (UnsupportedVersionException e) {
531
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
532
                } catch (IOException e) {
533
                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
534
                } catch (NoninvertibleTransformException e) {
535
                        NotificationManager.addError("NotinvertibleTransform", e);
536
                }
537
                return null;
538
        }
539

    
540
        /**
541
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent()
542
         */
543
        public Rectangle2D getFullExtent() {
544
                return fullExtent;
545
        }
546

    
547
        /**
548
         * 
549
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#draw(java.awt.image.BufferedImage,
550
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
551
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
552
         */
553
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
554
                        Cancellable cancel,double scale) throws DriverException {
555
                if (isWithinScale(scale)){
556
                        Point2D p = viewPort.getOffset();
557
                        // p will be (0, 0) when drawing a view or other when painting onto
558
                        // the Layout.
559
                        visualStatus.width =  viewPort.getImageWidth();
560
                        visualStatus.height =  viewPort.getImageHeight();
561
                        visualStatus.minX = viewPort.getAdjustedExtent().getMinX();
562
                        visualStatus.minY = viewPort.getAdjustedExtent().getMinY();
563
                        visualStatus.maxX = viewPort.getAdjustedExtent().getMaxX();
564
                        visualStatus.maxY = viewPort.getAdjustedExtent().getMaxY();
565
                        if (isSizeFixed()) {
566
                                // This condition handles those situations in which the server can
567
                                // only give static extent and resolution maps despite we need
568
                                // a specific BBOX and pixel WIDTH and HEIGHT
569
                                drawFixedSize(g, viewPort, cancel);
570

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

    
624
                        rasterProcess(g, vpData, f);
625
                        
626
                } catch (ValidationException e) {
627
                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
628
                } catch (UnsupportedVersionException e) {
629
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
630
                } catch (IOException e) {
631
                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
632
                } catch (IllegalStateException e) {
633
                        e.printStackTrace();
634
                } catch (InterruptedException e) {
635
                        e.printStackTrace();
636
                } catch (InvocationTargetException e) {
637
                        e.printStackTrace();
638
                }
639
                
640
                
641
        }
642
        
643
        /**
644
         * This is the method used to draw a tile in a WMS mosaic layer.
645
         */
646
        private void drawTile(Graphics2D g, ViewPort vp, Cancellable cancel) throws DriverException {
647

    
648
                // Compute the query geometry 
649
                // 1. Check if it is within borders
650
                Rectangle2D extent = getFullExtent();
651
        if ((vp.getExtent().getMinX() > extent.getMaxX()) ||
652
                (vp.getExtent().getMinY() > extent.getMaxY()) ||
653
                (vp.getExtent().getMaxX() < extent.getMinX()) ||
654
                (vp.getExtent().getMaxY() < extent.getMinY())) {
655
            return;
656
        }
657
        
658
        // 2. Compute extent to be requested.
659
        Rectangle2D bBox = new Rectangle2D.Double();
660
        Rectangle2D.intersect(vp.getExtent(), extent, bBox);
661
        
662
        // 3. Compute size in pixels
663
        double scalex = vp.getAffineTransform().getScaleX(); 
664
        double scaley = vp.getAffineTransform().getScaleY(); 
665
        int wImg = (int) Math.ceil(Math.abs(bBox.getWidth() * scalex) + 1);
666
        int hImg = (int) Math.ceil(Math.abs(bBox.getHeight() * scaley) + 1);
667
        Dimension sz = new Dimension(wImg, hImg);
668

    
669
        if ((wImg <= 0) || (hImg <= 0)) {
670
            return;
671
        }
672
                
673
                try {                        
674
                        wmsStatus.setExtent( bBox );
675
                        wmsStatus.setFormat(m_Format);
676
                        wmsStatus.setHeight( hImg );
677
                        wmsStatus.setWidth( wImg );
678
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
679
                        wmsStatus.setSrs(m_SRS);
680
                        wmsStatus.setStyles(styles);
681
                        wmsStatus.setDimensions(dimensions);
682
                        wmsStatus.setTransparency(wmsTransparency);
683
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
684
                        
685
                        getDriver().getMap(wmsStatus, new MyCancellable(cancel));
686
                        
687
                        // SwingUtilities.invokeAndWait(getDriver());
688
                        getDriver().run();
689
                        URLRetrieveTask task = new URLRetrieveTask(request);
690
                        
691
                        if (cancel.isCanceled())
692
                                System.err.println("CANCELADO!!!!");
693
                        
694
                        File f = getDriver().getFile();
695
                        g.setColor(Color.BLACK);
696
                        
697
                        String nameWordFile = f.getPath() + getExtensionWorldFile();
698
                        com.iver.andami.Utilities.createTemp(nameWordFile, this.getDataWorldFile(bBox, sz));
699
                        
700
                        if(status!=null && firstLoad){
701
                                status.applyStatus(this);
702
                                firstLoad = false;
703
                        }
704
                        ViewPortData vpData = new ViewPortData(
705
                                vp.getProjection(), new Extent(bBox), sz );
706
                        vpData.setMat(vp.getAffineTransform());
707

    
708
                        rasterProcess(g, vpData, f);
709
                                        
710
                } catch (ValidationException e) {
711
                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
712
                } catch (UnsupportedVersionException e) {
713
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
714
                } catch (IOException e) {
715
                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
716
                } catch (IllegalStateException e) {
717
                        e.printStackTrace();
718
                } catch (InterruptedException e) {
719
                        e.printStackTrace();
720
                /* } catch (InvocationTargetException e) {
721
                        e.printStackTrace();
722
                        System.err.println(e.getCause()); */
723
                }
724
                
725
        }
726

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

    
797
                raster.draw(g, vpData);
798
                
799
                //En el primer pxRaster de una imagen obtenemos el Stack Manager para poder modificarlo
800
                //si queremos desde las propiedades
801
                
802
                if(this.stackManager == null)
803
                        this.stackManager = raster.getStackManager(); 
804
                
805
                if(this.filterStack == null)
806
                        this.filterStack = raster.filterStack;
807
                
808
                //rasterFile.close();
809
        }
810
        
811
        /**
812
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D,
813
         *                 com.iver.cit.gvsig.fmap.ViewPort,
814
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
815
         */
816
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale)
817
        throws DriverException {
818
                if (isVisible() && isWithinScale(scale)){        
819
                        isPrinting = true;
820
                        if (!mustTilePrint) {
821
                                draw(null, g, viewPort, cancel,scale);
822
                        } else {
823
                                // Para no pedir imagenes demasiado grandes, vamos
824
                                // a hacer lo mismo que hace EcwFile: chunkear.
825
                                // Llamamos a drawView con cuadraditos m?s peque?os
826
                                // del BufferedImage ni caso, cuando se imprime viene con null
827
                                
828
                                Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipRect());
829
                                tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
830
                                for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
831
                                        // Parte que dibuja
832
                                        try {
833
                                                ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
834
                                                drawTile(g, vp, cancel);
835
                                        } catch (NoninvertibleTransformException e) {
836
                                                e.printStackTrace();
837
                                        }
838
                                }
839
                        }
840
                        isPrinting = false;
841
                }
842
        }
843

    
844
        
845
        /**
846
         * Devuelve el FMapWMSDriver.
847
         *
848
         * @return FMapWMSDriver
849
         *
850
         * @throws IllegalStateException
851
         * @throws ValidationException
852
         * @throws UnsupportedVersionException
853
         * @throws IOException
854
         */
855
        private ExperimentalAsynchronousFMapWMSDriver getDriver()
856
                throws IllegalStateException, ValidationException, 
857
                        UnsupportedVersionException, IOException {
858
                ExperimentalAsynchronousFMapWMSDriver drv = FMapWMSDriverFactory.getDriverForHost(host);
859
                drv.addListener(this);
860
//                if (wms == null) {
861
//                        wms = FMapWMSDriverFactory.getDriverForHost(host); 
862
//                        System.out.println("********** capa afegeix el listener");
863
//                        wms.addListener(this);
864
//                }
865
//
866
//                return wms;
867
                return drv;
868
        }
869

    
870
        /**
871
         * Devuelve el URL.
872
         *
873
         * @return URL.
874
         */
875
        public URL getHost() {
876
                return host;
877
        }
878

    
879
        /**
880
         * Inserta el URL.
881
         *
882
         * @param host URL.
883
         */
884
        public void setHost(URL host) {
885
                this.host = host;
886
        }
887

    
888
        /**
889
         * Devuelve la informaci?n de la consulta.
890
         *
891
         * @return String.
892
         */
893
        public String getInfoLayerQuery() {
894
                return infoLayerQuery;
895
        }
896

    
897
        /**
898
         * Inserta la informaci?n de la consulta.
899
         *
900
         * @param infoLayerQuery String.
901
         */
902
        public void setInfoLayerQuery(String infoLayerQuery) {
903
                this.infoLayerQuery = infoLayerQuery;
904
        }
905

    
906
        /**
907
         * Devuelve la consulta.
908
         *
909
         * @return String.
910
         */
911
        public String getLayerQuery() {
912
                return layerQuery;
913
        }
914

    
915
        /**
916
         * Inserta la consulta.
917
         *
918
         * @param layerQuery consulta.
919
         */
920
        public void setLayerQuery(String layerQuery) {
921
                this.layerQuery = layerQuery;
922
        }
923

    
924
        /**
925
         * Devuelve el formato.
926
         *
927
         * @return Formato.
928
         */
929
        public String getFormat() {
930
                return m_Format;
931
        }
932

    
933
        /**
934
         * Inserta el formato.
935
         *
936
         * @param format Formato.
937
         */
938
        public void setFormat(String format) {
939
                m_Format = format;
940
        }
941

    
942
        /**
943
         * Devuelve el SRS.
944
         *
945
         * @return SRS.
946
         */
947
        public String getSRS() {
948
                return m_SRS;
949
        }
950

    
951
        /**
952
         * Inserta el SRS.
953
         *
954
         * @param m_srs SRS.
955
         */
956
        public void setSRS(String m_srs) {
957
                m_SRS = m_srs;
958
        }
959

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

    
1032
                        Object [][] a = {
1033
                                {"Filename",rasterFile.getName().substring(rasterFile.getName().lastIndexOf("/")+1, rasterFile.getName().length())},
1034
                                {"Filesize",new Long(0)},
1035
                                {"Width",new Integer((int)this.getWidth())},
1036
                                {"Height", new Integer((int)this.getHeight())},
1037
                                {"Bands", new Integer(visualStatus.bandCount)},
1038
                                {"BandDataType", dataType}
1039
                        };
1040
                        for (int i=0; i<a.length; i++)
1041
                                attr.add(a[i]);
1042

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

    
1202
    /**
1203
     * @return Returns the wmsTransparency.
1204
     */
1205
    public boolean isWmsTransparent() {
1206
        return wmsTransparency;
1207
    }
1208

    
1209
    /**
1210
     * @param wmsTransparency The wmsTransparency to set.
1211
     */
1212
    public void setWmsTransparency(boolean wmsTransparency) {
1213
        this.wmsTransparency = wmsTransparency;
1214
    }
1215

    
1216
     /**
1217
     * @param styles
1218
     */
1219
    public void setStyles(Vector styles) {
1220
            //laura:
1221
            //layer query is built with the layer in reverse order
1222
            // so here we build the styles upside-down.
1223
            if (styles != null)
1224
            {
1225
                    this.styles = new Vector();
1226
                    for(int i = styles.size()-1; i>=0; i--)
1227
                    {
1228
                            this.styles.add(styles.elementAt(i));
1229
                    }
1230
            }
1231
    }
1232
    
1233
    /**
1234
     * Sets the dimension vector that is a list of key-value pairs containing
1235
     * the name of the dimension and the value for it
1236
     * @param dimensions
1237
     */
1238
    public void setDimensions(Vector dimensions) {
1239
        this.dimensions = dimensions;
1240
    }
1241

    
1242
    /**
1243
     * Sets the set of URLs that should be accessed for each operation performed
1244
     * to the server.
1245
     * 
1246
     * @param onlineResources
1247
     */
1248
        public void setOnlineResources(Hashtable onlineResources) {
1249
                this.onlineResources = onlineResources;
1250
        }
1251
        
1252
        /**
1253
         * When a server is not fully featured and it only can serve constant map
1254
         * sizes this value must be set. It expresses the size in pixels (width, height)
1255
         * that the map will be requested.
1256
         * @param Dimension sz
1257
         */
1258
        public void setFixedSize(Dimension sz) {
1259
                fixedSize = sz;
1260
        }
1261
        
1262
        /**
1263
         * Tells whether if this layer must deal with the server with the constant-size
1264
         * limitations or not.
1265
         * @return boolean.
1266
         */
1267
        private boolean isSizeFixed() {
1268
                return fixedSize != null && fixedSize.getWidth() > 0 && fixedSize.getHeight() > 0;
1269
        }
1270

    
1271
        /**
1272
         * If it is true, this layer accepts GetFeatureInfo operations. This WMS operations
1273
         * maps to FMap's infoByPoint(p) operation.
1274
         * @param b
1275
         */
1276
        public void setQueryable(boolean b) {
1277
                queryable = b;
1278
        }
1279

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

1437
                rasterProcess(g, vpData, f);*/
1438
        }
1439
}