Statistics
| Revision:

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

History | View | Annotate | Download (55.6 KB)

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

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

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

    
73
import org.cresques.filter.RasterFilterStack;
74
import org.cresques.filter.RasterFilterStackManager;
75
import org.cresques.geo.ViewPortData;
76
import org.cresques.io.GdalFile;
77
import org.cresques.io.GeoRasterFile;
78
import org.cresques.io.data.Grid;
79
import org.cresques.io.exceptions.NotSupportedExtensionException;
80
import org.cresques.px.Extent;
81
import org.cresques.px.PxRaster;
82
import org.exolab.castor.xml.ValidationException;
83
import org.gvsig.remoteClient.utils.Utilities;
84
import org.gvsig.remoteClient.wms.ICancellable;
85
import org.gvsig.remoteClient.wms.WMSStatus;
86

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

    
111

    
112

    
113
/**
114
* FMap's WMS Layer class.
115
*
116
* @author Jaume Dominguez Faus
117
*                   Nacho Brodin
118
*
119
*/
120
public class FLyrWMS extends FLyrDefault implements InfoByPoint, RasterOperations, IHasImageLegend {
121
        private boolean                                         isPrinting = false;
122
        private boolean                                         mustTileDraw = true;
123
        private boolean                                         mustTilePrint = true;
124
        private final int                                         maxTileDrawWidth = 1023;
125
        private final int                                         maxTileDrawHeight = 1023;
126
        private final int                                         maxTilePrintWidth = 1023;
127
        private final int                                         maxTilePrintHeight = 1023;
128
        private final int                                        minTilePrintWidth = 12;
129
        private final int                                        minTilePrintHeight = 12;
130

    
131
    public URL                                                         host;
132
    public String                                                 m_Format;
133

    
134
        private String                                                 m_SRS;
135
        private String                                                 layerQuery;
136
        private String                                                 infoLayerQuery;
137
        private FMapWMSDriver                                 wms;
138
        private WMSStatus                                         wmsStatus = new WMSStatus();
139
        private Rectangle2D                                 fullExtent;
140
        private boolean                                                wmsTransparency;
141
    private Vector                                                 styles;
142
    private Vector                                                 dimensions;
143
        private StatusRasterInterface                status = null;
144
        private int                                                 posX = 0, posY = 0;
145
        private double                                                 posXWC = 0, posYWC = 0;
146
        private int                                                 r = 0, g = 0, b = 0;
147
        private GeoRasterFile                                 rasterFile = null;
148
        private PxRaster                                         raster = null;
149
        private RasterFilterStack                         filterStack = null;
150
        private boolean                                                firstLoad = false;
151
        private int                                                 transparency = -1;
152
        private int                                                 rband = 0, gband = 1, bband = 2;
153
        private RasterFilterStackManager        stackManager = null;
154
        private Hashtable                                         onlineResources = new Hashtable();
155
        private Dimension                                         fixedSize;
156
        private boolean                                         queryable = true;
157
        private VisualStatusWMS                                visualStatus = new VisualStatusWMS();
158
        private Grid                                                grid = null;
159

    
160

    
161
        private class MyCancellable implements ICancellable
162
        {
163
                private Cancellable original;
164
                public MyCancellable(Cancellable cancelOriginal)
165
                {
166
                        this.original = cancelOriginal;
167
                }
168
                public boolean isCanceled() {
169
                        if (original == null) return false;
170
                        return original.isCanceled();
171
                }
172

    
173
        }
174

    
175
        public FLyrWMS(){
176
                super();
177
        }
178

    
179
        public FLyrWMS(Map args) throws DriverIOException{
180
                FMapWMSDriver drv = null;
181
                String host = (String)args.get("host");
182
                String sLayer = (String)args.get("layer");
183
                Rectangle2D fullExtent = (Rectangle2D)args.get("FullExtent");
184
                String sSRS = (String)args.get("SRS");
185
                String sFormat = (String)args.get("Format");
186
                String[] sLayers = sLayer.split(",");
187

    
188
                try {
189
                        this.setHost(new URL(host));
190
                } catch (MalformedURLException e) {
191
                        //e.printStackTrace();
192
                        throw new DriverIOException("Malformed host URL, '" + host + "' (" + e.toString() + ").");
193
                }
194
                try {
195
                        drv = this.getDriver();                        
196
                } catch (Exception e) {
197
                        // e.printStackTrace();
198
                        throw new DriverIOException("Can't get driver to host '" + host + "' (" + e.toString() + ").");
199
                }
200
                if( sFormat == null || sSRS == null || fullExtent == null ) {
201
                        if (!drv.connect(null))
202
                                throw new DriverIOException("Can't connect to host '" + host + "'.");
203

    
204
                        WMSLayerNode wmsNode = drv.getLayer(sLayer);
205
                        
206
                        if (wmsNode == null){
207
                                throw new DriverIOException("The server '" + host + "' doesn't has the layer '" + sLayer + "'.");
208
                        }
209
                        if( sFormat == null ) {
210
                                sFormat = this.getGreatFormat(drv.getFormats());
211
                        }
212
                        
213
                        //SRS
214
                        Vector allSrs = wmsNode.getAllSrs();
215
                        boolean isSRSSupported = false;
216
                        if( sSRS != null ) {
217
                                for (int i=0; i<allSrs.size() ; i++){
218
                                     if (((String)allSrs.get(i)).compareTo(sSRS) == 0){
219
                                             isSRSSupported = true;
220
                                     }                                     
221
                             }
222
                        }
223
                        
224
                     if(!isSRSSupported) {
225
                             for (int i=0; i<allSrs.size() ; i++){
226
                                     if (((String)wmsNode.getAllSrs().get(i)).compareTo("EPSG:4326") == 0){
227
                                             sSRS = (String)wmsNode.getAllSrs().get(i);
228
                                     }                                     
229
                             }
230
                             if (sSRS==null){
231
                                     sSRS = (String)wmsNode.getAllSrs().get(0);
232
                             }
233
                     }
234
                        if( fullExtent == null ) {
235
                                fullExtent = drv.getLayersExtent(sLayers,sSRS);
236
                        }
237
                }
238

    
239

    
240
                this.setFullExtent(fullExtent);
241
                this.setFormat(sFormat);
242
                this.setLayerQuery(sLayer);
243
                this.setInfoLayerQuery("");
244
                this.setSRS(sSRS);
245
                this.setName(sLayer);
246
                this.setOnlineResources(drv.getOnlineResources());
247
                load();
248
        }
249

    
250
        /**
251
         * It choose the best format to load different maps if the server
252
         * supports it. This format could be png, because it supports
253
         * transparency.
254
         * @param formats
255
         * Arraywith all the formats supported by the server
256
         * @return
257
         */
258
        private String getGreatFormat(Vector formats){
259
            for (int i=0 ; i<formats.size() ; i++){
260
                String format = (String) formats.get(i);
261
                    if (format.equals("image/jpg")){
262
                    return format;
263
                    }
264
                    if (format.equals("image/jpeg")){
265
                    return format;
266
                    }
267
            }
268

    
269
            return (String)formats.get(0);
270
        }
271

    
272
        /**
273
         * Clase que contiene los datos de visualizaci?n de WMS. Tiene datos que representan al
274
         * raster en la vista. Este raster puede estar compuesto por tiles por lo que valores 
275
         * como el ancho total o el m?nimo o m?ximo deben ser calculados a partir de todos los
276
         * tiles visualizados.
277
         * @author Nacho Brodin (brodin_ign@gva.es)
278
         */
279
        private class VisualStatusWMS{
280
                /**
281
                 * Ancho y alto de la imagen o del conjunto de tiles si los tiene. Coincide con
282
                 * el ancho y alto del viewPort
283
                 */
284
                private        int                                                        width = 0, height = 0;
285
                private double                                                minX = 0D, minY = 0D, maxX = 0D, maxY = 0D;
286
                private int                                                 bandCount = 0;
287
                private int                                                        dataType = DataBuffer.TYPE_UNDEFINED;
288

    
289
                /**
290
                 * Ancho y alto total del raster que ser? la suma de todos los tiles.
291
                 */
292
                private        int                                                        rasterWidth = 0, rasterHeight = 0;
293
                private        double                                                rasterMinX = Double.MAX_VALUE, rasterMinY = Double.MAX_VALUE;
294
                private        double                                                rasterMaxX = 0, rasterMaxY = 0;
295
                /**
296
                 * Lista de nombre de fichero que componen toda la visualizaci?n.
297
                 */
298
                private String[]                                        fileNames = null;
299
        }
300

    
301

    
302
        /**
303
         * Devuelve el XMLEntity con la informaci?n necesaria para reproducir la
304
         * capa.
305
         *
306
         * @return XMLEntity.
307
         * @throws XMLException
308
         */
309
        public XMLEntity getXMLEntity() throws XMLException {
310
                XMLEntity xml = super.getXMLEntity();
311

    
312
                // Full extent
313
                xml.putProperty("fullExtent", StringUtilities.rect2String(fullExtent));
314

    
315
                // Host
316
                xml.putProperty("host", host.toExternalForm());
317

    
318
                // Part of the query that is not the host, or the
319
                // layer names, or other not listed bellow
320
                xml.putProperty("infoLayerQuery", infoLayerQuery);
321

    
322
                // Part of the query containing the layer names
323
                xml.putProperty("layerQuery", layerQuery);
324

    
325
                // Format
326
                xml.putProperty("format", m_Format);
327

    
328
                // SRS
329
                xml.putProperty("srs", m_SRS);
330
                if (status!=null)
331
                        status.getXMLEntity(xml, true, this);
332
                else{
333
                        status = new StatusLayerRaster();
334
                        status.getXMLEntity(xml, true, this);
335
                }
336

    
337
        // Transparency
338
        xml.putProperty("wms_transparency", wmsTransparency);
339

    
340
        // Styles
341
        if (styles!=null){
342
            String stylePr = "";
343
            for (int i = 0; i < styles.size(); i++) {
344
                stylePr += (String) styles.get(i);
345
                if (i<styles.size()-1)
346
                    stylePr += ",";
347
            }
348
            if (stylePr.endsWith(","))
349
                    stylePr += " ";
350
            xml.putProperty("styles", stylePr);
351
        }
352

    
353
        // Dimensions
354
        if (dimensions!=null){
355
            String dim = "";
356
            for (int i = 0; i < dimensions.size(); i++) {
357
                dim += (String) dimensions.get(i);
358
                if (i<dimensions.size()-1)
359
                    dim += ",";
360
            }
361
            if (dim.endsWith(","))
362
                    dim += " ";
363
            xml.putProperty("dimensions", dim);
364
        }
365

    
366
        // OnlineResources
367
        Iterator it = onlineResources.keySet().iterator();
368
        String strOnlines = "";
369
        while (it.hasNext()) {
370
                String key = (String) it.next();
371
                String value = (String) onlineResources.get(key);
372
                strOnlines = key+"~##SEP2##~"+value;
373
                if (it.hasNext())
374
                        strOnlines += "~##SEP1##~";
375
        }
376
        xml.putProperty("onlineResources", strOnlines);
377

    
378
        // Queryable
379
        xml.putProperty("queryable", queryable);
380

    
381
        // fixedSize
382
        if (isSizeFixed()) {
383
                xml.putProperty("fixedSize", true);
384
                xml.putProperty("fixedWidth", fixedSize.width);
385
                xml.putProperty("fixedHeight", fixedSize.height);
386
        }
387
        return xml;
388
        }
389

    
390
        /**
391
         * A partir del XMLEntity reproduce la capa.
392
         *
393
         * @param xml XMLEntity
394
         *
395
         * @throws XMLException
396
         * @throws DriverException
397
         * @throws DriverIOException
398
         */
399
        public void setXMLEntity03(XMLEntity xml)
400
                throws XMLException {
401
                super.setXMLEntity(xml);
402
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty(
403
                                        "fullExtent"));
404

    
405
                try {
406
                        host = new URL(xml.getStringProperty("host"));
407
                } catch (MalformedURLException e) {
408
                        throw new XMLException(e);
409
                }
410

    
411
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
412
                layerQuery = xml.getStringProperty("layerQuery");
413
                m_Format = xml.getStringProperty("format");
414
                m_SRS = xml.getStringProperty("srs");
415
        }
416

    
417
        /**
418
         * A partir del XMLEntity reproduce la capa.
419
         *
420
         * @param xml XMLEntity
421
         *
422
         * @throws XMLException
423
         * @throws DriverException
424
         * @throws DriverIOException
425
         */
426
        public void setXMLEntity(XMLEntity xml)
427
                throws XMLException {
428
                super.setXMLEntity(xml);
429
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty(
430
                                        "fullExtent"));
431

    
432
                // Host
433
                try {
434
                        host = new URL(xml.getStringProperty("host"));
435
                } catch (MalformedURLException e) {
436
                        throw new XMLException(e);
437
                }
438

    
439
                // Part of the query that is not the host, or the
440
                // layer names, or other not listed bellow
441
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
442

    
443
                // Part of the query containing the layer names
444
                layerQuery = xml.getStringProperty("layerQuery");
445

    
446
                // Format
447
                m_Format = xml.getStringProperty("format");
448

    
449
                // SRS
450
                m_SRS = xml.getStringProperty("srs");
451

    
452
                String claseStr = StatusLayerRaster.defaultClass;
453
                if (xml.contains("raster.class")) {
454
                        claseStr = xml.getStringProperty("raster.class");
455
                }
456

    
457
                // Transparency
458
        if (xml.contains("wms_transparency"))
459
            wmsTransparency = xml.getBooleanProperty("wms_transparency");
460

    
461
        // Styles
462
        if (xml.contains("styles")){
463
            styles = new Vector();
464
            String[] stl = xml.getStringProperty("styles").split(",");
465

    
466
            for (int i = 0; i < stl.length; i++) {
467
                    if (stl[i].equals(" "))
468
                            stl[i]="";
469
                styles.add(stl[i]);
470
            }
471
        }
472

    
473
        // Dimensions
474
        if (xml.contains("dimensions")){
475
            dimensions = new Vector();
476
            String[] dims = xml.getStringProperty("dimensions").split(",");
477
            for (int i = 0; i < dims.length; i++){
478
                    if (dims[i].equals(" "))
479
                            dims[i]="";
480

    
481
                dimensions.add(dims[i]);
482
            }
483
        }
484

    
485
        // OnlineResources
486
        if (xml.contains("onlineResources")) {
487
                String[] operations = xml.getStringProperty("onlineResources").split("~##SEP1##~");
488
                for (int i = 0; i < operations.length; i++) {
489
                                String[] resources = operations[i].split("~##SEP2##~");
490
                                if (resources.length==2 && resources[1]!="")
491
                                        onlineResources.put(resources[0], resources[1]);
492
                        }
493
        }
494

    
495
        // Queryable
496
        queryable = true; // let's assume that the layer is queryable by default
497
        if (xml.contains("queryable"))
498
                queryable = xml.getBooleanProperty("queryable");
499

    
500
        // fixedSize
501
        if (xml.contains("fixedSize")) {
502
                fixedSize = new Dimension(xml.getIntProperty("fixedWidth"),
503
                                                  xml.getIntProperty("fixedHeight"));
504
        }
505

    
506
                if(status!=null)
507
                        status.setXMLEntity(xml, this);
508
                else{
509
                        if(claseStr!=null && !claseStr.equals("")){
510
                                try{
511
                                        Class clase = Class.forName(claseStr);
512
                                        Constructor constr = clase.getConstructor(null);
513
                                        status = (StatusRasterInterface)constr.newInstance(null);
514
                                        if(status!=null)
515
                                                status.setXMLEntity(xml, this);
516
                                }catch(ClassNotFoundException exc){
517
                                        exc.printStackTrace();
518
                                }catch(InstantiationException exc){
519
                                        exc.printStackTrace();
520
                                }catch(IllegalAccessException exc){
521
                                        exc.printStackTrace();
522
                                }catch(NoSuchMethodException exc){
523
                                        exc.printStackTrace();
524
                                }catch(InvocationTargetException exc){
525
                                        exc.printStackTrace();
526
                                }
527
                        }
528
                }
529
                firstLoad = true;
530
        }
531

    
532
        /**
533
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(com.iver.cit.gvsig.fmap.operations.QueriedPoint)
534
         */
535
        public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancellable) throws DriverException {
536
                XMLItem[] item =  new XMLItem[1];
537
                try {
538
                        if (queryable)
539
                        {
540
                                //TODO
541
                                // check if there are layers which are not queryable
542
                                ViewPort viewPort = getMapContext().getViewPort();
543

    
544
                                Point tiledPoint = new Point((int) p.getX() % maxTilePrintWidth, (int) p.getY() % maxTilePrintHeight);
545
                                Rectangle rect = new Rectangle(0, 0, viewPort.getImageWidth() - 1, viewPort.getImageHeight() - 1);
546
                                Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, rect);
547
                                tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
548
                                int nCols = tiles.getNumCols();
549

    
550
                                int col = (int) p.getX() / maxTilePrintWidth;
551
                                int row = (int) p.getY() / maxTilePrintHeight;
552
                                int tileIndex = (row*nCols) + col;
553

    
554
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileIndex);
555
                                wmsStatus.setExtent(vp.getAdjustedExtent());
556
                                wmsStatus.setHeight(vp.getImageHeight());
557
                                wmsStatus.setWidth(vp.getImageWidth());
558
                                wmsStatus.setOnlineResource((String) onlineResources.get("GetFeatureInfo"));
559
                                if (wmsStatus.getSrs() == null){
560
                                        wmsStatus.setSrs(this.m_SRS);
561
                                }
562
                                MyCancellable c = new MyCancellable(cancellable);
563
                                item[0] = new StringXMLItem(new String(getDriver()
564
                                                .getFeatureInfo(wmsStatus, (int) tiledPoint.getX(), (int) tiledPoint.getY(), Integer.MAX_VALUE, c)),this);
565
                                return item;
566
                        }
567
                        else
568
                        {
569
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),this.getName() + " " +
570
                                                PluginServices.getText(this,"layer_not_queryable"));
571
                                item[0] =  new StringXMLItem("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><info></info>",this);
572
                                return item;
573
                                //return null;
574
                        }
575
                } catch (WMSException  e) {
576
                        item[0] = new StringXMLItem("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><exception>" +
577
                        e.getMessage() + "</exception>", this);
578
                        return item;
579
                }
580
                /*azabala
581
                catch (ValidationException e) {
582
                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
583
                } catch (UnsupportedVersionException e) {
584
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
585
                } catch (IOException e) {
586
                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
587
                }
588
                */
589
                catch (ValidationException e) {
590
                        UnknownResponseFormatExceptionType type =
591
                                new UnknownResponseFormatExceptionType();
592
                        type.setLayerName(getName());
593
                        try {
594
                                type.setDriverName("WMS Driver");
595
                        } catch (Exception e1) {
596
                                e1.printStackTrace();
597
                        }
598
                        type.setFormat(m_Format);
599
                        type.setHost(host);
600
                        type.setProtocol("WMS");
601
                        DriverException exception = new DriverException("unknown_response_format", type);
602
                        throw exception;
603

    
604
                } catch (UnsupportedVersionException e) {
605
                        UnsuportedProtocolVersionExceptionType type =
606
                                new UnsuportedProtocolVersionExceptionType();
607
                        type.setLayerName(getName());
608
                        try {
609
                                type.setDriverName("WMS Driver");
610
                        } catch (Exception ex){
611
                        }
612
                        type.setUrl(host);
613
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e, type);
614

    
615
                } catch (IOException e) {
616
                        ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
617
                        type.setLayerName(getName());
618
                        try {
619
                                type.setDriverName("WMS Driver");
620
                        } catch (Exception e1) {
621
                        }
622
                        type.setHost(host);
623
                        throw new DriverException(PluginServices.
624
                                        getText(this, "connect_error"), e, type);
625
                }
626
                catch (NoninvertibleTransformException e) {
627
                        NotificationManager.addError("NotinvertibleTransform", e);
628
                }
629
                return null;
630
        }
631

    
632
        /**
633
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent()
634
         */
635
        public Rectangle2D getFullExtent() {
636
                return fullExtent;
637
        }
638

    
639
        /**
640
         *
641
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#draw(java.awt.image.BufferedImage,
642
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
643
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
644
         */
645
        private int callCount; // mess code, represents the amount of times the methods drawFixedSize or drawTile where tried for an extent
646
        private static final int MAX_RETRY_TIMES = 5; // mess code, represents the max amount of retries allowed.
647
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
648
                        Cancellable cancel,double scale) throws DriverException {
649
                callCount = 0; // mess code
650
                if (isWithinScale(scale)){
651
                        Point2D p = viewPort.getOffset();
652
                        // p will be (0, 0) when drawing a view or other when painting onto
653
                        // the Layout.
654
                        visualStatus.width =  viewPort.getImageWidth();
655
                        visualStatus.height =  viewPort.getImageHeight();
656
                        visualStatus.minX = viewPort.getAdjustedExtent().getMinX();
657
                        visualStatus.minY = viewPort.getAdjustedExtent().getMinY();
658
                        visualStatus.maxX = viewPort.getAdjustedExtent().getMaxX();
659
                        visualStatus.maxY = viewPort.getAdjustedExtent().getMaxY();
660

    
661

    
662
                        if (isSizeFixed()) {
663
                                // This condition handles those situations in which the server can
664
                                // only give static extent and resolution maps despite we need
665
                                // a specific BBOX and pixel WIDTH and HEIGHT
666
                                drawFixedSize(g, viewPort, cancel);
667

    
668
                        } else {
669
                                if(mustTileDraw){
670
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), viewPort.getImageWidth(), viewPort.getImageHeight());
671
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
672
                                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
673
                                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
674
                                                // drawing part
675
                                                try {
676
                                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
677
                                                        drawTile(g, vp, cancel);
678
                                                } catch (NoninvertibleTransformException e) {
679
                                                        e.printStackTrace();
680
                                                }
681
                                        }
682
                                }else
683
                                        drawTile(g, viewPort, cancel);
684
                        }
685
                }
686
//                Runtime r = Runtime.getRuntime();
687
//                long mem = r.totalMemory() - r.freeMemory();
688
//                System.err.println("Memoria total: " + (mem / 1024) +"KB");
689
        }
690

    
691
        private void drawFixedSize(Graphics2D g, ViewPort vp, Cancellable cancel) throws DriverException {
692
                callCount++; // mess code, it is not unusual a wms server to response an error which is completely
693
                                         // temporal and the response is available if we retry requesting.
694
                                         //
695

    
696

    
697
                // This is the extent that will be requested
698
                Rectangle2D bBox = getFullExtent();
699
                MyCancellable c = new MyCancellable(cancel);
700

    
701
                try {
702
                        wmsStatus.setExtent( bBox );
703
                        wmsStatus.setFormat( m_Format );
704
                        wmsStatus.setHeight( fixedSize.height );
705
                        wmsStatus.setWidth( fixedSize.width );
706
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
707
                        wmsStatus.setSrs(m_SRS);
708
                        wmsStatus.setStyles(styles);
709
                        wmsStatus.setDimensions(dimensions);
710
                        wmsStatus.setTransparency(wmsTransparency);
711
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
712
                        File f = getDriver().getMap(wmsStatus, c);
713
                        if (f == null)
714
                                return;
715
                        String nameWorldFile = f.getPath() + getExtensionWorldFile();
716
                        com.iver.andami.Utilities.createTemp(nameWorldFile, this.getDataWorldFile(bBox, fixedSize));
717

    
718
                        if(status!=null && firstLoad){
719
                                status.applyStatus(this);
720
                                firstLoad = false;
721
                        }
722

    
723
                        // And finally, obtain the extent intersecting the view and the BBox
724
                        // to draw to.
725
                        Rectangle2D extent = new Rectangle2D.Double();
726
                        Rectangle2D.intersect(vp.getAdjustedExtent(), bBox, extent);
727

    
728
                        ViewPortData vpData = new ViewPortData(
729
                                vp.getProjection(), new Extent(extent), fixedSize );
730
                        vpData.setMat(vp.getAffineTransform());
731

    
732
                        rasterProcess(g, vpData, f);
733

    
734
                } catch (ValidationException e) {
735
                        if (!c.isCanceled())
736
                        {
737
                                UnknownResponseFormatExceptionType type =
738
                                        new UnknownResponseFormatExceptionType();
739
                                type.setLayerName(getName());
740
                                try {
741
                                        type.setDriverName("WMS Driver");
742
                                } catch (Exception e1) {
743
                                        e1.printStackTrace();
744
                                }
745
                                type.setFormat(m_Format);
746
                                type.setHost(host);
747
                                type.setProtocol("WMS");
748
                                DriverException exception = new DriverException("unknown_response_format", type);
749
                                throw exception;
750
                        }
751
//        azabala                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
752
                } catch (UnsupportedVersionException e) {
753
                        if (!c.isCanceled()){
754
                                UnsuportedProtocolVersionExceptionType type =
755
                                        new UnsuportedProtocolVersionExceptionType();
756
                                type.setLayerName(getName());
757
                                try {
758
                                        type.setDriverName("WMS Driver");
759
                                } catch (Exception ex){
760
                                }
761
                                type.setUrl(host);
762
                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e, type);
763
                        }
764
//        azabala                throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
765
                } catch (IOException e) {
766
                        if (!c.isCanceled())
767
                                if (callCount<MAX_RETRY_TIMES) { // mess code
768
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
769
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
770
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
771
                                        drawFixedSize(g, vp, cancel); // mess code
772
                                } // mess code
773

    
774
                                if (callCount == 1) { // mess code
775
                                        ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
776
                                        type.setLayerName(getName());
777
                                        try {
778
                                                type.setDriverName("WMS Driver");
779
                                        } catch (Exception e1) {
780
                                        }
781
                                        type.setHost(host);
782
                                        throw new DriverException(PluginServices.
783
                                                        getText(this, "connect_error"), e, type);
784
//        azabala        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
785
                                } // mess code
786

    
787

    
788
                } catch (WMSException e) {
789
                        if (!c.isCanceled()) {
790
                                if (callCount<MAX_RETRY_TIMES) { // mess code
791
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
792
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
793
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
794
                                        drawFixedSize(g, vp, cancel); // mess code
795
                                } // mess code
796
                                if (callCount == 1) { // mess code
797
//                azabala                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
798
                                        WMSDriverExceptionType type = new WMSDriverExceptionType();
799
                                        type.setLayerName(getName());
800
                                        try {
801
                                                type.setDriverName("WMS Driver");
802
                                        } catch (Exception e1) {
803
                                        }
804
                                        type.setWcsStatus(this.wmsStatus);
805
                                        if (!isPrinting)
806
                                                this.setVisible(false);
807
                                        throw new DriverException("Error WMS", e,  type);
808

    
809

    
810
                                } // mess code
811
                        }
812
                }
813
                callCount--; // mess code
814
        }
815

    
816
        /**
817
         * This is the method used to draw a tile in a WMS mosaic layer.
818
         */
819
        private void drawTile(Graphics2D g, ViewPort vp, Cancellable cancel) throws DriverException {
820
                callCount++;
821
                // Compute the query geometry
822
                // 1. Check if it is within borders
823
                Rectangle2D extent = getFullExtent();
824
        if ((vp.getAdjustedExtent().getMinX() > extent.getMaxX()) ||
825
                (vp.getAdjustedExtent().getMinY() > extent.getMaxY()) ||
826
                (vp.getAdjustedExtent().getMaxX() < extent.getMinX()) ||
827
                (vp.getAdjustedExtent().getMaxY() < extent.getMinY())) {
828
            return;
829
        }
830

    
831
        // 2. Compute extent to be requested.
832
        Rectangle2D bBox = new Rectangle2D.Double();
833
        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
834

    
835
        // 3. Compute size in pixels
836
        double scalex = vp.getAffineTransform().getScaleX();
837
        double scaley = vp.getAffineTransform().getScaleY();
838
        int wImg = (int) Math.ceil(Math.abs(bBox.getWidth() * scalex) + 1);
839
        int hImg = (int) Math.ceil(Math.abs(bBox.getHeight() * scaley) + 1);
840

    
841
        Dimension sz = new Dimension(wImg, hImg);
842

    
843
        if ((wImg <= 0) || (hImg <= 0)) {
844
            return;
845
        }
846
        MyCancellable c = new MyCancellable(cancel);
847

    
848
                try {
849
//                        wImg = vp.getImageWidth();
850
//                        hImg = vp.getImageHeight();
851
                        sz = new Dimension(wImg, hImg);
852
                        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
853

    
854

    
855
                        wmsStatus.setExtent( bBox );
856
                        wmsStatus.setFormat(m_Format);
857
                        wmsStatus.setHeight( hImg );
858
                        wmsStatus.setWidth( wImg );
859
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
860
                        wmsStatus.setSrs(m_SRS);
861
                        wmsStatus.setStyles(styles);
862
                        wmsStatus.setDimensions(dimensions);
863
                        wmsStatus.setTransparency(wmsTransparency);
864
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
865

    
866
                        // begin patch; Avoid to request too small tiles.
867
                        // This generally occurs when printing
868

    
869
                        if (wImg < minTilePrintWidth) {
870
                                double wScale = (double) minTilePrintWidth / wImg;
871
                                wmsStatus.setWidth(minTilePrintWidth);
872
                                Rectangle2D sExtent = wmsStatus.getExtent();
873
                                Point2D initialPoint = new Point2D.Double(sExtent.getX(), sExtent.getY());
874
                                sExtent.setRect(sExtent.getX()*wScale, sExtent.getY(), sExtent.getWidth()*wScale, sExtent.getHeight());
875
                                if (!bBox.contains(initialPoint)) {
876
                                        sExtent.setRect(sExtent.getX() - initialPoint.getX(), sExtent.getY(), sExtent.getWidth(), sExtent.getHeight());
877
                                }
878
                        }
879

    
880
                        if (hImg < minTilePrintHeight) {
881
                                double hScale = (double) minTilePrintHeight / hImg;
882
                                wmsStatus.setHeight(minTilePrintHeight);
883
                                Rectangle2D sExtent = wmsStatus.getExtent();
884
                                Point2D initialPoint = new Point2D.Double(sExtent.getX(), sExtent.getY());
885
                                sExtent.setRect(sExtent.getX(), sExtent.getY()*hScale, sExtent.getWidth(), sExtent.getHeight()*hScale);
886
                                if (!bBox.contains(initialPoint)) {
887
                                        sExtent.setRect(sExtent.getX(), sExtent.getY() - initialPoint.getY(), sExtent.getWidth(), sExtent.getHeight());
888
                                }
889
                        }
890

    
891
                        // end patch
892
                        File f = getDriver().getMap(wmsStatus, c);
893
                        if (f == null)
894
                                return;
895
                        String nameWordFile = f.getPath() + getExtensionWorldFile();
896
                        com.iver.andami.Utilities.createTemp(nameWordFile, this.getDataWorldFile(bBox, sz));
897

    
898
                        ViewPortData vpData = new ViewPortData(
899
                                vp.getProjection(), new Extent(bBox), sz );
900
                        vpData.setMat(vp.getAffineTransform());
901

    
902
                        rasterProcess(g, vpData, f);
903

    
904
                } catch (ValidationException e) {
905
                //azabala
906
//                        if (!c.isCanceled())
907
//                                throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
908

    
909
                        if (!c.isCanceled())
910
                        {
911
                                UnknownResponseFormatExceptionType type =
912
                                        new UnknownResponseFormatExceptionType();
913
                                type.setLayerName(getName());
914
                                try {
915
                                        type.setDriverName("WMS Driver");
916
                                } catch (Exception e1) {
917
                                        e1.printStackTrace();
918
                                }
919
                                type.setFormat(m_Format);
920
                                type.setHost(host);
921
                                type.setProtocol("WMS");
922
                                DriverException exception = new DriverException("unknown_response_format", type);
923
                                throw exception;
924
                        }
925
                } catch (UnsupportedVersionException e) {
926

    
927
//                        if (!c.isCanceled())
928
//                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
929

    
930
                        if (!c.isCanceled()){
931
                                UnsuportedProtocolVersionExceptionType type =
932
                                        new UnsuportedProtocolVersionExceptionType();
933
                                type.setLayerName(getName());
934
                                try {
935
                                        type.setDriverName("WMS Driver");
936
                                } catch (Exception ex){
937
                                }
938
                                type.setUrl(host);
939
                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e, type);
940
                        }
941

    
942
                } catch (IOException e) {
943
                        /*azabala
944
                        if (!c.isCanceled())
945
                                if (callCount<MAX_RETRY_TIMES) {
946
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null);
947
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error
948
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0)
949
                                        drawTile(g, vp, cancel);
950
                                }
951
                                if (callCount == 1) {
952
                                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
953
                                }
954
                        */
955
                        if (!c.isCanceled()){
956
                                if (callCount<MAX_RETRY_TIMES) { // mess code
957
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
958
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
959
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
960

    
961
                                        //FIXME Aqu? deberiamos llamar a drawTile o a drawFixedSize????
962
                                        drawFixedSize(g, vp, cancel); // mess code
963
                                } // mess code
964
                        }
965
                        if (callCount == 1) { // mess code
966
                                ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
967
                                type.setLayerName(getName());
968
                                try {
969
                                        type.setDriverName("WMS Driver");
970
                                } catch (Exception e1) {}
971
                                type.setHost(host);
972
                                throw new DriverException(PluginServices.
973
                                                        getText(this, "connect_error"), e, type);
974
                        }//if
975
                } catch (WMSException e) {
976
                        /*azabala
977
                        if (!c.isCanceled()) {
978
                                if (callCount<MAX_RETRY_TIMES) {
979
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawTile() ] Failed in trying " + callCount + "/" + MAX_RETRY_TIMES +" \n", null);
980
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error
981
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0)
982
                                        drawTile(g, vp, cancel);
983
                                }
984
                                if (callCount == 1) {
985
                                        if (!isPrinting) {
986
                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
987
                                                this.setVisible(false);
988
                                        }
989
                                }
990
                        }
991
                        */
992
                        if (!c.isCanceled()) {
993
                                if (callCount<MAX_RETRY_TIMES) { // mess code
994
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
995
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
996
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
997
                                        drawTile(g, vp, cancel);
998
                                } // mess code
999
                                if (callCount == 1) { // mess code
1000
//                azabala                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
1001
                                        WMSDriverExceptionType type = new WMSDriverExceptionType();
1002
                                        type.setLayerName(getName());
1003
                                        try {
1004
                                                type.setDriverName("WMS Driver");
1005
                                        } catch (Exception e1) {
1006
                                        }
1007
                                        type.setWcsStatus(this.wmsStatus);
1008
                                        if (!isPrinting)
1009
                                                this.setVisible(false);
1010
                                        throw new DriverException("Error WMS", e,  type);
1011

    
1012

    
1013
                                } //if
1014
                        }//if
1015
                }//catch
1016
                callCount--;
1017
        }
1018

    
1019
        /**
1020
         * Obtiene la extensi?n del fichero de georreferenciaci?n
1021
         * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
1022
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
1023
         */
1024
        private String getExtensionWorldFile(){
1025
                String extWorldFile = ".wld";
1026
            if(m_Format.equals("image/tif") || m_Format.equals("image/tiff"))
1027
                    extWorldFile = ".tfw";
1028
            if(m_Format.equals("image/jpeg"))
1029
                    extWorldFile = ".jpgw";
1030
            return extWorldFile;
1031
        }
1032

    
1033
        /**
1034
         * Calcula el contenido del fichero de georreferenciaci?n de una imagen.
1035
         * @param bBox Tama?o y posici?n de la imagen (en coordenadas de usuario)
1036
         * @param sz Tama?o de la imagen en pixeles.
1037
         * @return el 'WorldFile', como String.
1038
         * @throws IOException
1039
         */
1040
        public String getDataWorldFile(Rectangle2D bBox, Dimension sz) throws IOException {
1041
                StringBuffer data = new StringBuffer();
1042
            data.append((bBox.getMaxX() - bBox.getMinX())/(sz.getWidth() - 1)+"\n");
1043
            data.append("0.0\n");
1044
            data.append("0.0\n");
1045
            data.append("-"+(bBox.getMaxY() - bBox.getMinY())/(sz.getHeight() - 1)+"\n");
1046
            data.append(""+bBox.getMinX()+"\n");
1047
            data.append(""+bBox.getMaxY()+"\n");
1048
            return data.toString();
1049
        }
1050

    
1051
        /**
1052
         * Dibuja una imagen usando PxRaster
1053
         * @param g        Graphics2D en el que hay que dibujar.
1054
         * @param vpData Par?metros de visualizaci?n
1055
         * @param file La imagen en cuesti?n.
1056
         */
1057
        private void rasterProcess(Graphics2D g, ViewPortData vpData, File file) throws DriverException {
1058

    
1059
                //Creamos el PxRaster
1060
                try {
1061
                        rasterFile = new GdalFile(vpData.getProjection(), file.getAbsolutePath());
1062
                } catch (NotSupportedExtensionException e) {
1063
                        throw new DriverException("Open File Error");
1064
                }
1065
                raster = new PxRaster(rasterFile, null, rasterFile.getExtent());
1066
                grid = new Grid(rasterFile);
1067
                grid.addRenderizer(raster);
1068
                
1069
                if(status != null && firstLoad){
1070
                        status.applyStatus(this);
1071
                        firstLoad = false;
1072
                }
1073

    
1074
                //Recuperamos la pila de filtros si ya hubiese sido cargado antes
1075
                if(this.filterStack!=null)
1076
                        raster.filterStack = this.filterStack;
1077

    
1078
                raster.setTransparency(false);
1079

    
1080
                //Asignamos transparencia y orden de bandas
1081
                if(this.transparency == -1 && !firstLoad);
1082
                else
1083
                        raster.setTransparency(this.transparency);
1084

    
1085
                raster.setBand(GeoRasterFile.RED_BAND,rband);
1086
                raster.setBand(GeoRasterFile.GREEN_BAND, gband);
1087
                raster.setBand(GeoRasterFile.BLUE_BAND, bband);
1088

    
1089
                //Despues del primer pxRaster asignamos el stackManager guardado para los siguientes.
1090
                //Con esto conseguimos asignar los cambios que se hayan producido desde el cuadro de
1091
                //propiedades cuando creamos un nuevo pxRaster
1092
                if(this.stackManager != null)
1093
                        raster.setStackManager(this.stackManager);
1094

    
1095
                if(visualStatus != null){
1096
                        visualStatus.bandCount = raster.getBandCount();
1097
                        visualStatus.dataType = raster.getDataType();
1098
                }
1099

    
1100
                raster.draw(g, vpData);
1101

    
1102
                //En el primer pxRaster de una imagen obtenemos el Stack Manager para poder modificarlo
1103
                //si queremos desde las propiedades
1104

    
1105
                if(this.stackManager == null)
1106
                        this.stackManager = raster.getStackManager();
1107

    
1108
                if(this.filterStack == null)
1109
                        this.filterStack = raster.filterStack;
1110

    
1111
                //rasterFile.close();
1112
        }
1113

    
1114
        /**
1115
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D,
1116
         *                 com.iver.cit.gvsig.fmap.ViewPort,
1117
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
1118
         */
1119
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet properties)
1120
                throws DriverException {
1121
                if (isVisible() && isWithinScale(scale)){
1122
                isPrinting = true;
1123
                if (!mustTilePrint) {
1124
                        draw(null, g, viewPort, cancel,scale);
1125
                } else {
1126
                // Para no pedir imagenes demasiado grandes, vamos
1127
                // a hacer lo mismo que hace EcwFile: chunkear.
1128
                // Llamamos a drawView con cuadraditos m?s peque?os
1129
                // del BufferedImage ni caso, cuando se imprime viene con null
1130

    
1131
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
1132
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
1133
                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
1134
                            // Parte que dibuja
1135
                            try {
1136
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
1137
                                drawTile(g, vp, cancel);
1138
                                } catch (NoninvertibleTransformException e) {
1139
                                        e.printStackTrace();
1140
                                }
1141
                }
1142
                }
1143
            isPrinting = false;
1144
                }
1145
        }
1146

    
1147
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale)
1148
                throws DriverException {
1149
                draw(null, g, viewPort, cancel,scale);
1150
        }
1151

    
1152
        /**
1153
         * Devuelve el FMapWMSDriver.
1154
         *
1155
         * @return FMapWMSDriver
1156
         *
1157
         * @throws IllegalStateException
1158
         * @throws ValidationException
1159
         * @throws UnsupportedVersionException
1160
         * @throws IOException
1161
         */
1162
        private FMapWMSDriver getDriver()
1163
                throws IllegalStateException, ValidationException,
1164
                        UnsupportedVersionException, IOException {
1165
                return FMapWMSDriverFactory.getFMapDriverForURL(host);
1166
        }
1167

    
1168
        /**
1169
         * Devuelve el FMapWMSDriver.
1170
         *
1171
         * @return FMapWMSDriver
1172
         *
1173
         * @throws IllegalStateException
1174
         * @throws ValidationException
1175
         * @throws UnsupportedVersionException
1176
         * @throws IOException
1177
         */
1178
        public void setDriver(FMapWMSDriver drv) {
1179
                wms = drv;
1180
        }
1181

    
1182
        /**
1183
         * Devuelve el URL.
1184
         *
1185
         * @return URL.
1186
         */
1187
        public URL getHost() {
1188
                return host;
1189
        }
1190

    
1191
        /**
1192
         * Inserta el URL.
1193
         *
1194
         * @param host URL.
1195
         */
1196
        public void setHost(URL host) {
1197
                this.host = host;
1198
        }
1199

    
1200
        /**
1201
         * Devuelve la informaci?n de la consulta.
1202
         *
1203
         * @return String.
1204
         */
1205
        public String getInfoLayerQuery() {
1206
                return infoLayerQuery;
1207
        }
1208

    
1209
        /**
1210
         * Inserta la informaci?n de la consulta.
1211
         *
1212
         * @param infoLayerQuery String.
1213
         */
1214
        public void setInfoLayerQuery(String infoLayerQuery) {
1215
                this.infoLayerQuery = infoLayerQuery;
1216
        }
1217

    
1218
        /**
1219
         * Devuelve la consulta.
1220
         *
1221
         * @return String.
1222
         */
1223
        public String getLayerQuery() {
1224
                return layerQuery;
1225
        }
1226

    
1227
        /**
1228
         * Inserta la consulta.
1229
         *
1230
         * @param layerQuery consulta.
1231
         */
1232
        public void setLayerQuery(String layerQuery) {
1233
                this.layerQuery = layerQuery;
1234
        }
1235

    
1236
        /**
1237
         * Devuelve el formato.
1238
         *
1239
         * @return Formato.
1240
         */
1241
        public String getFormat() {
1242
                return m_Format;
1243
        }
1244

    
1245
        /**
1246
         * Inserta el formato.
1247
         *
1248
         * @param format Formato.
1249
         */
1250
        public void setFormat(String format) {
1251
                m_Format = format;
1252
        }
1253

    
1254
        /**
1255
         * Devuelve el SRS.
1256
         *
1257
         * @return SRS.
1258
         */
1259
        public String getSRS() {
1260
                return m_SRS;
1261
        }
1262

    
1263
        /**
1264
         * Inserta el SRS.
1265
         *
1266
         * @param m_srs SRS.
1267
         */
1268
        public void setSRS(String m_srs) {
1269
                m_SRS = m_srs;
1270
        }
1271

    
1272
        /**
1273
         * Inserta la extensi?n total de la capa.
1274
         *
1275
         * @param fullExtent Rect?ngulo.
1276
         */
1277
        public void setFullExtent(Rectangle2D fullExtent) {
1278
                this.fullExtent = fullExtent;
1279
        }
1280

    
1281
        public HashMap getProperties() {
1282
                HashMap info = new HashMap();
1283
        String[] layerNames = getLayerQuery().split(",");
1284
        Vector layers = new Vector(layerNames.length);
1285
        try {
1286
            if(getDriver().connect(null)){
1287
                for (int i = 0; i < layerNames.length; i++) {
1288
                    layers.add(i, getDriver().getLayer(layerNames[i]));
1289
                }
1290
                info.put("name", getName());
1291
                info.put("selectedLayers", layers);
1292
                info.put("host", getHost());
1293
                info.put("srs", getSRS());
1294
                info.put("format", getFormat());
1295
                info.put("wmsTransparency", new Boolean(wmsTransparency));
1296
                info.put("styles", styles);
1297
                info.put("dimensions", dimensions);
1298
                info.put("fixedSize", fixedSize);
1299
                return info;
1300
            }
1301
        } catch (Exception e) {
1302
            e.printStackTrace();
1303
        }
1304
        return null;
1305
        }
1306

    
1307
        /**
1308
         * Asignar el estado del raster
1309
         * @param status
1310
         */
1311
        public void setStatus(StatusRasterInterface status){
1312
                this.status = status;
1313
        }
1314

    
1315
        /**
1316
         * Obtiene el estado del raster
1317
         * @return
1318
         */
1319
        public StatusRasterInterface getStatus(){
1320
                return this.status;
1321
        }
1322

    
1323
        /* (non-Javadoc)
1324
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getAttributes()
1325
         */
1326
        public ArrayList getAttributes() {
1327
                if(rasterFile != null){
1328
                        ArrayList attr = new ArrayList();
1329
                        String dataType = "Byte";
1330
                        if (rasterFile.getDataType() == DataBuffer.TYPE_BYTE) dataType = "Byte";
1331
                        else if (visualStatus.dataType == DataBuffer.TYPE_SHORT)
1332
                                dataType = "Short";
1333
                        else if (visualStatus.dataType == DataBuffer.TYPE_USHORT)
1334
                                dataType = "Unsigned Short";
1335
                        else if (visualStatus.dataType == DataBuffer.TYPE_INT)
1336
                                dataType = "Integer";
1337
                        else if (visualStatus.dataType == DataBuffer.TYPE_FLOAT)
1338
                                dataType = "Float";
1339
                        else if (visualStatus.dataType == DataBuffer.TYPE_DOUBLE)
1340
                                dataType = "Double";
1341
                        else
1342
                                dataType = "Unknown";
1343

    
1344
                        Object [][] a = {
1345
                                {"Filename",rasterFile.getName().substring(rasterFile.getName().lastIndexOf("/")+1, rasterFile.getName().length())},
1346
                                {"Filesize",new Long(0)},
1347
                                {"Width",new Integer((int)this.getWidth())},
1348
                                {"Height", new Integer((int)this.getHeight())},
1349
                                {"Bands", new Integer(visualStatus.bandCount)},
1350
                                {"BandDataType", dataType}
1351
                        };
1352
                        for (int i=0; i<a.length; i++)
1353
                                attr.add(a[i]);
1354

    
1355
                        return attr;
1356
                }
1357
                return  null;
1358
        }
1359

    
1360
        /* (non-Javadoc)
1361
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getFilterStack()
1362
         */
1363
        public RasterFilterStack getFilterStack() {
1364
                if(raster!=null)
1365
                        return raster.filterStack;
1366
                return null;
1367
        }
1368
        /* (non-Javadoc)
1369
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getHeight()
1370
         */
1371
        public double getHeight() {
1372
                return visualStatus.height;
1373
        }
1374

    
1375
        /* (non-Javadoc)
1376
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxX()
1377
         */
1378
        public double getMaxX() {
1379
                return visualStatus.maxX;
1380
        }
1381

    
1382
        /* (non-Javadoc)
1383
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxY()
1384
         */
1385
        public double getMaxY() {
1386
                return visualStatus.maxY;
1387
        }
1388

    
1389
        /* (non-Javadoc)
1390
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinX()
1391
         */
1392
        public double getMinX() {
1393
                return visualStatus.minX;
1394
        }
1395

    
1396
        /* (non-Javadoc)
1397
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinY()
1398
         */
1399
        public double getMinY() {
1400
                return visualStatus.minY;
1401
        }
1402
        /* (non-Javadoc)
1403
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getPixel(double, double)
1404
         */
1405
        public int[] getPixel(double wcx, double wcy) {
1406
                if(getPxRaster() != null)
1407
                        return getPxRaster().getPixel(wcx, wcy);
1408
        return null;
1409
        }
1410
        /* (non-Javadoc)
1411
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getSource()
1412
         */
1413
        public RasterAdapter getSource() {
1414
                return null;
1415
        }
1416
        /* (non-Javadoc)
1417
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getWidth()
1418
         */
1419
        public double getWidth() {
1420
                return visualStatus.width;
1421
        }
1422
        /* (non-Javadoc)
1423
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setBand(int, int)
1424
         */
1425
        public void setBand(int flag, int nBand) {
1426
                switch(flag){
1427
                case GeoRasterFile.RED_BAND:setBandR(nBand);break;
1428
                case GeoRasterFile.GREEN_BAND:setBandG(nBand);break;
1429
                case GeoRasterFile.BLUE_BAND:setBandB(nBand);break;
1430
                }
1431
        }
1432
        /* (non-Javadoc)
1433
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setFilterStack(org.cresques.io.raster.RasterFilterStack)
1434
         */
1435
        public void setFilterStack(RasterFilterStack stack) {
1436
                this.filterStack = stack;
1437
        }
1438
        /* (non-Javadoc)
1439
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPos(int, int)
1440
         */
1441
        public void setPos(int x, int y) {
1442
                this.posX = x;
1443
                this.posY = y;
1444
        }
1445

    
1446
        /* (non-Javadoc)
1447
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPosWC(double, double)
1448
         */
1449
        public void setPosWC(double x, double y) {
1450
                this.posXWC = x;
1451
                this.posYWC = y;
1452
        }
1453

    
1454
        /* (non-Javadoc)
1455
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setRGB(int, int, int)
1456
         */
1457
        public void setRGB(int r, int g, int b) {
1458
                this.r = r;
1459
                this.g = g;
1460
                this.b = b;
1461
        }
1462
        /* (non-Javadoc)
1463
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setSource(com.iver.cit.gvsig.fmap.layers.RasterAdapter)
1464
         */
1465
        public void setSource(RasterAdapter ra) {
1466
        }
1467
        /**
1468
         * @return Returns the raster.
1469
         */
1470
        public PxRaster getPxRaster() {
1471
                return raster;
1472
        }
1473
        /**
1474
         * @return Returns the rasterFile.
1475
         */
1476
        public GeoRasterFile getGeoRasterFile() {
1477
                return rasterFile;
1478
        }
1479

    
1480
        public void setTransparency(int trans) {
1481
                this.transparency = trans;
1482
        }
1483

    
1484
        /**
1485
         * Sets the R-band.
1486
         *
1487
         * Asigna la banda R.
1488
         * @param r
1489
         */
1490
        public void setBandR(int r){
1491
                this.rband = r;
1492
        }
1493

    
1494
        /**
1495
         * Sets the G-band.
1496
         *
1497
         * Asigna la banda G
1498
         * @param g
1499
         */
1500
        public void setBandG(int g){
1501
                this.gband = g;
1502
        }
1503

    
1504
        /**
1505
         * Sets the B-band.
1506
         *
1507
         * Asigna la banda B
1508
         * @param b
1509
         */
1510
        public void setBandB(int b){
1511
                this.bband = b;
1512
        }
1513

    
1514
    /**
1515
     * @return Returns the wmsTransparency.
1516
     */
1517
    public boolean isWmsTransparent() {
1518
        return wmsTransparency;
1519
    }
1520

    
1521
    /**
1522
     * @param wmsTransparency The wmsTransparency to set.
1523
     */
1524
    public void setWmsTransparency(boolean wmsTransparency) {
1525
        this.wmsTransparency = wmsTransparency;
1526
    }
1527

    
1528
     /**
1529
     * @param styles
1530
     */
1531
    public void setStyles(Vector styles) {
1532
            //laura:
1533
            //layer query is built with the layer in reverse order
1534
            // so here we build the styles upside-down.
1535
            if (styles != null)
1536
            {
1537
                    this.styles = new Vector();
1538
                    for(int i = styles.size()-1; i>=0; i--)
1539
                    {
1540
                            this.styles.add(styles.elementAt(i));
1541
                    }
1542
            }
1543
    }
1544

    
1545
    /**
1546
     * Sets the dimension vector that is a list of key-value pairs containing
1547
     * the name of the dimension and the value for it
1548
     * @param dimensions
1549
     */
1550
    public void setDimensions(Vector dimensions) {
1551
        this.dimensions = dimensions;
1552
    }
1553

    
1554
    /**
1555
     * Sets the set of URLs that should be accessed for each operation performed
1556
     * to the server.
1557
     *
1558
     * @param onlineResources
1559
     */
1560
        public void setOnlineResources(Hashtable onlineResources) {
1561
                this.onlineResources = onlineResources;
1562
        }
1563

    
1564
    /**
1565
     * Gets the URL that should be accessed for an operation performed
1566
     * to the server.
1567
     *
1568
     * @param onlineResources
1569
     */
1570
        public String getOnlineResource(String operation) {
1571
                return ((String) onlineResources.get(operation));
1572
        }
1573

    
1574
        /**
1575
         * When a server is not fully featured and it only can serve constant map
1576
         * sizes this value must be set. It expresses the size in pixels (width, height)
1577
         * that the map will be requested.
1578
         * @param Dimension sz
1579
         */
1580
        public void setFixedSize(Dimension sz) {
1581
                fixedSize = sz;
1582
        }
1583

    
1584
        /**
1585
         * Tells whether if this layer must deal with the server with the constant-size
1586
         * limitations or not.
1587
         * @return boolean.
1588
         */
1589
        private boolean isSizeFixed() {
1590
                return fixedSize != null && fixedSize.getWidth() > 0 && fixedSize.getHeight() > 0;
1591
        }
1592

    
1593
        /**
1594
         * If it is true, this layer accepts GetFeatureInfo operations. This WMS operations
1595
         * maps to FMap's infoByPoint(p) operation.
1596
         * @param b
1597
         */
1598
        public void setQueryable(boolean b) {
1599
                queryable = b;
1600
        }
1601

    
1602
        /**
1603
         * Creates the part of a OGC's MapContext document that would describe this
1604
         * layer(s).
1605
         * @param version, The desired version of the resulting document. (1.1.0)
1606
         * @return String containing the xml.
1607
         * @throws UnsupportedVersionException
1608
         */
1609
        public String toMapContext(String mapContextVersion) {
1610
                XmlBuilder xml = new XmlBuilder();
1611
                FMapWMSDriver drv;
1612
                try {
1613
                        drv = getDriver();
1614
                } catch (Exception e) {
1615
                        return xml.toString();
1616
                }
1617
                String[] layerNames = getLayerQuery().split(",");
1618
                String[] styleNames = (String[]) styles.toArray(new String[0]);
1619
                for (int i = 0; i < layerNames.length; i++) {
1620
                        WMSLayerNode layer = drv.getLayer(layerNames[i]);
1621
                        HashMap xmlAttrs = new HashMap();
1622

    
1623
                        // <Layer>
1624
                        xmlAttrs.put(WebMapContextTags.HIDDEN, !isVisible()+"");
1625
                        xmlAttrs.put(WebMapContextTags.QUERYABLE, queryable+"");
1626
                        xml.openTag(WebMapContextTags.LAYER, xmlAttrs);
1627
                        xmlAttrs.clear();
1628
                        if (mapContextVersion.equals("1.1.0") || mapContextVersion.equals("1.0.0")) {
1629
                                // <Server>
1630
                                xmlAttrs.put(WebMapContextTags.SERVICE, WebMapContextTags.WMS);
1631
                                xmlAttrs.put(WebMapContextTags.VERSION, drv.getVersion());
1632
                                xmlAttrs.put(WebMapContextTags.SERVER_TITLE, drv.getServiceTitle());
1633
                                xml.openTag(WebMapContextTags.SERVER, xmlAttrs);
1634
                                xmlAttrs.clear();
1635

    
1636
                                        // <OnlineResource>
1637
                                        xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1638
                                        xmlAttrs.put(WebMapContextTags.XLINK_HREF, getHost().toString());
1639
                                        xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1640
                                        xmlAttrs.clear();
1641
                                        // </OnlineResource>
1642

    
1643
                                xml.closeTag();
1644
                                // </Server>
1645

    
1646
                                // <Name>
1647
                                xml.writeTag(WebMapContextTags.NAME, layer.getName().trim());
1648
                                // </Name>
1649

    
1650
                                // <Title>
1651
                                xml.writeTag(WebMapContextTags.TITLE, layer.getTitle().trim());
1652
                                //?xml.writeTag(WebMapContextTags.TITLE, getName().trim());
1653
                                // </Title>
1654

    
1655
                                // <Abstract>
1656
                                if (layer.getAbstract() != null)
1657
                                        xml.writeTag(WebMapContextTags.ABSTRACT, layer.getAbstract());
1658
                                // </Abstract>
1659

    
1660
                                // <SRS> (a list of available SRS for the enclosing layer)
1661
                                String[] strings = (String[]) layer.getAllSrs().toArray(new String[0]);
1662
                                String mySRS = strings[0];
1663
                                for (int j = 1; j < strings.length; j++) {
1664
                                        mySRS += ","+strings[j];
1665
                                }
1666
                                xml.writeTag(WebMapContextTags.SRS, mySRS);
1667
                                // </SRS>
1668

    
1669
                                // <FormatList>
1670
                                xml.openTag(WebMapContextTags.FORMAT_LIST);
1671
                                        strings = (String[]) drv.getFormats().toArray(new String[0]);
1672
                                        for (int j = 0; j < strings.length; j++) {
1673
                    // <Format>
1674
                                                String str = strings[j].trim();
1675
                                                if (str.equals(getFormat()))
1676
                                                        xml.writeTag(WebMapContextTags.FORMAT, str, WebMapContextTags.CURRENT, "1");
1677
                                                else
1678
                                                        xml.writeTag(WebMapContextTags.FORMAT, str);
1679
                    // </Format>
1680
                                        }
1681
                                xml.closeTag();
1682
                                // </FormatList>
1683

    
1684
                                // <StyleList>
1685
                                xml.openTag(WebMapContextTags.STYLE_LIST);
1686

    
1687
                                        if (layer.getStyles().size()>0) {
1688
                                                for (int j = 0; j < layer.getStyles().size(); j++) {
1689
                                                        // <Style>
1690
                                                        FMapWMSStyle st = (FMapWMSStyle) layer.getStyles().get(j);
1691
                                                        if (st.name.equals(styleNames[i]))
1692
                                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1693
                                                        xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1694
                                                        xmlAttrs.clear();
1695

    
1696
                                                                // <Name>
1697
                                                                xml.writeTag(WebMapContextTags.NAME, st.name);
1698
                                                                // </Name>
1699

    
1700
                                                                // <Title>
1701
                                                                xml.writeTag(WebMapContextTags.TITLE, st.title);
1702
                                                                // </Title>
1703

    
1704
                                                                // <LegendURL width="180" format="image/gif" height="50">
1705
                                                                        // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1706
                                                                        // </OnlineResource>
1707
                                                                // </LegendURL>
1708
                                                        xml.closeTag();
1709
                                                        // </Style>
1710

    
1711
                                                }
1712

    
1713
                                        } else {
1714
                                                // Create fake style (for compatibility issues)
1715
                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1716
                                                // <Style>
1717
                                                xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1718
                                                        xmlAttrs.clear();
1719
                                                        // <Name>
1720
                                                        xml.writeTag(WebMapContextTags.NAME, "default");
1721
                                                        // </Name>
1722

    
1723
                                                        // <Title>
1724
                                                        xml.writeTag(WebMapContextTags.TITLE, "default");
1725
                                                        // </Title>
1726

    
1727
//                                                        // <LegendURL width="180" format="image/gif" height="50">
1728
//                                                        xmlAttrs.put(WebMapContextTags.WIDTH, "0");
1729
//                                                        xmlAttrs.put(WebMapContextTags.HEIGHT, "0");
1730
//                                                        xmlAttrs.put(WebMapContextTags.FORMAT.toLowerCase(), "image/gif");
1731
//                                                        xml.openTag(WebMapContextTags.LEGEND_URL, xmlAttrs);
1732
//                                                        xmlAttrs.clear();
1733
//                                                                // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1734
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1735
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_HREF, "http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif");
1736
//                                                                xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1737
//                                                                // </OnlineResource>
1738
//                                                    // </LegendURL>
1739
//                                                        xml.closeTag();
1740
                                                // </Style>
1741
                                                xml.closeTag();
1742
                                        }
1743
                                // </StyleList>
1744
                                xml.closeTag();
1745
                                if (mapContextVersion.compareTo("1.0.0") > 0) {
1746
                                // <DimensionList>
1747
                                        xml.openTag(WebMapContextTags.DIMENSION_LIST);
1748
                                        // <Dimension>
1749
                                        // </Dimension>
1750
                                        xml.closeTag();
1751
                                // </DimensionList>
1752
                                }
1753
                        } else {
1754
                                xml.writeTag("ERROR", PluginServices.getText(this, "unsupported_map_context_version"));
1755
                        }
1756
                        // </Layer>
1757
                        xml.closeTag();
1758
                }
1759
                return xml.getXML();
1760
        }
1761

    
1762
        public ImageIcon getTocImageIcon() {
1763
                return new ImageIcon(PluginServices.getPluginServices("com.iver.cit.gvsig.wms").getClassLoader().getResource("images/icoLayer.png"));
1764
        }
1765

    
1766
        /*
1767
         *  (non-Javadoc)
1768
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1769
         */
1770
        public int[] getTileSize() {
1771
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1772
                return size;
1773
        }
1774
        /*
1775
         *  (non-Javadoc)
1776
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1777
         */
1778
        public boolean isTiled() {
1779
                return mustTileDraw;
1780
        }
1781

    
1782
        public Image getImageLegend() {
1783
                try {
1784
                        //TODO:
1785
                        //store legend graphic and show it in TOC only when layer visible
1786
                        if (wms.hasLegendGraphic()){
1787
                                wmsStatus.setOnlineResource((String) onlineResources.get("GetLegendGraphic"));
1788
                                File legend = getDriver().getLegendGraphic(wmsStatus, layerQuery, null);
1789
                                Image img = null;
1790
                                if ((legend!= null) && (legend.length() > 0))
1791
                                        img = ImageIO.read(legend);
1792
                                return img;
1793
                        }else{
1794
                                return null;
1795
                        }
1796
                }catch(Exception e){
1797
                        //e.printStackTrace();
1798
                        return null;
1799
                }
1800
        }
1801

    
1802
        /**
1803
         * Obtiene el grid asociado al raster que hay cargado en ese momento
1804
         * @return grid
1805
         */
1806
        public Grid getGrid(){
1807
                return grid;
1808
        }
1809
        
1810
        /**
1811
         * Obtiene el tipo de dato de la capa raster
1812
         * @return Entero que representa el tipo de dato de la capa raster.
1813
         */
1814
        public int getDataType() {
1815
                return rasterFile.getDataType();
1816
        }
1817
        public boolean isQueryable(){
1818
                return queryable;
1819
        }
1820
}