Statistics
| Revision:

root / trunk / extensions / extWMS / src / com / iver / cit / gvsig / fmap / layers / FLyrWMS.java @ 7836

History | View | Annotate | Download (52.9 KB)

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

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

    
68
import javax.imageio.ImageIO;
69
import javax.swing.ImageIcon;
70
import javax.swing.JOptionPane;
71

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

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

    
108

    
109

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

    
128
    public URL                                                         host;
129
    public String                                                 m_Format;
130

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

    
156

    
157
        private class MyCancellable implements ICancellable
158
        {
159

    
160
                private Cancellable original;
161
                public MyCancellable(Cancellable cancelOriginal)
162
                {
163
                        this.original = cancelOriginal;
164
                }
165
                public boolean isCanceled() {
166
                        return original.isCanceled();
167
                }
168

    
169
        }
170

    
171
        public FLyrWMS(){
172
                super();
173
        }
174

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

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

    
200
                        WMSLayerNode wmsNode = drv.getLayer(sLayer);
201

    
202
                        if (wmsNode == null){
203
                                throw new DriverIOException("The server '" + host + "' doesn't has the layer '" + sLayer + "'.");
204
                        }
205
                        if( sFormat == null ) {
206
                                sFormat = this.getGreatFormat(drv.getFormats());
207
                        }
208
                     if( sSRS == null ) {
209
                             sSRS = (String)wmsNode.getAllSrs().get(0);
210
                     }
211
                        if( fullExtent == null ) {
212
                                fullExtent = drv.getLayersExtent(sLayers,(String)wmsNode.getAllSrs().get(0));
213
                        }
214
                }
215

    
216

    
217
                this.setFullExtent(fullExtent);
218
                this.setFormat(sFormat);
219
                this.setLayerQuery(sLayer);
220
                this.setInfoLayerQuery("");
221
                this.setSRS(sSRS);
222
                this.setName(sLayer);
223
        }
224

    
225
        /**
226
         * It choose the best format to load different maps if the server
227
         * supports it. This format could be png, because it supports
228
         * transparency.
229
         * @param formats
230
         * Arraywith all the formats supported by the server
231
         * @return
232
         */
233
        private String getGreatFormat(Vector formats){
234
            for (int i=0 ; i<formats.size() ; i++){
235
                String format = (String) formats.get(i);
236
                    if (format.equals("image/jpg")){
237
                    return format;
238
                    }
239
                    if (format.equals("image/jpeg")){
240
                    return format;
241
                    }
242
            }
243

    
244
            return (String)formats.get(0);
245
        }
246

    
247
        /**
248
         * Clase que contiene los datos de visualizaci?n de WMS.
249
         * @author Nacho Brodin (brodin_ign@gva.es)
250
         */
251
        private class VisualStatusWMS{
252
                /**
253
                 * Ancho y alto de la imagen o del conjunto de tiles si los tiene. Coincide con
254
                 * el ancho y alto del viewPort
255
                 */
256
                private        int                                                        width = 0, height = 0;
257
                private double                                                minX = 0D, minY = 0D, maxX = 0D, maxY = 0D;
258
                private int                                                 bandCount = 0;
259
                private int                                                        dataType = DataBuffer.TYPE_UNDEFINED;
260
        }
261

    
262

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

    
273
                // Full extent
274
                xml.putProperty("fullExtent", StringUtilities.rect2String(fullExtent));
275

    
276
                // Host
277
                xml.putProperty("host", host.toExternalForm());
278

    
279
                // Part of the query that is not the host, or the
280
                // layer names, or other not listed bellow
281
                xml.putProperty("infoLayerQuery", infoLayerQuery);
282

    
283
                // Part of the query containing the layer names
284
                xml.putProperty("layerQuery", layerQuery);
285

    
286
                // Format
287
                xml.putProperty("format", m_Format);
288

    
289
                // SRS
290
                xml.putProperty("srs", m_SRS);
291
                if (status!=null)
292
                        status.getXMLEntity(xml, true, this);
293
                else{
294
                        status = new StatusLayerRaster();
295
                        status.getXMLEntity(xml, true, this);
296
                }
297

    
298
        // Transparency
299
        xml.putProperty("wms_transparency", wmsTransparency);
300

    
301
        // Styles
302
        if (styles!=null){
303
            String stylePr = "";
304
            for (int i = 0; i < styles.size(); i++) {
305
                stylePr += (String) styles.get(i);
306
                if (i<styles.size()-1)
307
                    stylePr += ",";
308
            }
309
            if (stylePr.endsWith(","))
310
                    stylePr += " ";
311
            xml.putProperty("styles", stylePr);
312
        }
313

    
314
        // Dimensions
315
        if (dimensions!=null){
316
            String dim = "";
317
            for (int i = 0; i < dimensions.size(); i++) {
318
                dim += (String) dimensions.get(i);
319
                if (i<dimensions.size()-1)
320
                    dim += ",";
321
            }
322
            if (dim.endsWith(","))
323
                    dim += " ";
324
            xml.putProperty("dimensions", dim);
325
        }
326

    
327
        // OnlineResources
328
        Iterator it = onlineResources.keySet().iterator();
329
        String strOnlines = "";
330
        while (it.hasNext()) {
331
                String key = (String) it.next();
332
                String value = (String) onlineResources.get(key);
333
                strOnlines = key+"~##SEP2##~"+value;
334
                if (it.hasNext())
335
                        strOnlines += "~##SEP1##~";
336
        }
337
        xml.putProperty("onlineResources", strOnlines);
338

    
339
        // Queryable
340
        xml.putProperty("queryable", queryable);
341

    
342
        // fixedSize
343
        if (isSizeFixed()) {
344
                xml.putProperty("fixedSize", true);
345
                xml.putProperty("fixedWidth", fixedSize.width);
346
                xml.putProperty("fixedHeight", fixedSize.height);
347
        }
348
        return xml;
349
        }
350

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

    
366
                try {
367
                        host = new URL(xml.getStringProperty("host"));
368
                } catch (MalformedURLException e) {
369
                        throw new XMLException(e);
370
                }
371

    
372
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
373
                layerQuery = xml.getStringProperty("layerQuery");
374
                m_Format = xml.getStringProperty("format");
375
                m_SRS = xml.getStringProperty("srs");
376
        }
377

    
378
        /**
379
         * A partir del XMLEntity reproduce la capa.
380
         *
381
         * @param xml XMLEntity
382
         *
383
         * @throws XMLException
384
         * @throws DriverException
385
         * @throws DriverIOException
386
         */
387
        public void setXMLEntity(XMLEntity xml)
388
                throws XMLException {
389
                super.setXMLEntity(xml);
390
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty(
391
                                        "fullExtent"));
392

    
393
                // Host
394
                try {
395
                        host = new URL(xml.getStringProperty("host"));
396
                } catch (MalformedURLException e) {
397
                        throw new XMLException(e);
398
                }
399

    
400
                // Part of the query that is not the host, or the
401
                // layer names, or other not listed bellow
402
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
403

    
404
                // Part of the query containing the layer names
405
                layerQuery = xml.getStringProperty("layerQuery");
406

    
407
                // Format
408
                m_Format = xml.getStringProperty("format");
409

    
410
                // SRS
411
                m_SRS = xml.getStringProperty("srs");
412

    
413
                String claseStr = StatusLayerRaster.defaultClass;
414
                if (xml.contains("raster.class")) {
415
                        claseStr = xml.getStringProperty("raster.class");
416
                }
417

    
418
                // Transparency
419
        if (xml.contains("wms_transparency"))
420
            wmsTransparency = xml.getBooleanProperty("wms_transparency");
421

    
422
        // Styles
423
        if (xml.contains("styles")){
424
            styles = new Vector();
425
            String[] stl = xml.getStringProperty("styles").split(",");
426

    
427
            for (int i = 0; i < stl.length; i++) {
428
                    if (stl[i].equals(" "))
429
                            stl[i]="";
430
                styles.add(stl[i]);
431
            }
432
        }
433

    
434
        // Dimensions
435
        if (xml.contains("dimensions")){
436
            dimensions = new Vector();
437
            String[] dims = xml.getStringProperty("dimensions").split(",");
438
            for (int i = 0; i < dims.length; i++){
439
                    if (dims[i].equals(" "))
440
                            dims[i]="";
441

    
442
                dimensions.add(dims[i]);
443
            }
444
        }
445

    
446
        // OnlineResources
447
        if (xml.contains("onlineResources")) {
448
                String[] operations = xml.getStringProperty("onlineResources").split("~##SEP1##~");
449
                for (int i = 0; i < operations.length; i++) {
450
                                String[] resources = operations[i].split("~##SEP2##~");
451
                                if (resources.length==2 && resources[1]!="")
452
                                        onlineResources.put(resources[0], resources[1]);
453
                        }
454
        }
455

    
456
        // Queryable
457
        queryable = true; // let's assume that the layer is queryable by default
458
        if (xml.contains("queryable"))
459
                queryable = xml.getBooleanProperty("queryable");
460

    
461
        // fixedSize
462
        if (xml.contains("fixedSize")) {
463
                fixedSize = new Dimension(xml.getIntProperty("fixedWidth"),
464
                                                  xml.getIntProperty("fixedHeight"));
465
        }
466

    
467
                if(status!=null)
468
                        status.setXMLEntity(xml, this);
469
                else{
470
                        if(claseStr!=null && !claseStr.equals("")){
471
                                try{
472
                                        Class clase = Class.forName(claseStr);
473
                                        Constructor constr = clase.getConstructor(null);
474
                                        status = (StatusRasterInterface)constr.newInstance(null);
475
                                        if(status!=null)
476
                                                status.setXMLEntity(xml, this);
477
                                }catch(ClassNotFoundException exc){
478
                                        exc.printStackTrace();
479
                                }catch(InstantiationException exc){
480
                                        exc.printStackTrace();
481
                                }catch(IllegalAccessException exc){
482
                                        exc.printStackTrace();
483
                                }catch(NoSuchMethodException exc){
484
                                        exc.printStackTrace();
485
                                }catch(InvocationTargetException exc){
486
                                        exc.printStackTrace();
487
                                }
488
                        }
489
                }
490
                firstLoad = true;
491
        }
492

    
493
        /**
494
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(com.iver.cit.gvsig.fmap.operations.QueriedPoint)
495
         */
496
        public XMLItem[] getInfo(Point p, double tolerance) throws DriverException {
497
                XMLItem[] item =  new XMLItem[1];
498
                try {
499
                        if (queryable)
500
                        {
501
                                //TODO
502
                                // check if there are layers which are not queryable
503
                                ViewPort viewPort = getMapContext().getViewPort();
504

    
505
                                Point tiledPoint = new Point((int) p.getX() % maxTilePrintWidth, (int) p.getY() % maxTilePrintHeight);
506
                                Rectangle rect = new Rectangle(0, 0, viewPort.getImageWidth() - 1, viewPort.getImageHeight() - 1);
507
                                Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, rect);
508
                                tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
509
                                int nCols = tiles.getNumCols();
510

    
511
                                int col = (int) p.getX() / maxTilePrintWidth;
512
                                int row = (int) p.getY() / maxTilePrintHeight;
513
                                int tileIndex = (row*nCols) + col;
514

    
515
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileIndex);
516
                                wmsStatus.setExtent(vp.getExtent());
517
                                wmsStatus.setHeight(vp.getImageHeight());
518
                                wmsStatus.setWidth(vp.getImageWidth());
519
                                wmsStatus.setOnlineResource((String) onlineResources.get("GetFeatureInfo"));
520
                                item[0] = new StringXMLItem(new String(getDriver()
521
                                                .getFeatureInfo(wmsStatus, (int) tiledPoint.getX(), (int) tiledPoint.getY(), Integer.MAX_VALUE)),this);
522
                                return item;
523
                        }
524
                        else
525
                        {
526
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
527
                                                PluginServices.getText(this, "wms_not_queryable"));
528
                                item[0] =  new StringXMLItem("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><info></info>",this);
529
                                return item;
530
                        }
531
                } catch (WMSException  e) {
532
                        item[0] = new StringXMLItem("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><exception>" +
533
                        e.getMessage() + "</exception>", this);
534
                        return item;
535
                }
536
                /*azabala
537
                catch (ValidationException e) {
538
                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
539
                } catch (UnsupportedVersionException e) {
540
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
541
                } catch (IOException e) {
542
                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
543
                }
544
                */
545
                catch (ValidationException e) {
546
                        UnknownResponseFormatExceptionType type =
547
                                new UnknownResponseFormatExceptionType();
548
                        type.setLayerName(getName());
549
                        try {
550
                                type.setDriverName("WMS Driver");
551
                        } catch (Exception e1) {
552
                                e1.printStackTrace();
553
                        }
554
                        type.setFormat(m_Format);
555
                        type.setHost(host);
556
                        type.setProtocol("WMS");
557
                        DriverException exception = new DriverException("unknown_response_format", type);
558
                        throw exception;
559

    
560
                } catch (UnsupportedVersionException e) {
561
                        UnsuportedProtocolVersionExceptionType type =
562
                                new UnsuportedProtocolVersionExceptionType();
563
                        type.setLayerName(getName());
564
                        try {
565
                                type.setDriverName("WMS Driver");
566
                        } catch (Exception ex){
567
                        }
568
                        type.setUrl(host);
569
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e, type);
570

    
571
                } catch (IOException e) {
572
                        ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
573
                        type.setLayerName(getName());
574
                        try {
575
                                type.setDriverName("WMS Driver");
576
                        } catch (Exception e1) {
577
                        }
578
                        type.setHost(host);
579
                        throw new DriverException(PluginServices.
580
                                        getText(this, "connect_error"), e, type);
581
                }
582
                catch (NoninvertibleTransformException e) {
583
                        NotificationManager.addError("NotinvertibleTransform", e);
584
                }
585
                return null;
586
        }
587

    
588
        /**
589
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent()
590
         */
591
        public Rectangle2D getFullExtent() {
592
                return fullExtent;
593
        }
594

    
595
        /**
596
         *
597
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#draw(java.awt.image.BufferedImage,
598
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
599
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
600
         */
601
        private int callCount; // mess code, represents the amount of times the methods drawFixedSize or drawTile where tried for an extent
602
        private static final int MAX_RETRY_TIMES = 5; // mess code, represents the max amount of retries allowed.
603
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
604
                        Cancellable cancel,double scale) throws DriverException {
605
                callCount = 0; // mess code
606
                if (isWithinScale(scale)){
607
                        Point2D p = viewPort.getOffset();
608
                        // p will be (0, 0) when drawing a view or other when painting onto
609
                        // the Layout.
610
                        visualStatus.width =  viewPort.getImageWidth();
611
                        visualStatus.height =  viewPort.getImageHeight();
612
                        visualStatus.minX = viewPort.getAdjustedExtent().getMinX();
613
                        visualStatus.minY = viewPort.getAdjustedExtent().getMinY();
614
                        visualStatus.maxX = viewPort.getAdjustedExtent().getMaxX();
615
                        visualStatus.maxY = viewPort.getAdjustedExtent().getMaxY();
616

    
617

    
618
                        if (isSizeFixed()) {
619
                                // This condition handles those situations in which the server can
620
                                // only give static extent and resolution maps despite we need
621
                                // a specific BBOX and pixel WIDTH and HEIGHT
622
                                drawFixedSize(g, viewPort, cancel);
623

    
624
                        } else {
625
                                if(mustTileDraw){
626
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), viewPort.getImageWidth(), viewPort.getImageHeight());
627
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
628
                                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
629
                                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
630
                                                // drawing part
631
                                                try {
632
                                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
633
                                                        drawTile(g, vp, cancel);
634
                                                } catch (NoninvertibleTransformException e) {
635
                                                        e.printStackTrace();
636
                                                }
637
                                        }
638
                                }else
639
                                        drawTile(g, viewPort, cancel);
640
                        }
641
                }
642
//                Runtime r = Runtime.getRuntime();
643
//                long mem = r.totalMemory() - r.freeMemory();
644
//                System.err.println("Memoria total: " + (mem / 1024) +"KB");
645
        }
646

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

    
652

    
653
                // This is the extent that will be requested
654
                Rectangle2D bBox = getFullExtent();
655
                MyCancellable c = new MyCancellable(cancel);
656

    
657
                try {
658
                        wmsStatus.setExtent( bBox );
659
                        wmsStatus.setFormat( m_Format );
660
                        wmsStatus.setHeight( fixedSize.height );
661
                        wmsStatus.setWidth( fixedSize.width );
662
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
663
                        wmsStatus.setSrs(m_SRS);
664
                        wmsStatus.setStyles(styles);
665
                        wmsStatus.setDimensions(dimensions);
666
                        wmsStatus.setTransparency(wmsTransparency);
667
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
668
                        File f = getDriver().getMap(wmsStatus, c);
669
                        if (f == null)
670
                                return;
671
                        String nameWorldFile = f.getPath() + getExtensionWorldFile();
672
                        com.iver.andami.Utilities.createTemp(nameWorldFile, this.getDataWorldFile(bBox, fixedSize));
673

    
674
                        if(status!=null && firstLoad){
675
                                status.applyStatus(this);
676
                                firstLoad = false;
677
                        }
678

    
679
                        // And finally, obtain the extent intersecting the view and the BBox
680
                        // to draw to.
681
                        Rectangle2D extent = new Rectangle2D.Double();
682
                        Rectangle2D.intersect(vp.getAdjustedExtent(), bBox, extent);
683

    
684
                        ViewPortData vpData = new ViewPortData(
685
                                vp.getProjection(), new Extent(extent), fixedSize );
686
                        vpData.setMat(vp.getAffineTransform());
687

    
688
                        rasterProcess(g, vpData, f);
689

    
690
                } catch (ValidationException e) {
691
                        if (!c.isCanceled())
692
                        {
693
                                UnknownResponseFormatExceptionType type =
694
                                        new UnknownResponseFormatExceptionType();
695
                                type.setLayerName(getName());
696
                                try {
697
                                        type.setDriverName("WMS Driver");
698
                                } catch (Exception e1) {
699
                                        e1.printStackTrace();
700
                                }
701
                                type.setFormat(m_Format);
702
                                type.setHost(host);
703
                                type.setProtocol("WMS");
704
                                DriverException exception = new DriverException("unknown_response_format", type);
705
                                throw exception;
706
                        }
707
//        azabala                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
708
                } catch (UnsupportedVersionException e) {
709
                        if (!c.isCanceled()){
710
                                UnsuportedProtocolVersionExceptionType type =
711
                                        new UnsuportedProtocolVersionExceptionType();
712
                                type.setLayerName(getName());
713
                                try {
714
                                        type.setDriverName("WMS Driver");
715
                                } catch (Exception ex){
716
                                }
717
                                type.setUrl(host);
718
                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e, type);
719
                        }
720
//        azabala                throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
721
                } catch (IOException e) {
722
                        if (!c.isCanceled())
723
                                if (callCount<MAX_RETRY_TIMES) { // mess code
724
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
725
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
726
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
727
                                        drawFixedSize(g, vp, cancel); // mess code
728
                                } // mess code
729

    
730
                                if (callCount == 1) { // mess code
731
                                        ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
732
                                        type.setLayerName(getName());
733
                                        try {
734
                                                type.setDriverName("WMS Driver");
735
                                        } catch (Exception e1) {
736
                                        }
737
                                        type.setHost(host);
738
                                        throw new DriverException(PluginServices.
739
                                                        getText(this, "connect_error"), e, type);
740
//        azabala        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
741
                                } // mess code
742

    
743

    
744
                } catch (WMSException e) {
745
                        if (!c.isCanceled()) {
746
                                if (callCount<MAX_RETRY_TIMES) { // mess code
747
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
748
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
749
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
750
                                        drawFixedSize(g, vp, cancel); // mess code
751
                                } // mess code
752
                                if (callCount == 1) { // mess code
753
//                azabala                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
754
                                        WMSDriverExceptionType type = new WMSDriverExceptionType();
755
                                        type.setLayerName(getName());
756
                                        try {
757
                                                type.setDriverName("WMS Driver");
758
                                        } catch (Exception e1) {
759
                                        }
760
                                        type.setWcsStatus(this.wmsStatus);
761
                                        if (!isPrinting)
762
                                                this.setVisible(false);
763
                                        throw new DriverException("Error WMS", e,  type);
764

    
765

    
766
                                } // mess code
767
                        }
768
                }
769
                callCount--; // mess code
770
        }
771

    
772
        /**
773
         * This is the method used to draw a tile in a WMS mosaic layer.
774
         */
775
        private void drawTile(Graphics2D g, ViewPort vp, Cancellable cancel) throws DriverException {
776
                callCount++;
777
                // Compute the query geometry
778
                // 1. Check if it is within borders
779
                Rectangle2D extent = getFullExtent();
780
        if ((vp.getAdjustedExtent().getMinX() > extent.getMaxX()) ||
781
                (vp.getAdjustedExtent().getMinY() > extent.getMaxY()) ||
782
                (vp.getAdjustedExtent().getMaxX() < extent.getMinX()) ||
783
                (vp.getAdjustedExtent().getMaxY() < extent.getMinY())) {
784
            return;
785
        }
786

    
787
        // 2. Compute extent to be requested.
788
        Rectangle2D bBox = new Rectangle2D.Double();
789
        Rectangle2D.intersect(vp.getExtent(), extent, bBox);
790

    
791
        // 3. Compute size in pixels
792
        double scalex = vp.getAffineTransform().getScaleX();
793
        double scaley = vp.getAffineTransform().getScaleY();
794
        int wImg = (int) Math.ceil(Math.abs(bBox.getWidth() * scalex) + 1);
795
        int hImg = (int) Math.ceil(Math.abs(bBox.getHeight() * scaley) + 1);
796

    
797
        Dimension sz = new Dimension(wImg, hImg);
798

    
799
        if ((wImg <= 0) || (hImg <= 0)) {
800
            return;
801
        }
802
        MyCancellable c = new MyCancellable(cancel);
803

    
804
                try {
805
//                        wImg = vp.getImageWidth();
806
//                        hImg = vp.getImageHeight();
807
                        sz = new Dimension(wImg, hImg);
808
                        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
809

    
810

    
811
                        wmsStatus.setExtent( bBox );
812
                        wmsStatus.setFormat(m_Format);
813
                        wmsStatus.setHeight( hImg );
814
                        wmsStatus.setWidth( wImg );
815
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
816
                        wmsStatus.setSrs(m_SRS);
817
                        wmsStatus.setStyles(styles);
818
                        wmsStatus.setDimensions(dimensions);
819
                        wmsStatus.setTransparency(wmsTransparency);
820
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
821

    
822
                        // begin patch; Avoid to request too small tiles. 
823
                        // This generally occurs when printing 
824

    
825
                        if (wImg < minTilePrintWidth) {
826
                                double wScale = (double) minTilePrintWidth / wImg;
827
                                wmsStatus.setWidth(minTilePrintWidth);
828
                                Rectangle2D sExtent = wmsStatus.getExtent();
829
                                Point2D initialPoint = new Point2D.Double(sExtent.getX(), sExtent.getY());
830
                                sExtent.setRect(sExtent.getX()*wScale, sExtent.getY(), sExtent.getWidth()*wScale, sExtent.getHeight());
831
                                if (!bBox.contains(initialPoint)) {
832
                                        sExtent.setRect(sExtent.getX() - initialPoint.getX(), sExtent.getY(), sExtent.getWidth(), sExtent.getHeight());
833
                                }
834
                        }
835

    
836
                        if (hImg < minTilePrintHeight) {
837
                                double hScale = (double) minTilePrintHeight / hImg;
838
                                wmsStatus.setHeight(minTilePrintHeight);
839
                                Rectangle2D sExtent = wmsStatus.getExtent();
840
                                Point2D initialPoint = new Point2D.Double(sExtent.getX(), sExtent.getY());
841
                                sExtent.setRect(sExtent.getX(), sExtent.getY()*hScale, sExtent.getWidth(), sExtent.getHeight()*hScale);
842
                                if (!bBox.contains(initialPoint)) {
843
                                        sExtent.setRect(sExtent.getX(), sExtent.getY() - initialPoint.getY(), sExtent.getWidth(), sExtent.getHeight());
844
                                }
845
                        }
846

    
847
                        // end patch
848
                        File f = getDriver().getMap(wmsStatus, c);
849
                        if (f == null)
850
                                return;
851
                        String nameWordFile = f.getPath() + getExtensionWorldFile();
852
                        com.iver.andami.Utilities.createTemp(nameWordFile, this.getDataWorldFile(bBox, sz));
853

    
854
                        ViewPortData vpData = new ViewPortData(
855
                                vp.getProjection(), new Extent(bBox), sz );
856
                        vpData.setMat(vp.getAffineTransform());
857

    
858
                        rasterProcess(g, vpData, f);
859

    
860
                } catch (ValidationException e) {
861
                //azabala
862
//                        if (!c.isCanceled())
863
//                                throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
864

    
865
                        if (!c.isCanceled())
866
                        {
867
                                UnknownResponseFormatExceptionType type =
868
                                        new UnknownResponseFormatExceptionType();
869
                                type.setLayerName(getName());
870
                                try {
871
                                        type.setDriverName("WMS Driver");
872
                                } catch (Exception e1) {
873
                                        e1.printStackTrace();
874
                                }
875
                                type.setFormat(m_Format);
876
                                type.setHost(host);
877
                                type.setProtocol("WMS");
878
                                DriverException exception = new DriverException("unknown_response_format", type);
879
                                throw exception;
880
                        }
881
                } catch (UnsupportedVersionException e) {
882

    
883
//                        if (!c.isCanceled())
884
//                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
885

    
886
                        if (!c.isCanceled()){
887
                                UnsuportedProtocolVersionExceptionType type =
888
                                        new UnsuportedProtocolVersionExceptionType();
889
                                type.setLayerName(getName());
890
                                try {
891
                                        type.setDriverName("WMS Driver");
892
                                } catch (Exception ex){
893
                                }
894
                                type.setUrl(host);
895
                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e, type);
896
                        }
897

    
898
                } catch (IOException e) {
899
                        /*azabala
900
                        if (!c.isCanceled())
901
                                if (callCount<MAX_RETRY_TIMES) {
902
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null);
903
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error
904
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0)
905
                                        drawTile(g, vp, cancel);
906
                                }
907
                                if (callCount == 1) {
908
                                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
909
                                }
910
                        */
911
                        if (!c.isCanceled()){
912
                                if (callCount<MAX_RETRY_TIMES) { // mess code
913
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
914
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
915
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
916

    
917
                                        //FIXME Aqu? deberiamos llamar a drawTile o a drawFixedSize????
918
                                        drawFixedSize(g, vp, cancel); // mess code
919
                                } // mess code
920
                        }
921
                        if (callCount == 1) { // mess code
922
                                ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
923
                                type.setLayerName(getName());
924
                                try {
925
                                        type.setDriverName("WMS Driver");
926
                                } catch (Exception e1) {}
927
                                type.setHost(host);
928
                                throw new DriverException(PluginServices.
929
                                                        getText(this, "connect_error"), e, type);
930
                        }//if
931
                } catch (WMSException e) {
932
                        /*azabala
933
                        if (!c.isCanceled()) {
934
                                if (callCount<MAX_RETRY_TIMES) {
935
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawTile() ] Failed in trying " + callCount + "/" + MAX_RETRY_TIMES +" \n", null);
936
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error
937
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0)
938
                                        drawTile(g, vp, cancel);
939
                                }
940
                                if (callCount == 1) {
941
                                        if (!isPrinting) {
942
                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
943
                                                this.setVisible(false);
944
                                        }
945
                                }
946
                        }
947
                        */
948
                        if (!c.isCanceled()) {
949
                                if (callCount<MAX_RETRY_TIMES) { // mess code
950
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
951
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
952
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
953
                                        drawTile(g, vp, cancel);
954
                                } // mess code
955
                                if (callCount == 1) { // mess code
956
//                azabala                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
957
                                        WMSDriverExceptionType type = new WMSDriverExceptionType();
958
                                        type.setLayerName(getName());
959
                                        try {
960
                                                type.setDriverName("WMS Driver");
961
                                        } catch (Exception e1) {
962
                                        }
963
                                        type.setWcsStatus(this.wmsStatus);
964
                                        if (!isPrinting)
965
                                                this.setVisible(false);
966
                                        throw new DriverException("Error WMS", e,  type);
967

    
968

    
969
                                } //if
970
                        }//if
971
                }//catch
972
                callCount--;
973
        }
974

    
975
        /**
976
         * Obtiene la extensi?n del fichero de georreferenciaci?n
977
         * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
978
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
979
         */
980
        private String getExtensionWorldFile(){
981
                String extWorldFile = ".wld";
982
            if(m_Format.equals("image/tif") || m_Format.equals("image/tiff"))
983
                    extWorldFile = ".tfw";
984
            if(m_Format.equals("image/jpeg"))
985
                    extWorldFile = ".jpgw";
986
            return extWorldFile;
987
        }
988

    
989
        /**
990
         * Calcula el contenido del fichero de georreferenciaci?n de una imagen.
991
         * @param bBox Tama?o y posici?n de la imagen (en coordenadas de usuario)
992
         * @param sz Tama?o de la imagen en pixeles.
993
         * @return el 'WorldFile', como String.
994
         * @throws IOException
995
         */
996
        public String getDataWorldFile(Rectangle2D bBox, Dimension sz) throws IOException {
997
                StringBuffer data = new StringBuffer();
998
            data.append((bBox.getMaxX() - bBox.getMinX())/(sz.getWidth() - 1)+"\n");
999
            data.append("0.0\n");
1000
            data.append("0.0\n");
1001
            data.append((bBox.getMaxY() - bBox.getMinY())/(sz.getHeight() - 1)+"\n");
1002
            data.append(""+bBox.getMinX()+"\n");
1003
            data.append(""+bBox.getMinY()+"\n");
1004
            return data.toString();
1005
        }
1006

    
1007
        /**
1008
         * Dibuja una imagen usando PxRaster
1009
         * @param g        Graphics2D en el que hay que dibujar.
1010
         * @param vpData Par?metros de visualizaci?n
1011
         * @param file La imagen en cuesti?n.
1012
         */
1013
        private void rasterProcess(Graphics2D g, ViewPortData vpData, File file) {
1014

    
1015
                //Creamos el PxRaster
1016
                rasterFile = new GdalFile(vpData.getProjection(), file.getAbsolutePath());
1017
                raster = new PxRaster(rasterFile, null, rasterFile.getExtent());
1018

    
1019
                if(status!=null && firstLoad){
1020
                        status.applyStatus(this);
1021
                        firstLoad = false;
1022
                }
1023

    
1024
                //Recuperamos la pila de filtros si ya hubiese sido cargado antes
1025
                if(this.filterStack!=null)
1026
                        raster.filterStack = this.filterStack;
1027

    
1028
                raster.setTransparency(false);
1029

    
1030
                //Asignamos transparencia y orden de bandas
1031
                if(this.transparency==-1 && !firstLoad);
1032
                else
1033
                        raster.setTransparency(this.transparency);
1034

    
1035
                raster.setBand(GeoRasterFile.RED_BAND,rband);
1036
                raster.setBand(GeoRasterFile.GREEN_BAND, gband);
1037
                raster.setBand(GeoRasterFile.BLUE_BAND, bband);
1038

    
1039
                //Despues del primer pxRaster asignamos el stackManager guardado para los siguientes.
1040
                //Con esto conseguimos asignar los cambios que se hayan producido desde el cuadro de
1041
                //propiedades cuando creamos un nuevo pxRaster
1042
                if(this.stackManager != null)
1043
                        raster.setStackManager(this.stackManager);
1044

    
1045
                if(visualStatus != null){
1046
                        visualStatus.bandCount = raster.getBandCount();
1047
                        visualStatus.dataType = raster.getDataType();
1048
                }
1049

    
1050
                raster.draw(g, vpData);
1051

    
1052
                //En el primer pxRaster de una imagen obtenemos el Stack Manager para poder modificarlo
1053
                //si queremos desde las propiedades
1054

    
1055
                if(this.stackManager == null)
1056
                        this.stackManager = raster.getStackManager();
1057

    
1058
                if(this.filterStack == null)
1059
                        this.filterStack = raster.filterStack;
1060

    
1061
                //rasterFile.close();
1062
        }
1063

    
1064
        /**
1065
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D,
1066
         *                 com.iver.cit.gvsig.fmap.ViewPort,
1067
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
1068
         */
1069
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale)
1070
                throws DriverException {
1071
                if (isVisible() && isWithinScale(scale)){
1072
                isPrinting = true;
1073
                if (!mustTilePrint) {
1074
                        draw(null, g, viewPort, cancel,scale);
1075
                } else {
1076
                // Para no pedir imagenes demasiado grandes, vamos
1077
                // a hacer lo mismo que hace EcwFile: chunkear.
1078
                // Llamamos a drawView con cuadraditos m?s peque?os
1079
                // del BufferedImage ni caso, cuando se imprime viene con null
1080

    
1081
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
1082
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
1083
                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
1084
                            // Parte que dibuja
1085
                            try {
1086
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
1087
                                drawTile(g, vp, cancel);
1088
                                } catch (NoninvertibleTransformException e) {
1089
                                        e.printStackTrace();
1090
                                }
1091
                }
1092
                }
1093
            isPrinting = false;
1094
                }
1095
        }
1096

    
1097
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale)
1098
                throws DriverException {
1099
                draw(null, g, viewPort, cancel,scale);
1100
        }
1101

    
1102
        /**
1103
         * Devuelve el FMapWMSDriver.
1104
         *
1105
         * @return FMapWMSDriver
1106
         *
1107
         * @throws IllegalStateException
1108
         * @throws ValidationException
1109
         * @throws UnsupportedVersionException
1110
         * @throws IOException
1111
         */
1112
        private FMapWMSDriver getDriver()
1113
                throws IllegalStateException, ValidationException,
1114
                        UnsupportedVersionException, IOException {
1115
                return FMapWMSDriverFactory.getFMapDriverForURL(host);
1116
        }
1117

    
1118
        /**
1119
         * Devuelve el FMapWMSDriver.
1120
         *
1121
         * @return FMapWMSDriver
1122
         *
1123
         * @throws IllegalStateException
1124
         * @throws ValidationException
1125
         * @throws UnsupportedVersionException
1126
         * @throws IOException
1127
         */
1128
        public void setDriver(FMapWMSDriver drv) {
1129
                wms = drv;
1130
        }
1131

    
1132
        /**
1133
         * Devuelve el URL.
1134
         *
1135
         * @return URL.
1136
         */
1137
        public URL getHost() {
1138
                return host;
1139
        }
1140

    
1141
        /**
1142
         * Inserta el URL.
1143
         *
1144
         * @param host URL.
1145
         */
1146
        public void setHost(URL host) {
1147
                this.host = host;
1148
        }
1149

    
1150
        /**
1151
         * Devuelve la informaci?n de la consulta.
1152
         *
1153
         * @return String.
1154
         */
1155
        public String getInfoLayerQuery() {
1156
                return infoLayerQuery;
1157
        }
1158

    
1159
        /**
1160
         * Inserta la informaci?n de la consulta.
1161
         *
1162
         * @param infoLayerQuery String.
1163
         */
1164
        public void setInfoLayerQuery(String infoLayerQuery) {
1165
                this.infoLayerQuery = infoLayerQuery;
1166
        }
1167

    
1168
        /**
1169
         * Devuelve la consulta.
1170
         *
1171
         * @return String.
1172
         */
1173
        public String getLayerQuery() {
1174
                return layerQuery;
1175
        }
1176

    
1177
        /**
1178
         * Inserta la consulta.
1179
         *
1180
         * @param layerQuery consulta.
1181
         */
1182
        public void setLayerQuery(String layerQuery) {
1183
                this.layerQuery = layerQuery;
1184
        }
1185

    
1186
        /**
1187
         * Devuelve el formato.
1188
         *
1189
         * @return Formato.
1190
         */
1191
        public String getFormat() {
1192
                return m_Format;
1193
        }
1194

    
1195
        /**
1196
         * Inserta el formato.
1197
         *
1198
         * @param format Formato.
1199
         */
1200
        public void setFormat(String format) {
1201
                m_Format = format;
1202
        }
1203

    
1204
        /**
1205
         * Devuelve el SRS.
1206
         *
1207
         * @return SRS.
1208
         */
1209
        public String getSRS() {
1210
                return m_SRS;
1211
        }
1212

    
1213
        /**
1214
         * Inserta el SRS.
1215
         *
1216
         * @param m_srs SRS.
1217
         */
1218
        public void setSRS(String m_srs) {
1219
                m_SRS = m_srs;
1220
        }
1221

    
1222
        /**
1223
         * Inserta la extensi?n total de la capa.
1224
         *
1225
         * @param fullExtent Rect?ngulo.
1226
         */
1227
        public void setFullExtent(Rectangle2D fullExtent) {
1228
                this.fullExtent = fullExtent;
1229
        }
1230

    
1231
        public HashMap getProperties() {
1232
                HashMap info = new HashMap();
1233
        String[] layerNames = getLayerQuery().split(",");
1234
        Vector layers = new Vector(layerNames.length);
1235
        try {
1236
            if(getDriver().connect(null)){
1237
                for (int i = 0; i < layerNames.length; i++) {
1238
                    layers.add(i, getDriver().getLayer(layerNames[i]));
1239
                }
1240
                info.put("name", getName());
1241
                info.put("selectedLayers", layers);
1242
                info.put("host", getHost());
1243
                info.put("srs", getSRS());
1244
                info.put("format", getFormat());
1245
                info.put("wmsTransparency", new Boolean(wmsTransparency));
1246
                info.put("styles", styles);
1247
                info.put("dimensions", dimensions);
1248
                info.put("fixedSize", fixedSize);
1249
                return info;
1250
            }
1251
        } catch (Exception e) {
1252
            e.printStackTrace();
1253
        }
1254
        return null;
1255
        }
1256

    
1257
        /**
1258
         * Asignar el estado del raster
1259
         * @param status
1260
         */
1261
        public void setStatus(StatusRasterInterface status){
1262
                this.status = status;
1263
        }
1264

    
1265
        /**
1266
         * Obtiene el estado del raster
1267
         * @return
1268
         */
1269
        public StatusRasterInterface getStatus(){
1270
                return this.status;
1271
        }
1272

    
1273
        /* (non-Javadoc)
1274
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getAttributes()
1275
         */
1276
        public ArrayList getAttributes() {
1277
                if(rasterFile != null){
1278
                        ArrayList attr = new ArrayList();
1279
                        String dataType = "Byte";
1280
                        if (rasterFile.getDataType() == DataBuffer.TYPE_BYTE) dataType = "Byte";
1281
                        else if (visualStatus.dataType == DataBuffer.TYPE_SHORT)
1282
                                dataType = "Short";
1283
                        else if (visualStatus.dataType == DataBuffer.TYPE_USHORT)
1284
                                dataType = "Unsigned Short";
1285
                        else if (visualStatus.dataType == DataBuffer.TYPE_INT)
1286
                                dataType = "Integer";
1287
                        else if (visualStatus.dataType == DataBuffer.TYPE_FLOAT)
1288
                                dataType = "Float";
1289
                        else if (visualStatus.dataType == DataBuffer.TYPE_DOUBLE)
1290
                                dataType = "Double";
1291
                        else
1292
                                dataType = "Unknown";
1293

    
1294
                        Object [][] a = {
1295
                                {"Filename",rasterFile.getName().substring(rasterFile.getName().lastIndexOf("/")+1, rasterFile.getName().length())},
1296
                                {"Filesize",new Long(0)},
1297
                                {"Width",new Integer((int)this.getWidth())},
1298
                                {"Height", new Integer((int)this.getHeight())},
1299
                                {"Bands", new Integer(visualStatus.bandCount)},
1300
                                {"BandDataType", dataType}
1301
                        };
1302
                        for (int i=0; i<a.length; i++)
1303
                                attr.add(a[i]);
1304

    
1305
                        return attr;
1306
                }
1307
                return  null;
1308
        }
1309

    
1310
        /* (non-Javadoc)
1311
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getFilterStack()
1312
         */
1313
        public RasterFilterStack getFilterStack() {
1314
                if(raster!=null)
1315
                        return raster.filterStack;
1316
                return null;
1317
        }
1318
        /* (non-Javadoc)
1319
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getHeight()
1320
         */
1321
        public double getHeight() {
1322
                return visualStatus.height;
1323
        }
1324

    
1325
        /* (non-Javadoc)
1326
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxX()
1327
         */
1328
        public double getMaxX() {
1329
                return visualStatus.maxX;
1330
        }
1331

    
1332
        /* (non-Javadoc)
1333
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxY()
1334
         */
1335
        public double getMaxY() {
1336
                return visualStatus.maxY;
1337
        }
1338

    
1339
        /* (non-Javadoc)
1340
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinX()
1341
         */
1342
        public double getMinX() {
1343
                return visualStatus.minX;
1344
        }
1345

    
1346
        /* (non-Javadoc)
1347
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinY()
1348
         */
1349
        public double getMinY() {
1350
                return visualStatus.minY;
1351
        }
1352
        /* (non-Javadoc)
1353
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getPixel(double, double)
1354
         */
1355
        public int[] getPixel(double wcx, double wcy) {
1356
                if(getPxRaster() != null)
1357
                        return getPxRaster().getPixel(wcx, wcy);
1358
        return null;
1359
        }
1360
        /* (non-Javadoc)
1361
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getSource()
1362
         */
1363
        public RasterAdapter getSource() {
1364
                return null;
1365
        }
1366
        /* (non-Javadoc)
1367
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getWidth()
1368
         */
1369
        public double getWidth() {
1370
                return visualStatus.width;
1371
        }
1372
        /* (non-Javadoc)
1373
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setBand(int, int)
1374
         */
1375
        public void setBand(int flag, int nBand) {
1376
                switch(flag){
1377
                case GeoRasterFile.RED_BAND:setBandR(nBand);break;
1378
                case GeoRasterFile.GREEN_BAND:setBandG(nBand);break;
1379
                case GeoRasterFile.BLUE_BAND:setBandB(nBand);break;
1380
                }
1381
        }
1382
        /* (non-Javadoc)
1383
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setFilterStack(org.cresques.io.raster.RasterFilterStack)
1384
         */
1385
        public void setFilterStack(RasterFilterStack stack) {
1386
                this.filterStack = stack;
1387
        }
1388
        /* (non-Javadoc)
1389
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPos(int, int)
1390
         */
1391
        public void setPos(int x, int y) {
1392
                this.posX = x;
1393
                this.posY = y;
1394
        }
1395

    
1396
        /* (non-Javadoc)
1397
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPosWC(double, double)
1398
         */
1399
        public void setPosWC(double x, double y) {
1400
                this.posXWC = x;
1401
                this.posYWC = y;
1402
        }
1403

    
1404
        /* (non-Javadoc)
1405
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setRGB(int, int, int)
1406
         */
1407
        public void setRGB(int r, int g, int b) {
1408
                this.r = r;
1409
                this.g = g;
1410
                this.b = b;
1411
        }
1412
        /* (non-Javadoc)
1413
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setSource(com.iver.cit.gvsig.fmap.layers.RasterAdapter)
1414
         */
1415
        public void setSource(RasterAdapter ra) {
1416
        }
1417
        /**
1418
         * @return Returns the raster.
1419
         */
1420
        public PxRaster getPxRaster() {
1421
                return raster;
1422
        }
1423
        /**
1424
         * @return Returns the rasterFile.
1425
         */
1426
        public GeoRasterFile getGeoRasterFile() {
1427
                return rasterFile;
1428
        }
1429

    
1430
        public void setTransparency(int trans) {
1431
                this.transparency = trans;
1432
        }
1433

    
1434
        /**
1435
         * Sets the R-band.
1436
         *
1437
         * Asigna la banda R.
1438
         * @param r
1439
         */
1440
        public void setBandR(int r){
1441
                this.rband = r;
1442
        }
1443

    
1444
        /**
1445
         * Sets the G-band.
1446
         *
1447
         * Asigna la banda G
1448
         * @param g
1449
         */
1450
        public void setBandG(int g){
1451
                this.gband = g;
1452
        }
1453

    
1454
        /**
1455
         * Sets the B-band.
1456
         *
1457
         * Asigna la banda B
1458
         * @param b
1459
         */
1460
        public void setBandB(int b){
1461
                this.bband = b;
1462
        }
1463

    
1464
    /**
1465
     * @return Returns the wmsTransparency.
1466
     */
1467
    public boolean isWmsTransparent() {
1468
        return wmsTransparency;
1469
    }
1470

    
1471
    /**
1472
     * @param wmsTransparency The wmsTransparency to set.
1473
     */
1474
    public void setWmsTransparency(boolean wmsTransparency) {
1475
        this.wmsTransparency = wmsTransparency;
1476
    }
1477

    
1478
     /**
1479
     * @param styles
1480
     */
1481
    public void setStyles(Vector styles) {
1482
            //laura:
1483
            //layer query is built with the layer in reverse order
1484
            // so here we build the styles upside-down.
1485
            if (styles != null)
1486
            {
1487
                    this.styles = new Vector();
1488
                    for(int i = styles.size()-1; i>=0; i--)
1489
                    {
1490
                            this.styles.add(styles.elementAt(i));
1491
                    }
1492
            }
1493
    }
1494

    
1495
    /**
1496
     * Sets the dimension vector that is a list of key-value pairs containing
1497
     * the name of the dimension and the value for it
1498
     * @param dimensions
1499
     */
1500
    public void setDimensions(Vector dimensions) {
1501
        this.dimensions = dimensions;
1502
    }
1503

    
1504
    /**
1505
     * Sets the set of URLs that should be accessed for each operation performed
1506
     * to the server.
1507
     *
1508
     * @param onlineResources
1509
     */
1510
        public void setOnlineResources(Hashtable onlineResources) {
1511
                this.onlineResources = onlineResources;
1512
        }
1513

    
1514
        /**
1515
         * When a server is not fully featured and it only can serve constant map
1516
         * sizes this value must be set. It expresses the size in pixels (width, height)
1517
         * that the map will be requested.
1518
         * @param Dimension sz
1519
         */
1520
        public void setFixedSize(Dimension sz) {
1521
                fixedSize = sz;
1522
        }
1523

    
1524
        /**
1525
         * Tells whether if this layer must deal with the server with the constant-size
1526
         * limitations or not.
1527
         * @return boolean.
1528
         */
1529
        private boolean isSizeFixed() {
1530
                return fixedSize != null && fixedSize.getWidth() > 0 && fixedSize.getHeight() > 0;
1531
        }
1532

    
1533
        /**
1534
         * If it is true, this layer accepts GetFeatureInfo operations. This WMS operations
1535
         * maps to FMap's infoByPoint(p) operation.
1536
         * @param b
1537
         */
1538
        public void setQueryable(boolean b) {
1539
                queryable = b;
1540
        }
1541

    
1542
        /**
1543
         * Creates the part of a OGC's MapContext document that would describe this
1544
         * layer(s).
1545
         * @param version, The desired version of the resulting document. (1.1.0)
1546
         * @return String containing the xml.
1547
         * @throws UnsupportedVersionException
1548
         */
1549
        public String toMapContext(String mapContextVersion) {
1550
                XmlBuilder xml = new XmlBuilder();
1551
                FMapWMSDriver drv;
1552
                try {
1553
                        drv = getDriver();
1554
                } catch (Exception e) {
1555
                        return xml.toString();
1556
                }
1557
                String[] layerNames = getLayerQuery().split(",");
1558
                String[] styleNames = (String[]) styles.toArray(new String[0]);
1559
                for (int i = 0; i < layerNames.length; i++) {
1560
                        WMSLayerNode layer = drv.getLayer(layerNames[i]);
1561
                        HashMap xmlAttrs = new HashMap();
1562

    
1563
                        // <Layer>
1564
                        xmlAttrs.put(WebMapContextTags.HIDDEN, !isVisible()+"");
1565
                        xmlAttrs.put(WebMapContextTags.QUERYABLE, queryable+"");
1566
                        xml.openTag(WebMapContextTags.LAYER, xmlAttrs);
1567
                        xmlAttrs.clear();
1568
                        if (mapContextVersion.equals("1.1.0") || mapContextVersion.equals("1.0.0")) {
1569
                                // <Server>
1570
                                xmlAttrs.put(WebMapContextTags.SERVICE, WebMapContextTags.WMS);
1571
                                xmlAttrs.put(WebMapContextTags.VERSION, drv.getVersion());
1572
                                xmlAttrs.put(WebMapContextTags.SERVER_TITLE, drv.getServiceTitle());
1573
                                xml.openTag(WebMapContextTags.SERVER, xmlAttrs);
1574
                                xmlAttrs.clear();
1575

    
1576
                                        // <OnlineResource>
1577
                                        xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1578
                                        xmlAttrs.put(WebMapContextTags.XLINK_HREF, getHost().toString());
1579
                                        xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1580
                                        xmlAttrs.clear();
1581
                                        // </OnlineResource>
1582

    
1583
                                xml.closeTag();
1584
                                // </Server>
1585

    
1586
                                // <Name>
1587
                                xml.writeTag(WebMapContextTags.NAME, layer.getName().trim());
1588
                                // </Name>
1589

    
1590
                                // <Title>
1591
                                xml.writeTag(WebMapContextTags.TITLE, layer.getTitle().trim());
1592
                                //?xml.writeTag(WebMapContextTags.TITLE, getName().trim());
1593
                                // </Title>
1594

    
1595
                                // <Abstract>
1596
                                if (layer.getAbstract() != null)
1597
                                        xml.writeTag(WebMapContextTags.ABSTRACT, layer.getAbstract());
1598
                                // </Abstract>
1599

    
1600
                                // <SRS> (a list of available SRS for the enclosing layer)
1601
                                String[] strings = (String[]) layer.getAllSrs().toArray(new String[0]);
1602
                                String mySRS = strings[0];
1603
                                for (int j = 1; j < strings.length; j++) {
1604
                                        mySRS += ","+strings[j];
1605
                                }
1606
                                xml.writeTag(WebMapContextTags.SRS, mySRS);
1607
                                // </SRS>
1608

    
1609
                                // <FormatList>
1610
                                xml.openTag(WebMapContextTags.FORMAT_LIST);
1611
                                        strings = (String[]) drv.getFormats().toArray(new String[0]);
1612
                                        for (int j = 0; j < strings.length; j++) {
1613
                    // <Format>
1614
                                                String str = strings[j].trim();
1615
                                                if (str.equals(getFormat()))
1616
                                                        xml.writeTag(WebMapContextTags.FORMAT, str, WebMapContextTags.CURRENT, "1");
1617
                                                else
1618
                                                        xml.writeTag(WebMapContextTags.FORMAT, str);
1619
                    // </Format>
1620
                                        }
1621
                                xml.closeTag();
1622
                                // </FormatList>
1623

    
1624
                                // <StyleList>
1625
                                xml.openTag(WebMapContextTags.STYLE_LIST);
1626

    
1627
                                        if (layer.getStyles().size()>0) {
1628
                                                for (int j = 0; j < layer.getStyles().size(); j++) {
1629
                                                        // <Style>
1630
                                                        FMapWMSStyle st = (FMapWMSStyle) layer.getStyles().get(j);
1631
                                                        if (st.name.equals(styleNames[i]))
1632
                                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1633
                                                        xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1634
                                                        xmlAttrs.clear();
1635

    
1636
                                                                // <Name>
1637
                                                                xml.writeTag(WebMapContextTags.NAME, st.name);
1638
                                                                // </Name>
1639

    
1640
                                                                // <Title>
1641
                                                                xml.writeTag(WebMapContextTags.TITLE, st.title);
1642
                                                                // </Title>
1643

    
1644
                                                                // <LegendURL width="180" format="image/gif" height="50">
1645
                                                                        // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1646
                                                                        // </OnlineResource>
1647
                                                                // </LegendURL>
1648
                                                        xml.closeTag();
1649
                                                        // </Style>
1650

    
1651
                                                }
1652

    
1653
                                        } else {
1654
                                                // Create fake style (for compatibility issues)
1655
                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1656
                                                // <Style>
1657
                                                xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1658
                                                        xmlAttrs.clear();
1659
                                                        // <Name>
1660
                                                        xml.writeTag(WebMapContextTags.NAME, "default");
1661
                                                        // </Name>
1662

    
1663
                                                        // <Title>
1664
                                                        xml.writeTag(WebMapContextTags.TITLE, "default");
1665
                                                        // </Title>
1666

    
1667
//                                                        // <LegendURL width="180" format="image/gif" height="50">
1668
//                                                        xmlAttrs.put(WebMapContextTags.WIDTH, "0");
1669
//                                                        xmlAttrs.put(WebMapContextTags.HEIGHT, "0");
1670
//                                                        xmlAttrs.put(WebMapContextTags.FORMAT.toLowerCase(), "image/gif");
1671
//                                                        xml.openTag(WebMapContextTags.LEGEND_URL, xmlAttrs);
1672
//                                                        xmlAttrs.clear();
1673
//                                                                // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1674
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1675
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_HREF, "http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif");
1676
//                                                                xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1677
//                                                                // </OnlineResource>
1678
//                                                    // </LegendURL>
1679
//                                                        xml.closeTag();
1680
                                                // </Style>
1681
                                                xml.closeTag();
1682
                                        }
1683
                                // </StyleList>
1684
                                xml.closeTag();
1685
                                if (mapContextVersion.compareTo("1.0.0") > 0) {
1686
                                // <DimensionList>
1687
                                        xml.openTag(WebMapContextTags.DIMENSION_LIST);
1688
                                        // <Dimension>
1689
                                        // </Dimension>
1690
                                        xml.closeTag();
1691
                                // </DimensionList>
1692
                                }
1693
                        } else {
1694
                                xml.writeTag("ERROR", PluginServices.getText(this, "unsupported_map_context_version"));
1695
                        }
1696
                        // </Layer>
1697
                        xml.closeTag();
1698
                }
1699
                return xml.getXML();
1700
        }
1701

    
1702
        public ImageIcon getTocImageIcon() {
1703
                return new ImageIcon(PluginServices.getPluginServices("com.iver.cit.gvsig.wms").getClassLoader().getResource("images/icoLayer.png"));
1704
        }
1705

    
1706
        /*
1707
         *  (non-Javadoc)
1708
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1709
         */
1710
        public int[] getTileSize() {
1711
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1712
                return size;
1713
        }
1714

    
1715
        /*
1716
         *  (non-Javadoc)
1717
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1718
         */
1719
        public boolean isTiled() {
1720
                return mustTileDraw;
1721
        }
1722

    
1723
        public Image getImageLegend() {
1724
                try {
1725
                        File legend = getDriver().getLegendGraphic(layerQuery, null);
1726
                        Image img = null;
1727
                        img = ImageIO.read(legend);
1728
                        return img;
1729
                }catch(Exception e){
1730
                        e.printStackTrace();
1731
                        return null;
1732
                }
1733
        }
1734

    
1735

    
1736
}