Statistics
| Revision:

svn-gvsig-desktop / tags / v1_0_2_Build_900 / extensions / extWMS / src / com / iver / cit / gvsig / fmap / layers / FLyrWMS.java @ 10562

History | View | Annotate | Download (55.9 KB)

1 4503 jaume
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2 3746 jaume
*
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 4503 jaume
*   Av. Blasco Ib??ez, 50
24 3746 jaume
*   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 3841 nacho
import java.awt.Dimension;
45 3746 jaume
import java.awt.Graphics2D;
46 8765 jjdelcerro
import java.awt.Image;
47 3746 jaume
import java.awt.Point;
48 3840 nacho
import java.awt.Rectangle;
49 3746 jaume
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 4378 nacho
import java.awt.image.DataBuffer;
55 3746 jaume
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 3841 nacho
import java.util.Hashtable;
64 4222 jaume
import java.util.Iterator;
65 4677 jorpiell
import java.util.Map;
66 3746 jaume
import java.util.Vector;
67
68 8765 jjdelcerro
import javax.imageio.ImageIO;
69 9013 caballero
import javax.print.attribute.PrintRequestAttributeSet;
70 5763 jmvivo
import javax.swing.ImageIcon;
71 3746 jaume
import javax.swing.JOptionPane;
72
73 5981 nacho
import org.cresques.filter.RasterFilterStack;
74
import org.cresques.filter.RasterFilterStackManager;
75 3746 jaume
import org.cresques.geo.ViewPortData;
76 5991 nacho
import org.cresques.io.GdalFile;
77 3746 jaume
import org.cresques.io.GeoRasterFile;
78 9056 nacho
import org.cresques.io.data.Grid;
79
import org.cresques.io.exceptions.NotSupportedExtensionException;
80 3746 jaume
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 5409 jaume
import org.gvsig.remoteClient.wms.ICancellable;
85 3746 jaume
import org.gvsig.remoteClient.wms.WMSStatus;
86
87
import com.iver.andami.PluginServices;
88 4222 jaume
import com.iver.andami.messages.NotificationManager;
89 8765 jjdelcerro
import com.iver.cit.gvsig.fmap.ConnectionErrorExceptionType;
90 3746 jaume
import com.iver.cit.gvsig.fmap.DriverException;
91 8765 jjdelcerro
import com.iver.cit.gvsig.fmap.UnknownResponseFormatExceptionType;
92
import com.iver.cit.gvsig.fmap.UnsuportedProtocolVersionExceptionType;
93 3746 jaume
import com.iver.cit.gvsig.fmap.ViewPort;
94 8765 jjdelcerro
import com.iver.cit.gvsig.fmap.WMSDriverExceptionType;
95 3746 jaume
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 5279 jmvivo
import com.iver.cit.gvsig.fmap.drivers.wms.FMapWMSDriverFactory;
99 5409 jaume
import com.iver.cit.gvsig.fmap.drivers.wms.WMSException;
100 4730 jaume
import com.iver.cit.gvsig.fmap.layers.WMSLayerNode.FMapWMSStyle;
101 8765 jjdelcerro
import com.iver.cit.gvsig.fmap.layers.layerOperations.IHasImageLegend;
102 3746 jaume
import com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint;
103 5055 ldiaz
import com.iver.cit.gvsig.fmap.layers.layerOperations.StringXMLItem;
104 5203 ldiaz
import com.iver.cit.gvsig.fmap.layers.layerOperations.XMLItem;
105 4730 jaume
import com.iver.cit.gvsig.fmap.rendering.XmlBuilder;
106 5023 jaume
import com.iver.cit.gvsig.wmc.WebMapContextTags;
107 3746 jaume
import com.iver.utiles.StringUtilities;
108
import com.iver.utiles.XMLEntity;
109 5347 jaume
import com.iver.utiles.swing.threads.Cancellable;
110 3746 jaume
111
112 5203 ldiaz
113 3746 jaume
/**
114 4222 jaume
* FMap's WMS Layer class.
115 3746 jaume
*
116 3749 jaume
* @author Jaume Dominguez Faus
117 8765 jjdelcerro
*                   Nacho Brodin
118 6050 jaume
*
119 3746 jaume
*/
120 8765 jjdelcerro
public class FLyrWMS extends FLyrDefault implements InfoByPoint, RasterOperations, IHasImageLegend {
121 4222 jaume
        private boolean                                         isPrinting = false;
122 5534 nacho
        private boolean                                         mustTileDraw = true;
123 4222 jaume
        private boolean                                         mustTilePrint = true;
124 5534 nacho
        private final int                                         maxTileDrawWidth = 1023;
125
        private final int                                         maxTileDrawHeight = 1023;
126
        private final int                                         maxTilePrintWidth = 1023;
127
        private final int                                         maxTilePrintHeight = 1023;
128 6822 jaume
        private final int                                        minTilePrintWidth = 12;
129
        private final int                                        minTilePrintHeight = 12;
130 6050 jaume
131 4222 jaume
    public URL                                                         host;
132
    public String                                                 m_Format;
133 6050 jaume
134 4222 jaume
        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 3746 jaume
        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 3756 jaume
        private boolean                                                firstLoad = false;
151 3746 jaume
        private int                                                 transparency = -1;
152
        private int                                                 rband = 0, gband = 1, bband = 2;
153
        private RasterFilterStackManager        stackManager = null;
154 4222 jaume
        private Hashtable                                         onlineResources = new Hashtable();
155
        private Dimension                                         fixedSize;
156
        private boolean                                         queryable = true;
157
        private VisualStatusWMS                                visualStatus = new VisualStatusWMS();
158 9056 nacho
        private Grid                                                grid = null;
159 6050 jaume
160
161 5409 jaume
        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 8765 jjdelcerro
                        if (original == null) return false;
170 5409 jaume
                        return original.isCanceled();
171
                }
172 6050 jaume
173 5409 jaume
        }
174 6050 jaume
175 4677 jorpiell
        public FLyrWMS(){
176
                super();
177
        }
178 6050 jaume
179 4677 jorpiell
        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 6050 jaume
188 4677 jorpiell
                try {
189
                        this.setHost(new URL(host));
190
                } catch (MalformedURLException e) {
191
                        //e.printStackTrace();
192 6050 jaume
                        throw new DriverIOException("Malformed host URL, '" + host + "' (" + e.toString() + ").");
193 4677 jorpiell
                }
194
                try {
195 10208 jorpiell
                        drv = this.getDriver();
196 4677 jorpiell
                } catch (Exception e) {
197
                        // e.printStackTrace();
198 6050 jaume
                        throw new DriverIOException("Can't get driver to host '" + host + "' (" + e.toString() + ").");
199 4677 jorpiell
                }
200
                if( sFormat == null || sSRS == null || fullExtent == null ) {
201 5409 jaume
                        if (!drv.connect(null))
202 6050 jaume
                                throw new DriverIOException("Can't connect to host '" + host + "'.");
203
204 4677 jorpiell
                        WMSLayerNode wmsNode = drv.getLayer(sLayer);
205 10208 jorpiell
206 4677 jorpiell
                        if (wmsNode == null){
207
                                throw new DriverIOException("The server '" + host + "' doesn't has the layer '" + sLayer + "'.");
208 6050 jaume
                        }
209 4677 jorpiell
                        if( sFormat == null ) {
210
                                sFormat = this.getGreatFormat(drv.getFormats());
211
                        }
212 10208 jorpiell
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 9536 jcampos
                             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 4677 jorpiell
                     }
234
                        if( fullExtent == null ) {
235 10208 jorpiell
                                fullExtent = drv.getLayersExtent(sLayers,sSRS);
236 4677 jorpiell
                        }
237
                }
238 6050 jaume
239
240 4677 jorpiell
                this.setFullExtent(fullExtent);
241
                this.setFormat(sFormat);
242
                this.setLayerQuery(sLayer);
243
                this.setInfoLayerQuery("");
244
                this.setSRS(sSRS);
245
                this.setName(sLayer);
246 10208 jorpiell
                this.setOnlineResources(drv.getOnlineResources());
247
                load();
248 4677 jorpiell
        }
249 6050 jaume
250 4222 jaume
        /**
251 6050 jaume
         * It choose the best format to load different maps if the server
252
         * supports it. This format could be png, because it supports
253 4677 jorpiell
         * transparency.
254
         * @param formats
255
         * Arraywith all the formats supported by the server
256
         * @return
257 6050 jaume
         */
258 4677 jorpiell
        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 6050 jaume
269 4677 jorpiell
            return (String)formats.get(0);
270
        }
271 6050 jaume
272 4677 jorpiell
        /**
273 9056 nacho
         * 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 4222 jaume
         * @author Nacho Brodin (brodin_ign@gva.es)
278
         */
279
        private class VisualStatusWMS{
280
                /**
281 6050 jaume
                 * Ancho y alto de la imagen o del conjunto de tiles si los tiene. Coincide con
282 4222 jaume
                 * 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 4378 nacho
                private int                                                 bandCount = 0;
287
                private int                                                        dataType = DataBuffer.TYPE_UNDEFINED;
288 9056 nacho
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 4222 jaume
        }
300 3746 jaume
301 6050 jaume
302 3746 jaume
        /**
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 4222 jaume
                // Full extent
313 3746 jaume
                xml.putProperty("fullExtent", StringUtilities.rect2String(fullExtent));
314 6050 jaume
315 4222 jaume
                // Host
316 3746 jaume
                xml.putProperty("host", host.toExternalForm());
317 6050 jaume
318 4222 jaume
                // Part of the query that is not the host, or the
319
                // layer names, or other not listed bellow
320 3746 jaume
                xml.putProperty("infoLayerQuery", infoLayerQuery);
321 6050 jaume
322 4222 jaume
                // Part of the query containing the layer names
323 3746 jaume
                xml.putProperty("layerQuery", layerQuery);
324 6050 jaume
325 4222 jaume
                // Format
326 3746 jaume
                xml.putProperty("format", m_Format);
327 6050 jaume
328 4222 jaume
                // SRS
329 3746 jaume
                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 6050 jaume
337 4222 jaume
        // Transparency
338 3746 jaume
        xml.putProperty("wms_transparency", wmsTransparency);
339 6050 jaume
340 4222 jaume
        // Styles
341 3746 jaume
        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 4222 jaume
            if (stylePr.endsWith(","))
349
                    stylePr += " ";
350 3746 jaume
            xml.putProperty("styles", stylePr);
351
        }
352 6050 jaume
353
        // Dimensions
354 3746 jaume
        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 4222 jaume
            if (dim.endsWith(","))
362
                    dim += " ";
363 3746 jaume
            xml.putProperty("dimensions", dim);
364
        }
365 6050 jaume
366 4222 jaume
        // 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 6050 jaume
378 4222 jaume
        // Queryable
379
        xml.putProperty("queryable", queryable);
380 6050 jaume
381 4222 jaume
        // fixedSize
382
        if (isSizeFixed()) {
383
                xml.putProperty("fixedSize", true);
384
                xml.putProperty("fixedWidth", fixedSize.width);
385
                xml.putProperty("fixedHeight", fixedSize.height);
386
        }
387 3746 jaume
        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 6050 jaume
432 4222 jaume
                // Host
433 3746 jaume
                try {
434
                        host = new URL(xml.getStringProperty("host"));
435
                } catch (MalformedURLException e) {
436
                        throw new XMLException(e);
437
                }
438
439 4222 jaume
                // Part of the query that is not the host, or the
440
                // layer names, or other not listed bellow
441 3746 jaume
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
442 4222 jaume
443
                // Part of the query containing the layer names
444 3746 jaume
                layerQuery = xml.getStringProperty("layerQuery");
445 6050 jaume
446 4222 jaume
                // Format
447 3746 jaume
                m_Format = xml.getStringProperty("format");
448 6050 jaume
449 4222 jaume
                // SRS
450 3746 jaume
                m_SRS = xml.getStringProperty("srs");
451 6050 jaume
452 4222 jaume
                String claseStr = StatusLayerRaster.defaultClass;
453 3746 jaume
                if (xml.contains("raster.class")) {
454
                        claseStr = xml.getStringProperty("raster.class");
455
                }
456 6050 jaume
457 4222 jaume
                // Transparency
458 3746 jaume
        if (xml.contains("wms_transparency"))
459
            wmsTransparency = xml.getBooleanProperty("wms_transparency");
460 6050 jaume
461 4222 jaume
        // Styles
462 3746 jaume
        if (xml.contains("styles")){
463
            styles = new Vector();
464
            String[] stl = xml.getStringProperty("styles").split(",");
465 6050 jaume
466 3746 jaume
            for (int i = 0; i < stl.length; i++) {
467 4222 jaume
                    if (stl[i].equals(" "))
468
                            stl[i]="";
469 3746 jaume
                styles.add(stl[i]);
470
            }
471
        }
472 6050 jaume
473 4222 jaume
        // Dimensions
474 3746 jaume
        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 4222 jaume
                    if (dims[i].equals(" "))
479
                            dims[i]="";
480 6050 jaume
481 3746 jaume
                dimensions.add(dims[i]);
482
            }
483
        }
484 6050 jaume
485 4222 jaume
        // 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 6050 jaume
495 4222 jaume
        // 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 6050 jaume
500 4222 jaume
        // fixedSize
501
        if (xml.contains("fixedSize")) {
502 6050 jaume
                fixedSize = new Dimension(xml.getIntProperty("fixedWidth"),
503 4222 jaume
                                                  xml.getIntProperty("fixedHeight"));
504
        }
505 6050 jaume
506 3746 jaume
                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 6050 jaume
                                }
527 3746 jaume
                        }
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 8765 jjdelcerro
        public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancellable) throws DriverException {
536 5055 ldiaz
                XMLItem[] item =  new XMLItem[1];
537 6050 jaume
                try {
538 4222 jaume
                        if (queryable)
539
                        {
540
                                //TODO
541
                                // check if there are layers which are not queryable
542 6881 cesar
                                ViewPort viewPort = getMapContext().getViewPort();
543 4222 jaume
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 6050 jaume
554 4222 jaume
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileIndex);
555 8907 jaume
                                wmsStatus.setExtent(vp.getAdjustedExtent());
556 4222 jaume
                                wmsStatus.setHeight(vp.getImageHeight());
557
                                wmsStatus.setWidth(vp.getImageWidth());
558
                                wmsStatus.setOnlineResource((String) onlineResources.get("GetFeatureInfo"));
559 10527 ldiaz
560
                                //This is in the case we call layer.getInfo outside the info tool.
561 10522 ldiaz
                                if (wmsStatus.getSrs() == null){
562
                                        wmsStatus.setSrs(this.m_SRS);
563
                                }
564 10527 ldiaz
                                if(wmsStatus.getFormat() == null){
565
                                        wmsStatus.setFormat(this.m_Format);
566
                                }
567
                                if(wmsStatus.getLayerNames().isEmpty()){
568
                                        wmsStatus.addLayerName(this.getLayerQuery());
569
                                }
570
571 8765 jjdelcerro
                                MyCancellable c = new MyCancellable(cancellable);
572 5055 ldiaz
                                item[0] = new StringXMLItem(new String(getDriver()
573 8765 jjdelcerro
                                                .getFeatureInfo(wmsStatus, (int) tiledPoint.getX(), (int) tiledPoint.getY(), Integer.MAX_VALUE, c)),this);
574 5055 ldiaz
                                return item;
575 4222 jaume
                        }
576
                        else
577
                        {
578 8765 jjdelcerro
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),this.getName() + " " +
579
                                                PluginServices.getText(this,"layer_not_queryable"));
580 5203 ldiaz
                                item[0] =  new StringXMLItem("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><info></info>",this);
581 5055 ldiaz
                                return item;
582 8765 jjdelcerro
                                //return null;
583 4222 jaume
                        }
584 3746 jaume
                } catch (WMSException  e) {
585 5055 ldiaz
                        item[0] = new StringXMLItem("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><exception>" +
586 5203 ldiaz
                        e.getMessage() + "</exception>", this);
587 5055 ldiaz
                        return item;
588 8765 jjdelcerro
                }
589
                /*azabala
590
                catch (ValidationException e) {
591 4222 jaume
                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
592 3746 jaume
                } catch (UnsupportedVersionException e) {
593 4222 jaume
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
594 3746 jaume
                } catch (IOException e) {
595 4222 jaume
                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
596 8765 jjdelcerro
                }
597
                */
598
                catch (ValidationException e) {
599
                        UnknownResponseFormatExceptionType type =
600
                                new UnknownResponseFormatExceptionType();
601
                        type.setLayerName(getName());
602
                        try {
603
                                type.setDriverName("WMS Driver");
604
                        } catch (Exception e1) {
605
                                e1.printStackTrace();
606
                        }
607
                        type.setFormat(m_Format);
608
                        type.setHost(host);
609
                        type.setProtocol("WMS");
610
                        DriverException exception = new DriverException("unknown_response_format", type);
611
                        throw exception;
612
613
                } catch (UnsupportedVersionException e) {
614
                        UnsuportedProtocolVersionExceptionType type =
615
                                new UnsuportedProtocolVersionExceptionType();
616
                        type.setLayerName(getName());
617
                        try {
618
                                type.setDriverName("WMS Driver");
619
                        } catch (Exception ex){
620
                        }
621
                        type.setUrl(host);
622
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e, type);
623
624
                } catch (IOException e) {
625
                        ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
626
                        type.setLayerName(getName());
627
                        try {
628
                                type.setDriverName("WMS Driver");
629
                        } catch (Exception e1) {
630
                        }
631
                        type.setHost(host);
632
                        throw new DriverException(PluginServices.
633
                                        getText(this, "connect_error"), e, type);
634
                }
635
                catch (NoninvertibleTransformException e) {
636 4222 jaume
                        NotificationManager.addError("NotinvertibleTransform", e);
637 3746 jaume
                }
638 4222 jaume
                return null;
639 3746 jaume
        }
640
641
        /**
642
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent()
643
         */
644
        public Rectangle2D getFullExtent() {
645
                return fullExtent;
646
        }
647
648
        /**
649 6050 jaume
         *
650 3746 jaume
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#draw(java.awt.image.BufferedImage,
651
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
652 5334 jaume
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
653 3746 jaume
         */
654 6805 jaume
        private int callCount; // mess code, represents the amount of times the methods drawFixedSize or drawTile where tried for an extent
655
        private static final int MAX_RETRY_TIMES = 5; // mess code, represents the max amount of retries allowed.
656 3746 jaume
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
657
                        Cancellable cancel,double scale) throws DriverException {
658 6805 jaume
                callCount = 0; // mess code
659 4222 jaume
                if (isWithinScale(scale)){
660
                        Point2D p = viewPort.getOffset();
661
                        // p will be (0, 0) when drawing a view or other when painting onto
662
                        // the Layout.
663
                        visualStatus.width =  viewPort.getImageWidth();
664
                        visualStatus.height =  viewPort.getImageHeight();
665
                        visualStatus.minX = viewPort.getAdjustedExtent().getMinX();
666
                        visualStatus.minY = viewPort.getAdjustedExtent().getMinY();
667
                        visualStatus.maxX = viewPort.getAdjustedExtent().getMaxX();
668
                        visualStatus.maxY = viewPort.getAdjustedExtent().getMaxY();
669 6805 jaume
670
671 4222 jaume
                        if (isSizeFixed()) {
672
                                // This condition handles those situations in which the server can
673
                                // only give static extent and resolution maps despite we need
674
                                // a specific BBOX and pixel WIDTH and HEIGHT
675
                                drawFixedSize(g, viewPort, cancel);
676
677
                        } else {
678 5534 nacho
                                if(mustTileDraw){
679
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), viewPort.getImageWidth(), viewPort.getImageHeight());
680
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
681
                                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
682
                                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
683
                                                // drawing part
684
                                                try {
685
                                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
686
                                                        drawTile(g, vp, cancel);
687
                                                } catch (NoninvertibleTransformException e) {
688
                                                        e.printStackTrace();
689
                                                }
690 4222 jaume
                                        }
691 5534 nacho
                                }else
692
                                        drawTile(g, viewPort, cancel);
693 4222 jaume
                        }
694 3841 nacho
                }
695 4730 jaume
//                Runtime r = Runtime.getRuntime();
696
//                long mem = r.totalMemory() - r.freeMemory();
697
//                System.err.println("Memoria total: " + (mem / 1024) +"KB");
698 3841 nacho
        }
699 6050 jaume
700 4222 jaume
        private void drawFixedSize(Graphics2D g, ViewPort vp, Cancellable cancel) throws DriverException {
701 6805 jaume
                callCount++; // mess code, it is not unusual a wms server to response an error which is completely
702
                                         // temporal and the response is available if we retry requesting.
703
                                         //
704
705
706 4222 jaume
                // This is the extent that will be requested
707
                Rectangle2D bBox = getFullExtent();
708 5409 jaume
                MyCancellable c = new MyCancellable(cancel);
709 6050 jaume
710
                try {
711 4222 jaume
                        wmsStatus.setExtent( bBox );
712
                        wmsStatus.setFormat( m_Format );
713
                        wmsStatus.setHeight( fixedSize.height );
714
                        wmsStatus.setWidth( fixedSize.width );
715
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
716
                        wmsStatus.setSrs(m_SRS);
717
                        wmsStatus.setStyles(styles);
718
                        wmsStatus.setDimensions(dimensions);
719
                        wmsStatus.setTransparency(wmsTransparency);
720
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
721 5409 jaume
                        File f = getDriver().getMap(wmsStatus, c);
722
                        if (f == null)
723
                                return;
724 4222 jaume
                        String nameWorldFile = f.getPath() + getExtensionWorldFile();
725
                        com.iver.andami.Utilities.createTemp(nameWorldFile, this.getDataWorldFile(bBox, fixedSize));
726 6050 jaume
727 4222 jaume
                        if(status!=null && firstLoad){
728
                                status.applyStatus(this);
729
                                firstLoad = false;
730
                        }
731 6050 jaume
732 4222 jaume
                        // And finally, obtain the extent intersecting the view and the BBox
733
                        // to draw to.
734
                        Rectangle2D extent = new Rectangle2D.Double();
735
                        Rectangle2D.intersect(vp.getAdjustedExtent(), bBox, extent);
736 6050 jaume
737 4222 jaume
                        ViewPortData vpData = new ViewPortData(
738
                                vp.getProjection(), new Extent(extent), fixedSize );
739
                        vpData.setMat(vp.getAffineTransform());
740
741
                        rasterProcess(g, vpData, f);
742 6050 jaume
743 4222 jaume
                } catch (ValidationException e) {
744 5409 jaume
                        if (!c.isCanceled())
745 8765 jjdelcerro
                        {
746
                                UnknownResponseFormatExceptionType type =
747
                                        new UnknownResponseFormatExceptionType();
748
                                type.setLayerName(getName());
749
                                try {
750
                                        type.setDriverName("WMS Driver");
751
                                } catch (Exception e1) {
752
                                        e1.printStackTrace();
753
                                }
754
                                type.setFormat(m_Format);
755
                                type.setHost(host);
756
                                type.setProtocol("WMS");
757
                                DriverException exception = new DriverException("unknown_response_format", type);
758
                                throw exception;
759
                        }
760
//        azabala                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
761 4222 jaume
                } catch (UnsupportedVersionException e) {
762 8765 jjdelcerro
                        if (!c.isCanceled()){
763
                                UnsuportedProtocolVersionExceptionType type =
764
                                        new UnsuportedProtocolVersionExceptionType();
765
                                type.setLayerName(getName());
766
                                try {
767
                                        type.setDriverName("WMS Driver");
768
                                } catch (Exception ex){
769
                                }
770
                                type.setUrl(host);
771
                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e, type);
772
                        }
773
//        azabala                throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
774 4222 jaume
                } catch (IOException e) {
775 5409 jaume
                        if (!c.isCanceled())
776 6818 jaume
                                if (callCount<MAX_RETRY_TIMES) { // mess code
777
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
778
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
779
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
780
                                        drawFixedSize(g, vp, cancel); // mess code
781
                                } // mess code
782 8765 jjdelcerro
783 6818 jaume
                                if (callCount == 1) { // mess code
784 8765 jjdelcerro
                                        ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
785
                                        type.setLayerName(getName());
786
                                        try {
787
                                                type.setDriverName("WMS Driver");
788
                                        } catch (Exception e1) {
789
                                        }
790
                                        type.setHost(host);
791
                                        throw new DriverException(PluginServices.
792
                                                        getText(this, "connect_error"), e, type);
793
//        azabala        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
794 6818 jaume
                                } // mess code
795 8765 jjdelcerro
796
797 4222 jaume
                } catch (WMSException e) {
798 5409 jaume
                        if (!c.isCanceled()) {
799 6818 jaume
                                if (callCount<MAX_RETRY_TIMES) { // mess code
800
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
801
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
802
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
803
                                        drawFixedSize(g, vp, cancel); // mess code
804
                                } // mess code
805
                                if (callCount == 1) { // mess code
806 8765 jjdelcerro
//                azabala                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
807
                                        WMSDriverExceptionType type = new WMSDriverExceptionType();
808
                                        type.setLayerName(getName());
809
                                        try {
810
                                                type.setDriverName("WMS Driver");
811
                                        } catch (Exception e1) {
812
                                        }
813
                                        type.setWcsStatus(this.wmsStatus);
814 6805 jaume
                                        if (!isPrinting)
815
                                                this.setVisible(false);
816 8765 jjdelcerro
                                        throw new DriverException("Error WMS", e,  type);
817 6805 jaume
818 8765 jjdelcerro
819 6818 jaume
                                } // mess code
820 5409 jaume
                        }
821 3841 nacho
                }
822 6818 jaume
                callCount--; // mess code
823 4222 jaume
        }
824 6050 jaume
825 3841 nacho
        /**
826 4222 jaume
         * This is the method used to draw a tile in a WMS mosaic layer.
827 3841 nacho
         */
828 4222 jaume
        private void drawTile(Graphics2D g, ViewPort vp, Cancellable cancel) throws DriverException {
829 6805 jaume
                callCount++;
830 6050 jaume
                // Compute the query geometry
831 4222 jaume
                // 1. Check if it is within borders
832
                Rectangle2D extent = getFullExtent();
833 6426 jaume
        if ((vp.getAdjustedExtent().getMinX() > extent.getMaxX()) ||
834
                (vp.getAdjustedExtent().getMinY() > extent.getMaxY()) ||
835
                (vp.getAdjustedExtent().getMaxX() < extent.getMinX()) ||
836
                (vp.getAdjustedExtent().getMaxY() < extent.getMinY())) {
837 4222 jaume
            return;
838
        }
839 6050 jaume
840 4222 jaume
        // 2. Compute extent to be requested.
841
        Rectangle2D bBox = new Rectangle2D.Double();
842 8907 jaume
        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
843 6050 jaume
844 4222 jaume
        // 3. Compute size in pixels
845 6050 jaume
        double scalex = vp.getAffineTransform().getScaleX();
846
        double scaley = vp.getAffineTransform().getScaleY();
847 4222 jaume
        int wImg = (int) Math.ceil(Math.abs(bBox.getWidth() * scalex) + 1);
848
        int hImg = (int) Math.ceil(Math.abs(bBox.getHeight() * scaley) + 1);
849 6050 jaume
850 4222 jaume
        Dimension sz = new Dimension(wImg, hImg);
851
852
        if ((wImg <= 0) || (hImg <= 0)) {
853
            return;
854
        }
855 5409 jaume
        MyCancellable c = new MyCancellable(cancel);
856 6050 jaume
857 5534 nacho
                try {
858 7642 jaume
//                        wImg = vp.getImageWidth();
859
//                        hImg = vp.getImageHeight();
860
                        sz = new Dimension(wImg, hImg);
861 6086 jaume
                        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
862 6050 jaume
863 6822 jaume
864 4222 jaume
                        wmsStatus.setExtent( bBox );
865
                        wmsStatus.setFormat(m_Format);
866
                        wmsStatus.setHeight( hImg );
867
                        wmsStatus.setWidth( wImg );
868
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
869
                        wmsStatus.setSrs(m_SRS);
870
                        wmsStatus.setStyles(styles);
871
                        wmsStatus.setDimensions(dimensions);
872
                        wmsStatus.setTransparency(wmsTransparency);
873
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
874 6050 jaume
875 8765 jjdelcerro
                        // begin patch; Avoid to request too small tiles.
876
                        // This generally occurs when printing
877 6822 jaume
878
                        if (wImg < minTilePrintWidth) {
879
                                double wScale = (double) minTilePrintWidth / wImg;
880
                                wmsStatus.setWidth(minTilePrintWidth);
881
                                Rectangle2D sExtent = wmsStatus.getExtent();
882
                                Point2D initialPoint = new Point2D.Double(sExtent.getX(), sExtent.getY());
883
                                sExtent.setRect(sExtent.getX()*wScale, sExtent.getY(), sExtent.getWidth()*wScale, sExtent.getHeight());
884
                                if (!bBox.contains(initialPoint)) {
885
                                        sExtent.setRect(sExtent.getX() - initialPoint.getX(), sExtent.getY(), sExtent.getWidth(), sExtent.getHeight());
886
                                }
887
                        }
888
889
                        if (hImg < minTilePrintHeight) {
890
                                double hScale = (double) minTilePrintHeight / hImg;
891
                                wmsStatus.setHeight(minTilePrintHeight);
892
                                Rectangle2D sExtent = wmsStatus.getExtent();
893
                                Point2D initialPoint = new Point2D.Double(sExtent.getX(), sExtent.getY());
894
                                sExtent.setRect(sExtent.getX(), sExtent.getY()*hScale, sExtent.getWidth(), sExtent.getHeight()*hScale);
895
                                if (!bBox.contains(initialPoint)) {
896
                                        sExtent.setRect(sExtent.getX(), sExtent.getY() - initialPoint.getY(), sExtent.getWidth(), sExtent.getHeight());
897
                                }
898
                        }
899
900
                        // end patch
901 5409 jaume
                        File f = getDriver().getMap(wmsStatus, c);
902
                        if (f == null)
903
                                return;
904 4222 jaume
                        String nameWordFile = f.getPath() + getExtensionWorldFile();
905
                        com.iver.andami.Utilities.createTemp(nameWordFile, this.getDataWorldFile(bBox, sz));
906 7642 jaume
907 4222 jaume
                        ViewPortData vpData = new ViewPortData(
908
                                vp.getProjection(), new Extent(bBox), sz );
909
                        vpData.setMat(vp.getAffineTransform());
910
911
                        rasterProcess(g, vpData, f);
912 7642 jaume
913 3840 nacho
                } catch (ValidationException e) {
914 8765 jjdelcerro
                //azabala
915
//                        if (!c.isCanceled())
916
//                                throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
917
918 5409 jaume
                        if (!c.isCanceled())
919 8765 jjdelcerro
                        {
920
                                UnknownResponseFormatExceptionType type =
921
                                        new UnknownResponseFormatExceptionType();
922
                                type.setLayerName(getName());
923
                                try {
924
                                        type.setDriverName("WMS Driver");
925
                                } catch (Exception e1) {
926
                                        e1.printStackTrace();
927
                                }
928
                                type.setFormat(m_Format);
929
                                type.setHost(host);
930
                                type.setProtocol("WMS");
931
                                DriverException exception = new DriverException("unknown_response_format", type);
932
                                throw exception;
933
                        }
934 3840 nacho
                } catch (UnsupportedVersionException e) {
935 8765 jjdelcerro
936
//                        if (!c.isCanceled())
937
//                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
938
939
                        if (!c.isCanceled()){
940
                                UnsuportedProtocolVersionExceptionType type =
941
                                        new UnsuportedProtocolVersionExceptionType();
942
                                type.setLayerName(getName());
943
                                try {
944
                                        type.setDriverName("WMS Driver");
945
                                } catch (Exception ex){
946
                                }
947
                                type.setUrl(host);
948
                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e, type);
949
                        }
950
951 3840 nacho
                } catch (IOException e) {
952 8765 jjdelcerro
                        /*azabala
953 5409 jaume
                        if (!c.isCanceled())
954 6805 jaume
                                if (callCount<MAX_RETRY_TIMES) {
955
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null);
956
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error
957
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0)
958 7075 jaume
                                        drawTile(g, vp, cancel);
959 6805 jaume
                                }
960
                                if (callCount == 1) {
961
                                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
962
                                }
963 8765 jjdelcerro
                        */
964
                        if (!c.isCanceled()){
965
                                if (callCount<MAX_RETRY_TIMES) { // mess code
966
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
967
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
968
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
969
970
                                        //FIXME Aqu? deberiamos llamar a drawTile o a drawFixedSize????
971
                                        drawFixedSize(g, vp, cancel); // mess code
972
                                } // mess code
973
                        }
974
                        if (callCount == 1) { // mess code
975
                                ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
976
                                type.setLayerName(getName());
977
                                try {
978
                                        type.setDriverName("WMS Driver");
979
                                } catch (Exception e1) {}
980
                                type.setHost(host);
981
                                throw new DriverException(PluginServices.
982
                                                        getText(this, "connect_error"), e, type);
983
                        }//if
984 3840 nacho
                } catch (WMSException e) {
985 8765 jjdelcerro
                        /*azabala
986 5409 jaume
                        if (!c.isCanceled()) {
987 6805 jaume
                                if (callCount<MAX_RETRY_TIMES) {
988
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawTile() ] Failed in trying " + callCount + "/" + MAX_RETRY_TIMES +" \n", null);
989
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error
990
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0)
991
                                        drawTile(g, vp, cancel);
992
                                }
993
                                if (callCount == 1) {
994 6939 jaume
                                        if (!isPrinting) {
995
                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
996 6805 jaume
                                                this.setVisible(false);
997 6939 jaume
                                        }
998 6805 jaume
                                }
999 5409 jaume
                        }
1000 8765 jjdelcerro
                        */
1001
                        if (!c.isCanceled()) {
1002
                                if (callCount<MAX_RETRY_TIMES) { // mess code
1003
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
1004
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
1005
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
1006
                                        drawTile(g, vp, cancel);
1007
                                } // mess code
1008
                                if (callCount == 1) { // mess code
1009
//                azabala                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
1010
                                        WMSDriverExceptionType type = new WMSDriverExceptionType();
1011
                                        type.setLayerName(getName());
1012
                                        try {
1013
                                                type.setDriverName("WMS Driver");
1014
                                        } catch (Exception e1) {
1015
                                        }
1016
                                        type.setWcsStatus(this.wmsStatus);
1017
                                        if (!isPrinting)
1018
                                                this.setVisible(false);
1019
                                        throw new DriverException("Error WMS", e,  type);
1020
1021
1022
                                } //if
1023
                        }//if
1024
                }//catch
1025 6805 jaume
                callCount--;
1026 3746 jaume
        }
1027 4222 jaume
1028
        /**
1029
         * Obtiene la extensi?n del fichero de georreferenciaci?n
1030 6986 cesar
         * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
1031 6050 jaume
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
1032 4222 jaume
         */
1033
        private String getExtensionWorldFile(){
1034
                String extWorldFile = ".wld";
1035
            if(m_Format.equals("image/tif") || m_Format.equals("image/tiff"))
1036
                    extWorldFile = ".tfw";
1037
            if(m_Format.equals("image/jpeg"))
1038
                    extWorldFile = ".jpgw";
1039
            return extWorldFile;
1040
        }
1041 6050 jaume
1042 3746 jaume
        /**
1043 4222 jaume
         * Calcula el contenido del fichero de georreferenciaci?n de una imagen.
1044
         * @param bBox Tama?o y posici?n de la imagen (en coordenadas de usuario)
1045
         * @param sz Tama?o de la imagen en pixeles.
1046
         * @return el 'WorldFile', como String.
1047 3746 jaume
         * @throws IOException
1048
         */
1049 4222 jaume
        public String getDataWorldFile(Rectangle2D bBox, Dimension sz) throws IOException {
1050
                StringBuffer data = new StringBuffer();
1051
            data.append((bBox.getMaxX() - bBox.getMinX())/(sz.getWidth() - 1)+"\n");
1052
            data.append("0.0\n");
1053
            data.append("0.0\n");
1054 8765 jjdelcerro
            data.append("-"+(bBox.getMaxY() - bBox.getMinY())/(sz.getHeight() - 1)+"\n");
1055 4222 jaume
            data.append(""+bBox.getMinX()+"\n");
1056 8765 jjdelcerro
            data.append(""+bBox.getMaxY()+"\n");
1057 4222 jaume
            return data.toString();
1058 3746 jaume
        }
1059 6050 jaume
1060 3746 jaume
        /**
1061 4222 jaume
         * Dibuja una imagen usando PxRaster
1062
         * @param g        Graphics2D en el que hay que dibujar.
1063
         * @param vpData Par?metros de visualizaci?n
1064
         * @param file La imagen en cuesti?n.
1065
         */
1066 9056 nacho
        private void rasterProcess(Graphics2D g, ViewPortData vpData, File file) throws DriverException {
1067 6050 jaume
1068
                //Creamos el PxRaster
1069 9056 nacho
                try {
1070
                        rasterFile = new GdalFile(vpData.getProjection(), file.getAbsolutePath());
1071
                } catch (NotSupportedExtensionException e) {
1072
                        throw new DriverException("Open File Error");
1073
                }
1074 3746 jaume
                raster = new PxRaster(rasterFile, null, rasterFile.getExtent());
1075 9056 nacho
                grid = new Grid(rasterFile);
1076
                grid.addRenderizer(raster);
1077
1078
                if(status != null && firstLoad){
1079 7106 nacho
                        status.applyStatus(this);
1080
                        firstLoad = false;
1081
                }
1082 7642 jaume
1083 3746 jaume
                //Recuperamos la pila de filtros si ya hubiese sido cargado antes
1084
                if(this.filterStack!=null)
1085
                        raster.filterStack = this.filterStack;
1086 6050 jaume
1087 3746 jaume
                raster.setTransparency(false);
1088 6050 jaume
1089 3746 jaume
                //Asignamos transparencia y orden de bandas
1090 9056 nacho
                if(this.transparency == -1 && !firstLoad);
1091 3746 jaume
                else
1092
                        raster.setTransparency(this.transparency);
1093 6050 jaume
1094 3746 jaume
                raster.setBand(GeoRasterFile.RED_BAND,rband);
1095
                raster.setBand(GeoRasterFile.GREEN_BAND, gband);
1096
                raster.setBand(GeoRasterFile.BLUE_BAND, bband);
1097 6050 jaume
1098 3746 jaume
                //Despues del primer pxRaster asignamos el stackManager guardado para los siguientes.
1099 6050 jaume
                //Con esto conseguimos asignar los cambios que se hayan producido desde el cuadro de
1100 3746 jaume
                //propiedades cuando creamos un nuevo pxRaster
1101
                if(this.stackManager != null)
1102 6050 jaume
                        raster.setStackManager(this.stackManager);
1103
1104 4378 nacho
                if(visualStatus != null){
1105
                        visualStatus.bandCount = raster.getBandCount();
1106
                        visualStatus.dataType = raster.getDataType();
1107
                }
1108 3841 nacho
1109 3746 jaume
                raster.draw(g, vpData);
1110 6050 jaume
1111 3746 jaume
                //En el primer pxRaster de una imagen obtenemos el Stack Manager para poder modificarlo
1112
                //si queremos desde las propiedades
1113 6050 jaume
1114 3746 jaume
                if(this.stackManager == null)
1115 6050 jaume
                        this.stackManager = raster.getStackManager();
1116
1117 3746 jaume
                if(this.filterStack == null)
1118
                        this.filterStack = raster.filterStack;
1119 6050 jaume
1120 4329 ldiaz
                //rasterFile.close();
1121 3746 jaume
        }
1122 6050 jaume
1123 3746 jaume
        /**
1124
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D,
1125
         *                 com.iver.cit.gvsig.fmap.ViewPort,
1126 5334 jaume
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
1127 3746 jaume
         */
1128 9013 caballero
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet properties)
1129 3746 jaume
                throws DriverException {
1130 6050 jaume
                if (isVisible() && isWithinScale(scale)){
1131 3746 jaume
                isPrinting = true;
1132
                if (!mustTilePrint) {
1133
                        draw(null, g, viewPort, cancel,scale);
1134
                } else {
1135
                // Para no pedir imagenes demasiado grandes, vamos
1136
                // a hacer lo mismo que hace EcwFile: chunkear.
1137 4222 jaume
                // Llamamos a drawView con cuadraditos m?s peque?os
1138 3746 jaume
                // del BufferedImage ni caso, cuando se imprime viene con null
1139 6050 jaume
1140 6986 cesar
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
1141 3746 jaume
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
1142
                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
1143
                            // Parte que dibuja
1144
                            try {
1145
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
1146 4222 jaume
                                drawTile(g, vp, cancel);
1147 3746 jaume
                                } catch (NoninvertibleTransformException e) {
1148
                                        e.printStackTrace();
1149
                                }
1150
                }
1151
                }
1152
            isPrinting = false;
1153
                }
1154
        }
1155 6050 jaume
1156 3746 jaume
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale)
1157
                throws DriverException {
1158
                draw(null, g, viewPort, cancel,scale);
1159
        }
1160
1161
        /**
1162
         * Devuelve el FMapWMSDriver.
1163
         *
1164
         * @return FMapWMSDriver
1165
         *
1166
         * @throws IllegalStateException
1167
         * @throws ValidationException
1168
         * @throws UnsupportedVersionException
1169
         * @throws IOException
1170
         */
1171
        private FMapWMSDriver getDriver()
1172 6050 jaume
                throws IllegalStateException, ValidationException,
1173 3746 jaume
                        UnsupportedVersionException, IOException {
1174 5334 jaume
                return FMapWMSDriverFactory.getFMapDriverForURL(host);
1175 3746 jaume
        }
1176 6050 jaume
1177 3746 jaume
        /**
1178
         * Devuelve el FMapWMSDriver.
1179
         *
1180
         * @return FMapWMSDriver
1181
         *
1182
         * @throws IllegalStateException
1183
         * @throws ValidationException
1184
         * @throws UnsupportedVersionException
1185
         * @throws IOException
1186
         */
1187
        public void setDriver(FMapWMSDriver drv) {
1188
                wms = drv;
1189
        }
1190
1191
        /**
1192
         * Devuelve el URL.
1193
         *
1194
         * @return URL.
1195
         */
1196
        public URL getHost() {
1197
                return host;
1198
        }
1199
1200
        /**
1201
         * Inserta el URL.
1202
         *
1203
         * @param host URL.
1204
         */
1205
        public void setHost(URL host) {
1206
                this.host = host;
1207
        }
1208
1209
        /**
1210
         * Devuelve la informaci?n de la consulta.
1211
         *
1212
         * @return String.
1213
         */
1214
        public String getInfoLayerQuery() {
1215
                return infoLayerQuery;
1216
        }
1217
1218
        /**
1219 4222 jaume
         * Inserta la informaci?n de la consulta.
1220 3746 jaume
         *
1221
         * @param infoLayerQuery String.
1222
         */
1223
        public void setInfoLayerQuery(String infoLayerQuery) {
1224
                this.infoLayerQuery = infoLayerQuery;
1225
        }
1226
1227
        /**
1228
         * Devuelve la consulta.
1229
         *
1230
         * @return String.
1231
         */
1232
        public String getLayerQuery() {
1233
                return layerQuery;
1234
        }
1235
1236
        /**
1237
         * Inserta la consulta.
1238
         *
1239
         * @param layerQuery consulta.
1240
         */
1241
        public void setLayerQuery(String layerQuery) {
1242
                this.layerQuery = layerQuery;
1243
        }
1244
1245
        /**
1246
         * Devuelve el formato.
1247
         *
1248
         * @return Formato.
1249
         */
1250
        public String getFormat() {
1251
                return m_Format;
1252
        }
1253
1254
        /**
1255
         * Inserta el formato.
1256
         *
1257
         * @param format Formato.
1258
         */
1259
        public void setFormat(String format) {
1260
                m_Format = format;
1261
        }
1262
1263
        /**
1264
         * Devuelve el SRS.
1265
         *
1266
         * @return SRS.
1267
         */
1268
        public String getSRS() {
1269
                return m_SRS;
1270
        }
1271
1272
        /**
1273
         * Inserta el SRS.
1274
         *
1275
         * @param m_srs SRS.
1276
         */
1277
        public void setSRS(String m_srs) {
1278
                m_SRS = m_srs;
1279
        }
1280
1281
        /**
1282 4222 jaume
         * Inserta la extensi?n total de la capa.
1283 3746 jaume
         *
1284 4222 jaume
         * @param fullExtent Rect?ngulo.
1285 3746 jaume
         */
1286
        public void setFullExtent(Rectangle2D fullExtent) {
1287
                this.fullExtent = fullExtent;
1288
        }
1289 6050 jaume
1290 3746 jaume
        public HashMap getProperties() {
1291
                HashMap info = new HashMap();
1292
        String[] layerNames = getLayerQuery().split(",");
1293
        Vector layers = new Vector(layerNames.length);
1294
        try {
1295 5409 jaume
            if(getDriver().connect(null)){
1296 3746 jaume
                for (int i = 0; i < layerNames.length; i++) {
1297 5410 jaume
                    layers.add(i, getDriver().getLayer(layerNames[i]));
1298 3746 jaume
                }
1299 4222 jaume
                info.put("name", getName());
1300 3746 jaume
                info.put("selectedLayers", layers);
1301
                info.put("host", getHost());
1302
                info.put("srs", getSRS());
1303
                info.put("format", getFormat());
1304
                info.put("wmsTransparency", new Boolean(wmsTransparency));
1305
                info.put("styles", styles);
1306
                info.put("dimensions", dimensions);
1307 4222 jaume
                info.put("fixedSize", fixedSize);
1308 3746 jaume
                return info;
1309
            }
1310
        } catch (Exception e) {
1311
            e.printStackTrace();
1312
        }
1313
        return null;
1314
        }
1315 6050 jaume
1316 3746 jaume
        /**
1317
         * Asignar el estado del raster
1318
         * @param status
1319
         */
1320
        public void setStatus(StatusRasterInterface status){
1321
                this.status = status;
1322
        }
1323 6050 jaume
1324 3746 jaume
        /**
1325
         * Obtiene el estado del raster
1326
         * @return
1327
         */
1328
        public StatusRasterInterface getStatus(){
1329
                return this.status;
1330
        }
1331 6050 jaume
1332 3746 jaume
        /* (non-Javadoc)
1333
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getAttributes()
1334
         */
1335
        public ArrayList getAttributes() {
1336
                if(rasterFile != null){
1337
                        ArrayList attr = new ArrayList();
1338 4378 nacho
                        String dataType = "Byte";
1339 3746 jaume
                        if (rasterFile.getDataType() == DataBuffer.TYPE_BYTE) dataType = "Byte";
1340 4378 nacho
                        else if (visualStatus.dataType == DataBuffer.TYPE_SHORT)
1341 3746 jaume
                                dataType = "Short";
1342 4378 nacho
                        else if (visualStatus.dataType == DataBuffer.TYPE_USHORT)
1343 3746 jaume
                                dataType = "Unsigned Short";
1344 4378 nacho
                        else if (visualStatus.dataType == DataBuffer.TYPE_INT)
1345 3746 jaume
                                dataType = "Integer";
1346 4378 nacho
                        else if (visualStatus.dataType == DataBuffer.TYPE_FLOAT)
1347 3746 jaume
                                dataType = "Float";
1348 4378 nacho
                        else if (visualStatus.dataType == DataBuffer.TYPE_DOUBLE)
1349 3746 jaume
                                dataType = "Double";
1350
                        else
1351
                                dataType = "Unknown";
1352 4378 nacho
1353 3746 jaume
                        Object [][] a = {
1354
                                {"Filename",rasterFile.getName().substring(rasterFile.getName().lastIndexOf("/")+1, rasterFile.getName().length())},
1355 4378 nacho
                                {"Filesize",new Long(0)},
1356
                                {"Width",new Integer((int)this.getWidth())},
1357
                                {"Height", new Integer((int)this.getHeight())},
1358
                                {"Bands", new Integer(visualStatus.bandCount)},
1359
                                {"BandDataType", dataType}
1360 3746 jaume
                        };
1361 4378 nacho
                        for (int i=0; i<a.length; i++)
1362 3746 jaume
                                attr.add(a[i]);
1363 4378 nacho
1364 3746 jaume
                        return attr;
1365
                }
1366
                return  null;
1367
        }
1368 6050 jaume
1369 3746 jaume
        /* (non-Javadoc)
1370
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getFilterStack()
1371
         */
1372
        public RasterFilterStack getFilterStack() {
1373
                if(raster!=null)
1374
                        return raster.filterStack;
1375
                return null;
1376
        }
1377
        /* (non-Javadoc)
1378
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getHeight()
1379
         */
1380
        public double getHeight() {
1381 4222 jaume
                return visualStatus.height;
1382 3746 jaume
        }
1383 6050 jaume
1384 3746 jaume
        /* (non-Javadoc)
1385
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxX()
1386
         */
1387
        public double getMaxX() {
1388 4222 jaume
                return visualStatus.maxX;
1389 3746 jaume
        }
1390 6050 jaume
1391 3746 jaume
        /* (non-Javadoc)
1392
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxY()
1393
         */
1394
        public double getMaxY() {
1395 4222 jaume
                return visualStatus.maxY;
1396 3746 jaume
        }
1397 6050 jaume
1398 3746 jaume
        /* (non-Javadoc)
1399
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinX()
1400
         */
1401
        public double getMinX() {
1402 4222 jaume
                return visualStatus.minX;
1403 3746 jaume
        }
1404 6050 jaume
1405 3746 jaume
        /* (non-Javadoc)
1406
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinY()
1407
         */
1408
        public double getMinY() {
1409 4222 jaume
                return visualStatus.minY;
1410 3746 jaume
        }
1411
        /* (non-Javadoc)
1412
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getPixel(double, double)
1413
         */
1414
        public int[] getPixel(double wcx, double wcy) {
1415
                if(getPxRaster() != null)
1416
                        return getPxRaster().getPixel(wcx, wcy);
1417
        return null;
1418
        }
1419
        /* (non-Javadoc)
1420
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getSource()
1421
         */
1422
        public RasterAdapter getSource() {
1423
                return null;
1424
        }
1425
        /* (non-Javadoc)
1426
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getWidth()
1427
         */
1428
        public double getWidth() {
1429 4222 jaume
                return visualStatus.width;
1430 3746 jaume
        }
1431
        /* (non-Javadoc)
1432
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setBand(int, int)
1433
         */
1434
        public void setBand(int flag, int nBand) {
1435
                switch(flag){
1436
                case GeoRasterFile.RED_BAND:setBandR(nBand);break;
1437
                case GeoRasterFile.GREEN_BAND:setBandG(nBand);break;
1438
                case GeoRasterFile.BLUE_BAND:setBandB(nBand);break;
1439
                }
1440
        }
1441
        /* (non-Javadoc)
1442
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setFilterStack(org.cresques.io.raster.RasterFilterStack)
1443
         */
1444
        public void setFilterStack(RasterFilterStack stack) {
1445
                this.filterStack = stack;
1446
        }
1447
        /* (non-Javadoc)
1448
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPos(int, int)
1449
         */
1450
        public void setPos(int x, int y) {
1451
                this.posX = x;
1452
                this.posY = y;
1453
        }
1454 6050 jaume
1455 3746 jaume
        /* (non-Javadoc)
1456
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPosWC(double, double)
1457
         */
1458
        public void setPosWC(double x, double y) {
1459
                this.posXWC = x;
1460
                this.posYWC = y;
1461
        }
1462 6050 jaume
1463 3746 jaume
        /* (non-Javadoc)
1464
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setRGB(int, int, int)
1465
         */
1466
        public void setRGB(int r, int g, int b) {
1467
                this.r = r;
1468
                this.g = g;
1469
                this.b = b;
1470
        }
1471
        /* (non-Javadoc)
1472
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setSource(com.iver.cit.gvsig.fmap.layers.RasterAdapter)
1473
         */
1474
        public void setSource(RasterAdapter ra) {
1475
        }
1476
        /**
1477
         * @return Returns the raster.
1478
         */
1479
        public PxRaster getPxRaster() {
1480
                return raster;
1481
        }
1482
        /**
1483
         * @return Returns the rasterFile.
1484
         */
1485
        public GeoRasterFile getGeoRasterFile() {
1486
                return rasterFile;
1487
        }
1488 6050 jaume
1489 3746 jaume
        public void setTransparency(int trans) {
1490
                this.transparency = trans;
1491
        }
1492 6050 jaume
1493 3746 jaume
        /**
1494
         * Sets the R-band.
1495 6050 jaume
         *
1496 3746 jaume
         * Asigna la banda R.
1497
         * @param r
1498
         */
1499
        public void setBandR(int r){
1500
                this.rband = r;
1501
        }
1502 6050 jaume
1503 3746 jaume
        /**
1504
         * Sets the G-band.
1505 6050 jaume
         *
1506 3746 jaume
         * Asigna la banda G
1507
         * @param g
1508
         */
1509
        public void setBandG(int g){
1510
                this.gband = g;
1511
        }
1512 6050 jaume
1513 3746 jaume
        /**
1514
         * Sets the B-band.
1515 6050 jaume
         *
1516 3746 jaume
         * Asigna la banda B
1517
         * @param b
1518
         */
1519
        public void setBandB(int b){
1520
                this.bband = b;
1521
        }
1522
1523
    /**
1524
     * @return Returns the wmsTransparency.
1525
     */
1526 4222 jaume
    public boolean isWmsTransparent() {
1527 3746 jaume
        return wmsTransparency;
1528
    }
1529
1530
    /**
1531
     * @param wmsTransparency The wmsTransparency to set.
1532
     */
1533
    public void setWmsTransparency(boolean wmsTransparency) {
1534
        this.wmsTransparency = wmsTransparency;
1535
    }
1536
1537 3842 nacho
     /**
1538 3746 jaume
     * @param styles
1539
     */
1540
    public void setStyles(Vector styles) {
1541 3842 nacho
            //laura:
1542
            //layer query is built with the layer in reverse order
1543
            // so here we build the styles upside-down.
1544
            if (styles != null)
1545
            {
1546
                    this.styles = new Vector();
1547
                    for(int i = styles.size()-1; i>=0; i--)
1548
                    {
1549
                            this.styles.add(styles.elementAt(i));
1550
                    }
1551
            }
1552 3746 jaume
    }
1553 6050 jaume
1554 3746 jaume
    /**
1555 4222 jaume
     * Sets the dimension vector that is a list of key-value pairs containing
1556
     * the name of the dimension and the value for it
1557 3746 jaume
     * @param dimensions
1558
     */
1559
    public void setDimensions(Vector dimensions) {
1560
        this.dimensions = dimensions;
1561
    }
1562 4222 jaume
1563
    /**
1564
     * Sets the set of URLs that should be accessed for each operation performed
1565
     * to the server.
1566 6050 jaume
     *
1567 4222 jaume
     * @param onlineResources
1568
     */
1569
        public void setOnlineResources(Hashtable onlineResources) {
1570
                this.onlineResources = onlineResources;
1571
        }
1572 6050 jaume
1573 8765 jjdelcerro
    /**
1574
     * Gets the URL that should be accessed for an operation performed
1575
     * to the server.
1576
     *
1577
     * @param onlineResources
1578
     */
1579
        public String getOnlineResource(String operation) {
1580
                return ((String) onlineResources.get(operation));
1581
        }
1582
1583 4222 jaume
        /**
1584
         * When a server is not fully featured and it only can serve constant map
1585
         * sizes this value must be set. It expresses the size in pixels (width, height)
1586
         * that the map will be requested.
1587
         * @param Dimension sz
1588
         */
1589
        public void setFixedSize(Dimension sz) {
1590
                fixedSize = sz;
1591
        }
1592 6050 jaume
1593 4222 jaume
        /**
1594
         * Tells whether if this layer must deal with the server with the constant-size
1595
         * limitations or not.
1596
         * @return boolean.
1597
         */
1598
        private boolean isSizeFixed() {
1599
                return fixedSize != null && fixedSize.getWidth() > 0 && fixedSize.getHeight() > 0;
1600
        }
1601
1602
        /**
1603
         * If it is true, this layer accepts GetFeatureInfo operations. This WMS operations
1604
         * maps to FMap's infoByPoint(p) operation.
1605
         * @param b
1606
         */
1607
        public void setQueryable(boolean b) {
1608
                queryable = b;
1609
        }
1610 4730 jaume
1611
        /**
1612
         * Creates the part of a OGC's MapContext document that would describe this
1613
         * layer(s).
1614
         * @param version, The desired version of the resulting document. (1.1.0)
1615
         * @return String containing the xml.
1616 6050 jaume
         * @throws UnsupportedVersionException
1617 4730 jaume
         */
1618 4917 jaume
        public String toMapContext(String mapContextVersion) {
1619 4730 jaume
                XmlBuilder xml = new XmlBuilder();
1620
                FMapWMSDriver drv;
1621
                try {
1622
                        drv = getDriver();
1623
                } catch (Exception e) {
1624
                        return xml.toString();
1625 6050 jaume
                }
1626 4730 jaume
                String[] layerNames = getLayerQuery().split(",");
1627 6050 jaume
                String[] styleNames = (String[]) styles.toArray(new String[0]);
1628 4730 jaume
                for (int i = 0; i < layerNames.length; i++) {
1629
                        WMSLayerNode layer = drv.getLayer(layerNames[i]);
1630 4917 jaume
                        HashMap xmlAttrs = new HashMap();
1631 6050 jaume
1632 4833 jaume
                        // <Layer>
1633 4917 jaume
                        xmlAttrs.put(WebMapContextTags.HIDDEN, !isVisible()+"");
1634
                        xmlAttrs.put(WebMapContextTags.QUERYABLE, queryable+"");
1635 5409 jaume
                        xml.openTag(WebMapContextTags.LAYER, xmlAttrs);
1636
                        xmlAttrs.clear();
1637 4917 jaume
                        if (mapContextVersion.equals("1.1.0") || mapContextVersion.equals("1.0.0")) {
1638 4730 jaume
                                // <Server>
1639 4876 jaume
                                xmlAttrs.put(WebMapContextTags.SERVICE, WebMapContextTags.WMS);
1640
                                xmlAttrs.put(WebMapContextTags.VERSION, drv.getVersion());
1641
                                xmlAttrs.put(WebMapContextTags.SERVER_TITLE, drv.getServiceTitle());
1642
                                xml.openTag(WebMapContextTags.SERVER, xmlAttrs);
1643 4730 jaume
                                xmlAttrs.clear();
1644 6050 jaume
1645 4730 jaume
                                        // <OnlineResource>
1646 4876 jaume
                                        xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1647
                                        xmlAttrs.put(WebMapContextTags.XLINK_HREF, getHost().toString());
1648
                                        xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1649 4730 jaume
                                        xmlAttrs.clear();
1650
                                        // </OnlineResource>
1651 6050 jaume
1652 4730 jaume
                                xml.closeTag();
1653
                                // </Server>
1654 6050 jaume
1655 4730 jaume
                                // <Name>
1656 4915 jaume
                                xml.writeTag(WebMapContextTags.NAME, layer.getName().trim());
1657 4730 jaume
                                // </Name>
1658 6050 jaume
1659 4730 jaume
                                // <Title>
1660 8765 jjdelcerro
                                xml.writeTag(WebMapContextTags.TITLE, layer.getTitle().trim());
1661
                                //?xml.writeTag(WebMapContextTags.TITLE, getName().trim());
1662 4730 jaume
                                // </Title>
1663 6050 jaume
1664 4730 jaume
                                // <Abstract>
1665 4915 jaume
                                if (layer.getAbstract() != null)
1666
                                        xml.writeTag(WebMapContextTags.ABSTRACT, layer.getAbstract());
1667 4730 jaume
                                // </Abstract>
1668 6050 jaume
1669 4730 jaume
                                // <SRS> (a list of available SRS for the enclosing layer)
1670
                                String[] strings = (String[]) layer.getAllSrs().toArray(new String[0]);
1671
                                String mySRS = strings[0];
1672
                                for (int j = 1; j < strings.length; j++) {
1673
                                        mySRS += ","+strings[j];
1674
                                }
1675 4915 jaume
                                xml.writeTag(WebMapContextTags.SRS, mySRS);
1676 4730 jaume
                                // </SRS>
1677 6050 jaume
1678 4730 jaume
                                // <FormatList>
1679 4876 jaume
                                xml.openTag(WebMapContextTags.FORMAT_LIST);
1680 4730 jaume
                                        strings = (String[]) drv.getFormats().toArray(new String[0]);
1681
                                        for (int j = 0; j < strings.length; j++) {
1682
                    // <Format>
1683 4915 jaume
                                                String str = strings[j].trim();
1684
                                                if (str.equals(getFormat()))
1685
                                                        xml.writeTag(WebMapContextTags.FORMAT, str, WebMapContextTags.CURRENT, "1");
1686
                                                else
1687
                                                        xml.writeTag(WebMapContextTags.FORMAT, str);
1688 6050 jaume
                    // </Format>
1689 4730 jaume
                                        }
1690
                                xml.closeTag();
1691
                                // </FormatList>
1692 6050 jaume
1693 4730 jaume
                                // <StyleList>
1694 5409 jaume
                                xml.openTag(WebMapContextTags.STYLE_LIST);
1695 6050 jaume
1696 5409 jaume
                                        if (layer.getStyles().size()>0) {
1697
                                                for (int j = 0; j < layer.getStyles().size(); j++) {
1698
                                                        // <Style>
1699
                                                        FMapWMSStyle st = (FMapWMSStyle) layer.getStyles().get(j);
1700 5410 jaume
                                                        if (st.name.equals(styleNames[i]))
1701 5409 jaume
                                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1702
                                                        xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1703
                                                        xmlAttrs.clear();
1704 6050 jaume
1705 5409 jaume
                                                                // <Name>
1706
                                                                xml.writeTag(WebMapContextTags.NAME, st.name);
1707
                                                                // </Name>
1708 6050 jaume
1709 5409 jaume
                                                                // <Title>
1710
                                                                xml.writeTag(WebMapContextTags.TITLE, st.title);
1711
                                                                // </Title>
1712 6050 jaume
1713 5409 jaume
                                                                // <LegendURL width="180" format="image/gif" height="50">
1714
                                                                        // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1715
                                                                        // </OnlineResource>
1716
                                                                // </LegendURL>
1717
                                                        xml.closeTag();
1718
                                                        // </Style>
1719 6050 jaume
1720 5409 jaume
                                                }
1721 6050 jaume
1722 5409 jaume
                                        } else {
1723
                                                // Create fake style (for compatibility issues)
1724
                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1725 4730 jaume
                                                // <Style>
1726 4876 jaume
                                                xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1727 5409 jaume
                                                        xmlAttrs.clear();
1728 4730 jaume
                                                        // <Name>
1729 5409 jaume
                                                        xml.writeTag(WebMapContextTags.NAME, "default");
1730 4730 jaume
                                                        // </Name>
1731 6050 jaume
1732 4730 jaume
                                                        // <Title>
1733 5409 jaume
                                                        xml.writeTag(WebMapContextTags.TITLE, "default");
1734 4730 jaume
                                                        // </Title>
1735 6050 jaume
1736 5411 jaume
//                                                        // <LegendURL width="180" format="image/gif" height="50">
1737
//                                                        xmlAttrs.put(WebMapContextTags.WIDTH, "0");
1738
//                                                        xmlAttrs.put(WebMapContextTags.HEIGHT, "0");
1739
//                                                        xmlAttrs.put(WebMapContextTags.FORMAT.toLowerCase(), "image/gif");
1740
//                                                        xml.openTag(WebMapContextTags.LEGEND_URL, xmlAttrs);
1741
//                                                        xmlAttrs.clear();
1742
//                                                                // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1743
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1744
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_HREF, "http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif");
1745
//                                                                xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1746
//                                                                // </OnlineResource>
1747
//                                                    // </LegendURL>
1748
//                                                        xml.closeTag();
1749 5409 jaume
                                                // </Style>
1750 4940 jaume
                                                xml.closeTag();
1751 4730 jaume
                                        }
1752
                                // </StyleList>
1753 5409 jaume
                                xml.closeTag();
1754 4940 jaume
                                if (mapContextVersion.compareTo("1.0.0") > 0) {
1755 4730 jaume
                                // <DimensionList>
1756 4940 jaume
                                        xml.openTag(WebMapContextTags.DIMENSION_LIST);
1757 4730 jaume
                                        // <Dimension>
1758
                                        // </Dimension>
1759 4940 jaume
                                        xml.closeTag();
1760 4730 jaume
                                // </DimensionList>
1761 4917 jaume
                                }
1762 4730 jaume
                        } else {
1763
                                xml.writeTag("ERROR", PluginServices.getText(this, "unsupported_map_context_version"));
1764
                        }
1765 4833 jaume
                        // </Layer>
1766
                        xml.closeTag();
1767 4730 jaume
                }
1768 4915 jaume
                return xml.getXML();
1769 4730 jaume
        }
1770 6050 jaume
1771
        public ImageIcon getTocImageIcon() {
1772 5763 jmvivo
                return new ImageIcon(PluginServices.getPluginServices("com.iver.cit.gvsig.wms").getClassLoader().getResource("images/icoLayer.png"));
1773
        }
1774 6005 nacho
1775
        /*
1776
         *  (non-Javadoc)
1777
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1778
         */
1779
        public int[] getTileSize() {
1780 6050 jaume
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1781 6005 nacho
                return size;
1782
        }
1783
        /*
1784
         *  (non-Javadoc)
1785
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1786
         */
1787
        public boolean isTiled() {
1788
                return mustTileDraw;
1789
        }
1790 6050 jaume
1791 8765 jjdelcerro
        public Image getImageLegend() {
1792
                try {
1793 10518 ldiaz
                        //TODO:
1794
                        //store legend graphic and show it in TOC only when layer visible
1795
                        if (wms.hasLegendGraphic()){
1796 8765 jjdelcerro
                                wmsStatus.setOnlineResource((String) onlineResources.get("GetLegendGraphic"));
1797
                                File legend = getDriver().getLegendGraphic(wmsStatus, layerQuery, null);
1798
                                Image img = null;
1799
                                if ((legend!= null) && (legend.length() > 0))
1800
                                        img = ImageIO.read(legend);
1801
                                return img;
1802
                        }else{
1803
                                return null;
1804
                        }
1805
                }catch(Exception e){
1806 9056 nacho
                        //e.printStackTrace();
1807 8765 jjdelcerro
                        return null;
1808
                }
1809
        }
1810 6050 jaume
1811 9056 nacho
        /**
1812
         * Obtiene el grid asociado al raster que hay cargado en ese momento
1813
         * @return grid
1814
         */
1815
        public Grid getGrid(){
1816
                return grid;
1817
        }
1818
1819
        /**
1820
         * Obtiene el tipo de dato de la capa raster
1821
         * @return Entero que representa el tipo de dato de la capa raster.
1822
         */
1823
        public int getDataType() {
1824
                return rasterFile.getDataType();
1825
        }
1826 10362 ldiaz
        public boolean isQueryable(){
1827
                return queryable;
1828
        }
1829 3746 jaume
}