Statistics
| Revision:

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

History | View | Annotate | Download (43 KB)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
652
        if ((wImg <= 0) || (hImg <= 0)) {
653
            return;
654
        }
655
                
656
                try {                        
657
                        wmsStatus.setExtent( bBox );
658
                        wmsStatus.setFormat(m_Format);
659
                        wmsStatus.setHeight( hImg );
660
                        wmsStatus.setWidth( wImg );
661
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
662
                        wmsStatus.setSrs(m_SRS);
663
                        wmsStatus.setStyles(styles);
664
                        wmsStatus.setDimensions(dimensions);
665
                        wmsStatus.setTransparency(wmsTransparency);
666
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
667
                        
668
                        
669
                        dProperties.bBox = bBox;
670
                        dProperties.graphics = g;
671
                        dProperties.sz = sz;
672
                        dProperties.viewPort = vp;
673
                        getDriver().getMap(wmsStatus);
674
//                        String nameWordFile = f.getPath() + getExtensionWorldFile();
675
//                        com.iver.andami.Utilities.createTemp(nameWordFile, this.getDataWorldFile(bBox, sz));
676
//                        
677
//                        if(status!=null && firstLoad){
678
//                                status.applyStatus(this);
679
//                                firstLoad = false;
680
//                        }
681
//                        ViewPortData vpData = new ViewPortData(
682
//                                vp.getProjection(), new Extent(bBox), sz );
683
//                        vpData.setMat(vp.getAffineTransform());
684
//
685
//                        rasterProcess(g, vpData, f);
686
                        
687
                } catch (ValidationException e) {
688
                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
689
                } catch (UnsupportedVersionException e) {
690
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
691
                } catch (IOException e) {
692
                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
693
                } catch (WMSException e) {
694
            JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
695
                        this.setVisible(false);
696
                }
697
                
698
        }
699

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

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

    
817
        /**
818
         * Devuelve el FMapWMSDriver.
819
         *
820
         * @return FMapWMSDriver
821
         *
822
         * @throws IllegalStateException
823
         * @throws ValidationException
824
         * @throws UnsupportedVersionException
825
         * @throws IOException
826
         */
827
        private FMapWMSDriver getDriver()
828
                throws IllegalStateException, ValidationException, 
829
                        UnsupportedVersionException, IOException {
830
                FMapWMSDriver drv = FMapWMSDriverFactory.getDriverForHost(host);
831
                drv.addListener(this);
832
                System.err.println("********** capa afegeix el listener");
833
//                if (wms == null) {
834
//                        wms = FMapWMSDriverFactory.getDriverForHost(host); 
835
//                        System.out.println("********** capa afegeix el listener");
836
//                        wms.addListener(this);
837
//                }
838
//
839
//                return wms;
840
                return drv;
841
        }
842
        
843
        /**
844
         * Devuelve el FMapWMSDriver.
845
         *
846
         * @return FMapWMSDriver
847
         *
848
         * @throws IllegalStateException
849
         * @throws ValidationException
850
         * @throws UnsupportedVersionException
851
         * @throws IOException
852
         */
853
//        public void setDriver(FMapWMSDriver drv) {
854
//                wms = drv;
855
//        }
856

    
857
        /**
858
         * Devuelve el URL.
859
         *
860
         * @return URL.
861
         */
862
        public URL getHost() {
863
                return host;
864
        }
865

    
866
        /**
867
         * Inserta el URL.
868
         *
869
         * @param host URL.
870
         */
871
        public void setHost(URL host) {
872
                this.host = host;
873
        }
874

    
875
        /**
876
         * Devuelve la informaci?n de la consulta.
877
         *
878
         * @return String.
879
         */
880
        public String getInfoLayerQuery() {
881
                return infoLayerQuery;
882
        }
883

    
884
        /**
885
         * Inserta la informaci?n de la consulta.
886
         *
887
         * @param infoLayerQuery String.
888
         */
889
        public void setInfoLayerQuery(String infoLayerQuery) {
890
                this.infoLayerQuery = infoLayerQuery;
891
        }
892

    
893
        /**
894
         * Devuelve la consulta.
895
         *
896
         * @return String.
897
         */
898
        public String getLayerQuery() {
899
                return layerQuery;
900
        }
901

    
902
        /**
903
         * Inserta la consulta.
904
         *
905
         * @param layerQuery consulta.
906
         */
907
        public void setLayerQuery(String layerQuery) {
908
                this.layerQuery = layerQuery;
909
        }
910

    
911
        /**
912
         * Devuelve el formato.
913
         *
914
         * @return Formato.
915
         */
916
        public String getFormat() {
917
                return m_Format;
918
        }
919

    
920
        /**
921
         * Inserta el formato.
922
         *
923
         * @param format Formato.
924
         */
925
        public void setFormat(String format) {
926
                m_Format = format;
927
        }
928

    
929
        /**
930
         * Devuelve el SRS.
931
         *
932
         * @return SRS.
933
         */
934
        public String getSRS() {
935
                return m_SRS;
936
        }
937

    
938
        /**
939
         * Inserta el SRS.
940
         *
941
         * @param m_srs SRS.
942
         */
943
        public void setSRS(String m_srs) {
944
                m_SRS = m_srs;
945
        }
946

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

    
1019
                        Object [][] a = {
1020
                                {"Filename",rasterFile.getName().substring(rasterFile.getName().lastIndexOf("/")+1, rasterFile.getName().length())},
1021
                                {"Filesize",new Long(0)},
1022
                                {"Width",new Integer((int)this.getWidth())},
1023
                                {"Height", new Integer((int)this.getHeight())},
1024
                                {"Bands", new Integer(visualStatus.bandCount)},
1025
                                {"BandDataType", dataType}
1026
                        };
1027
                        for (int i=0; i<a.length; i++)
1028
                                attr.add(a[i]);
1029

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

    
1189
    /**
1190
     * @return Returns the wmsTransparency.
1191
     */
1192
    public boolean isWmsTransparent() {
1193
        return wmsTransparency;
1194
    }
1195

    
1196
    /**
1197
     * @param wmsTransparency The wmsTransparency to set.
1198
     */
1199
    public void setWmsTransparency(boolean wmsTransparency) {
1200
        this.wmsTransparency = wmsTransparency;
1201
    }
1202

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

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

    
1258
        /**
1259
         * If it is true, this layer accepts GetFeatureInfo operations. This WMS operations
1260
         * maps to FMap's infoByPoint(p) operation.
1261
         * @param b
1262
         */
1263
        public void setQueryable(boolean b) {
1264
                queryable = b;
1265
        }
1266

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

    
1458
                rasterProcess(g, vpData, f);
1459
        }
1460
}