Statistics
| Revision:

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

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