Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extWMS / src / com / iver / cit / gvsig / fmap / layers / FLyrWMS.java @ 6818

History | View | Annotate | Download (45.6 KB)

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

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

    
67
import javax.swing.ImageIcon;
68
import javax.swing.JOptionPane;
69

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

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

    
101

    
102

    
103
/**
104
* FMap's WMS Layer class.
105
*
106
* @author Jaume Dominguez Faus
107
*                   Nacho Brodin
108
*
109
*/
110
public class FLyrWMS extends FLyrDefault implements InfoByPoint, RasterOperations {
111
        private boolean                                         isPrinting = false;
112
        private boolean                                         mustTileDraw = true;
113
        private boolean                                         mustTilePrint = true;
114
        private final int                                         maxTileDrawWidth = 1023;
115
        private final int                                         maxTileDrawHeight = 1023;
116
        private final int                                         maxTilePrintWidth = 1023;
117
        private final int                                         maxTilePrintHeight = 1023;
118

    
119
    public URL                                                         host;
120
    public String                                                 m_Format;
121

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

    
147

    
148
        private class MyCancellable implements ICancellable
149
        {
150

    
151
                private Cancellable original;
152
                public MyCancellable(Cancellable cancelOriginal)
153
                {
154
                        this.original = cancelOriginal;
155
                }
156
                public boolean isCanceled() {
157
                        return original.isCanceled();
158
                }
159

    
160
        }
161

    
162
        public FLyrWMS(){
163
                super();
164
        }
165

    
166
        public FLyrWMS(Map args) throws DriverIOException{
167
                FMapWMSDriver drv = null;
168
                String host = (String)args.get("host");
169
                String sLayer = (String)args.get("layer");
170
                Rectangle2D fullExtent = (Rectangle2D)args.get("FullExtent");
171
                String sSRS = (String)args.get("SRS");
172
                String sFormat = (String)args.get("Format");
173
                String[] sLayers = sLayer.split(",");
174

    
175
                try {
176
                        this.setHost(new URL(host));
177
                } catch (MalformedURLException e) {
178
                        //e.printStackTrace();
179
                        throw new DriverIOException("Malformed host URL, '" + host + "' (" + e.toString() + ").");
180
                }
181
                try {
182
                        drv = this.getDriver();
183
                } catch (Exception e) {
184
                        // e.printStackTrace();
185
                        throw new DriverIOException("Can't get driver to host '" + host + "' (" + e.toString() + ").");
186
                }
187
                if( sFormat == null || sSRS == null || fullExtent == null ) {
188
                        if (!drv.connect(null))
189
                                throw new DriverIOException("Can't connect to host '" + host + "'.");
190

    
191
                        WMSLayerNode wmsNode = drv.getLayer(sLayer);
192

    
193
                        if (wmsNode == null){
194
                                throw new DriverIOException("The server '" + host + "' doesn't has the layer '" + sLayer + "'.");
195
                        }
196
                        if( sFormat == null ) {
197
                                sFormat = this.getGreatFormat(drv.getFormats());
198
                        }
199
                     if( sSRS == null ) {
200
                             sSRS = (String)wmsNode.getAllSrs().get(0);
201
                     }
202
                        if( fullExtent == null ) {
203
                                fullExtent = drv.getLayersExtent(sLayers,(String)wmsNode.getAllSrs().get(0));
204
                        }
205
                }
206

    
207

    
208
                this.setFullExtent(fullExtent);
209
                this.setFormat(sFormat);
210
                this.setLayerQuery(sLayer);
211
                this.setInfoLayerQuery("");
212
                this.setSRS(sSRS);
213
                this.setName(sLayer);
214
        }
215

    
216
        /**
217
         * It choose the best format to load different maps if the server
218
         * supports it. This format could be png, because it supports
219
         * transparency.
220
         * @param formats
221
         * Arraywith all the formats supported by the server
222
         * @return
223
         */
224
        private String getGreatFormat(Vector formats){
225
            for (int i=0 ; i<formats.size() ; i++){
226
                String format = (String) formats.get(i);
227
                    if (format.equals("image/jpg")){
228
                    return format;
229
                    }
230
                    if (format.equals("image/jpeg")){
231
                    return format;
232
                    }
233
            }
234

    
235
            return (String)formats.get(0);
236
        }
237

    
238
        /**
239
         * Clase que contiene los datos de visualizaci?n de WMS.
240
         * @author Nacho Brodin (brodin_ign@gva.es)
241
         */
242
        private class VisualStatusWMS{
243
                /**
244
                 * Ancho y alto de la imagen o del conjunto de tiles si los tiene. Coincide con
245
                 * el ancho y alto del viewPort
246
                 */
247
                private        int                                                        width = 0, height = 0;
248
                private double                                                minX = 0D, minY = 0D, maxX = 0D, maxY = 0D;
249
                private int                                                 bandCount = 0;
250
                private int                                                        dataType = DataBuffer.TYPE_UNDEFINED;
251
        }
252

    
253

    
254
        /**
255
         * Devuelve el XMLEntity con la informaci?n necesaria para reproducir la
256
         * capa.
257
         *
258
         * @return XMLEntity.
259
         * @throws XMLException
260
         */
261
        public XMLEntity getXMLEntity() throws XMLException {
262
                XMLEntity xml = super.getXMLEntity();
263

    
264
                // Full extent
265
                xml.putProperty("fullExtent", StringUtilities.rect2String(fullExtent));
266

    
267
                // Host
268
                xml.putProperty("host", host.toExternalForm());
269

    
270
                // Part of the query that is not the host, or the
271
                // layer names, or other not listed bellow
272
                xml.putProperty("infoLayerQuery", infoLayerQuery);
273

    
274
                // Part of the query containing the layer names
275
                xml.putProperty("layerQuery", layerQuery);
276

    
277
                // Format
278
                xml.putProperty("format", m_Format);
279

    
280
                // SRS
281
                xml.putProperty("srs", m_SRS);
282
                if (status!=null)
283
                        status.getXMLEntity(xml, true, this);
284
                else{
285
                        status = new StatusLayerRaster();
286
                        status.getXMLEntity(xml, true, this);
287
                }
288

    
289
        // Transparency
290
        xml.putProperty("wms_transparency", wmsTransparency);
291

    
292
        // Styles
293
        if (styles!=null){
294
            String stylePr = "";
295
            for (int i = 0; i < styles.size(); i++) {
296
                stylePr += (String) styles.get(i);
297
                if (i<styles.size()-1)
298
                    stylePr += ",";
299
            }
300
            if (stylePr.endsWith(","))
301
                    stylePr += " ";
302
            xml.putProperty("styles", stylePr);
303
        }
304

    
305
        // Dimensions
306
        if (dimensions!=null){
307
            String dim = "";
308
            for (int i = 0; i < dimensions.size(); i++) {
309
                dim += (String) dimensions.get(i);
310
                if (i<dimensions.size()-1)
311
                    dim += ",";
312
            }
313
            if (dim.endsWith(","))
314
                    dim += " ";
315
            xml.putProperty("dimensions", dim);
316
        }
317

    
318
        // OnlineResources
319
        Iterator it = onlineResources.keySet().iterator();
320
        String strOnlines = "";
321
        while (it.hasNext()) {
322
                String key = (String) it.next();
323
                String value = (String) onlineResources.get(key);
324
                strOnlines = key+"~##SEP2##~"+value;
325
                if (it.hasNext())
326
                        strOnlines += "~##SEP1##~";
327
        }
328
        xml.putProperty("onlineResources", strOnlines);
329

    
330
        // Queryable
331
        xml.putProperty("queryable", queryable);
332

    
333
        // fixedSize
334
        if (isSizeFixed()) {
335
                xml.putProperty("fixedSize", true);
336
                xml.putProperty("fixedWidth", fixedSize.width);
337
                xml.putProperty("fixedHeight", fixedSize.height);
338
        }
339
        return xml;
340
        }
341

    
342
        /**
343
         * A partir del XMLEntity reproduce la capa.
344
         *
345
         * @param xml XMLEntity
346
         *
347
         * @throws XMLException
348
         * @throws DriverException
349
         * @throws DriverIOException
350
         */
351
        public void setXMLEntity03(XMLEntity xml)
352
                throws XMLException {
353
                super.setXMLEntity(xml);
354
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty(
355
                                        "fullExtent"));
356

    
357
                try {
358
                        host = new URL(xml.getStringProperty("host"));
359
                } catch (MalformedURLException e) {
360
                        throw new XMLException(e);
361
                }
362

    
363
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
364
                layerQuery = xml.getStringProperty("layerQuery");
365
                m_Format = xml.getStringProperty("format");
366
                m_SRS = xml.getStringProperty("srs");
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 setXMLEntity(XMLEntity xml)
379
                throws XMLException {
380
                super.setXMLEntity(xml);
381
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty(
382
                                        "fullExtent"));
383

    
384
                // Host
385
                try {
386
                        host = new URL(xml.getStringProperty("host"));
387
                } catch (MalformedURLException e) {
388
                        throw new XMLException(e);
389
                }
390

    
391
                // Part of the query that is not the host, or the
392
                // layer names, or other not listed bellow
393
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
394

    
395
                // Part of the query containing the layer names
396
                layerQuery = xml.getStringProperty("layerQuery");
397

    
398
                // Format
399
                m_Format = xml.getStringProperty("format");
400

    
401
                // SRS
402
                m_SRS = xml.getStringProperty("srs");
403

    
404
                String claseStr = StatusLayerRaster.defaultClass;
405
                if (xml.contains("raster.class")) {
406
                        claseStr = xml.getStringProperty("raster.class");
407
                }
408

    
409
                // Transparency
410
        if (xml.contains("wms_transparency"))
411
            wmsTransparency = xml.getBooleanProperty("wms_transparency");
412

    
413
        // Styles
414
        if (xml.contains("styles")){
415
            styles = new Vector();
416
            String[] stl = xml.getStringProperty("styles").split(",");
417

    
418
            for (int i = 0; i < stl.length; i++) {
419
                    if (stl[i].equals(" "))
420
                            stl[i]="";
421
                styles.add(stl[i]);
422
            }
423
        }
424

    
425
        // Dimensions
426
        if (xml.contains("dimensions")){
427
            dimensions = new Vector();
428
            String[] dims = xml.getStringProperty("dimensions").split(",");
429
            for (int i = 0; i < dims.length; i++){
430
                    if (dims[i].equals(" "))
431
                            dims[i]="";
432

    
433
                dimensions.add(dims[i]);
434
            }
435
        }
436

    
437
        // OnlineResources
438
        if (xml.contains("onlineResources")) {
439
                String[] operations = xml.getStringProperty("onlineResources").split("~##SEP1##~");
440
                for (int i = 0; i < operations.length; i++) {
441
                                String[] resources = operations[i].split("~##SEP2##~");
442
                                if (resources.length==2 && resources[1]!="")
443
                                        onlineResources.put(resources[0], resources[1]);
444
                        }
445
        }
446

    
447
        // Queryable
448
        queryable = true; // let's assume that the layer is queryable by default
449
        if (xml.contains("queryable"))
450
                queryable = xml.getBooleanProperty("queryable");
451

    
452
        // fixedSize
453
        if (xml.contains("fixedSize")) {
454
                fixedSize = new Dimension(xml.getIntProperty("fixedWidth"),
455
                                                  xml.getIntProperty("fixedHeight"));
456
        }
457

    
458
                if(status!=null)
459
                        status.setXMLEntity(xml, this);
460
                else{
461
                        if(claseStr!=null && !claseStr.equals("")){
462
                                try{
463
                                        Class clase = Class.forName(claseStr);
464
                                        Constructor constr = clase.getConstructor(null);
465
                                        status = (StatusRasterInterface)constr.newInstance(null);
466
                                        if(status!=null)
467
                                                status.setXMLEntity(xml, this);
468
                                }catch(ClassNotFoundException exc){
469
                                        exc.printStackTrace();
470
                                }catch(InstantiationException exc){
471
                                        exc.printStackTrace();
472
                                }catch(IllegalAccessException exc){
473
                                        exc.printStackTrace();
474
                                }catch(NoSuchMethodException exc){
475
                                        exc.printStackTrace();
476
                                }catch(InvocationTargetException exc){
477
                                        exc.printStackTrace();
478
                                }
479
                        }
480
                }
481
                firstLoad = true;
482
        }
483

    
484
        /**
485
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(com.iver.cit.gvsig.fmap.operations.QueriedPoint)
486
         */
487
        public XMLItem[] getInfo(Point p, double tolerance) throws DriverException {
488
                XMLItem[] item =  new XMLItem[1];
489
                try {
490
                        if (queryable)
491
                        {
492
                                //TODO
493
                                // check if there are layers which are not queryable
494
                                ViewPort viewPort = getFMap().getViewPort();
495

    
496
                                Point tiledPoint = new Point((int) p.getX() % maxTilePrintWidth, (int) p.getY() % maxTilePrintHeight);
497
                                Rectangle rect = new Rectangle(0, 0, viewPort.getImageWidth() - 1, viewPort.getImageHeight() - 1);
498
                                Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, rect);
499
                                tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
500
                                int nCols = tiles.getNumCols();
501

    
502
                                int col = (int) p.getX() / maxTilePrintWidth;
503
                                int row = (int) p.getY() / maxTilePrintHeight;
504
                                int tileIndex = (row*nCols) + col;
505

    
506
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileIndex);
507
                                wmsStatus.setExtent(vp.getExtent());
508
                                wmsStatus.setHeight(vp.getImageHeight());
509
                                wmsStatus.setWidth(vp.getImageWidth());
510
                                wmsStatus.setOnlineResource((String) onlineResources.get("GetFeatureInfo"));
511
                                item[0] = new StringXMLItem(new String(getDriver()
512
                                                .getFeatureInfo(wmsStatus, (int) tiledPoint.getX(), (int) tiledPoint.getY(), Integer.MAX_VALUE)),this);
513
                                return item;
514
                        }
515
                        else
516
                        {
517
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
518
                                                PluginServices.getText(this, "wms_not_queryable"));
519
                                item[0] =  new StringXMLItem("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><info></info>",this);
520
                                return item;
521
                        }
522
                } catch (WMSException  e) {
523
                        item[0] = new StringXMLItem("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><exception>" +
524
                        e.getMessage() + "</exception>", this);
525
                        return item;
526
                } catch (ValidationException e) {
527
                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
528
                } catch (UnsupportedVersionException e) {
529
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
530
                } catch (IOException e) {
531
                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
532
                } catch (NoninvertibleTransformException e) {
533
                        NotificationManager.addError("NotinvertibleTransform", e);
534
                }
535
                return null;
536
        }
537

    
538
        /**
539
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent()
540
         */
541
        public Rectangle2D getFullExtent() {
542
                return fullExtent;
543
        }
544

    
545
        /**
546
         *
547
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#draw(java.awt.image.BufferedImage,
548
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
549
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
550
         */
551
        private int callCount; // mess code, represents the amount of times the methods drawFixedSize or drawTile where tried for an extent
552
        private static final int MAX_RETRY_TIMES = 5; // mess code, represents the max amount of retries allowed.
553
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
554
                        Cancellable cancel,double scale) throws DriverException {
555
                callCount = 0; // mess code
556
                if (isWithinScale(scale)){
557
                        Point2D p = viewPort.getOffset();
558
                        // p will be (0, 0) when drawing a view or other when painting onto
559
                        // the Layout.
560
                        visualStatus.width =  viewPort.getImageWidth();
561
                        visualStatus.height =  viewPort.getImageHeight();
562
                        visualStatus.minX = viewPort.getAdjustedExtent().getMinX();
563
                        visualStatus.minY = viewPort.getAdjustedExtent().getMinY();
564
                        visualStatus.maxX = viewPort.getAdjustedExtent().getMaxX();
565
                        visualStatus.maxY = viewPort.getAdjustedExtent().getMaxY();
566

    
567

    
568
                        if (isSizeFixed()) {
569
                                // This condition handles those situations in which the server can
570
                                // only give static extent and resolution maps despite we need
571
                                // a specific BBOX and pixel WIDTH and HEIGHT
572
                                drawFixedSize(g, viewPort, cancel);
573

    
574
                        } else {
575
                                if(mustTileDraw){
576
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), viewPort.getImageWidth(), viewPort.getImageHeight());
577
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
578
                                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
579
                                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
580
                                                // drawing part
581
                                                try {
582
                                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
583
                                                        drawTile(g, vp, cancel);
584
                                                } catch (NoninvertibleTransformException e) {
585
                                                        e.printStackTrace();
586
                                                }
587
                                        }
588
                                }else
589
                                        drawTile(g, viewPort, cancel);
590
                        }
591
                }
592
//                Runtime r = Runtime.getRuntime();
593
//                long mem = r.totalMemory() - r.freeMemory();
594
//                System.err.println("Memoria total: " + (mem / 1024) +"KB");
595
        }
596

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

    
602

    
603
                // This is the extent that will be requested
604
                Rectangle2D bBox = getFullExtent();
605
                MyCancellable c = new MyCancellable(cancel);
606

    
607
                try {
608
                        wmsStatus.setExtent( bBox );
609
                        wmsStatus.setFormat( m_Format );
610
                        wmsStatus.setHeight( fixedSize.height );
611
                        wmsStatus.setWidth( fixedSize.width );
612
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
613
                        wmsStatus.setSrs(m_SRS);
614
                        wmsStatus.setStyles(styles);
615
                        wmsStatus.setDimensions(dimensions);
616
                        wmsStatus.setTransparency(wmsTransparency);
617
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
618
                        File f = getDriver().getMap(wmsStatus, c);
619
                        if (f == null)
620
                                return;
621
                        String nameWorldFile = f.getPath() + getExtensionWorldFile();
622
                        com.iver.andami.Utilities.createTemp(nameWorldFile, this.getDataWorldFile(bBox, fixedSize));
623

    
624
                        if(status!=null && firstLoad){
625
                                status.applyStatus(this);
626
                                firstLoad = false;
627
                        }
628

    
629
                        // And finally, obtain the extent intersecting the view and the BBox
630
                        // to draw to.
631
                        Rectangle2D extent = new Rectangle2D.Double();
632
                        Rectangle2D.intersect(vp.getAdjustedExtent(), bBox, extent);
633

    
634
                        ViewPortData vpData = new ViewPortData(
635
                                vp.getProjection(), new Extent(extent), fixedSize );
636
                        vpData.setMat(vp.getAffineTransform());
637

    
638
                        rasterProcess(g, vpData, f);
639

    
640
                } catch (ValidationException e) {
641
                        if (!c.isCanceled())
642
                                throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
643
                } catch (UnsupportedVersionException e) {
644
                        if (!c.isCanceled())
645
                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
646
                } catch (IOException e) {
647
                        if (!c.isCanceled())
648
                                if (callCount<MAX_RETRY_TIMES) { // mess code
649
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
650
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
651
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
652
                                        drawFixedSize(g, vp, cancel); // mess code
653
                                } // mess code
654
                                if (callCount == 1) { // mess code
655
                                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
656
                                } // mess code
657
                } catch (WMSException e) {
658
                        if (!c.isCanceled()) {
659
                                if (callCount<MAX_RETRY_TIMES) { // mess code
660
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null); // mess code
661
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error // mess code
662
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0) // mess code
663
                                        drawFixedSize(g, vp, cancel); // mess code
664
                                } // mess code
665
                                if (callCount == 1) { // mess code
666
                                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
667
                                        if (!isPrinting)
668
                                                this.setVisible(false);
669

    
670
                                } // mess code
671
                        }
672
                }
673
                callCount--; // mess code
674
        }
675

    
676
        /**
677
         * This is the method used to draw a tile in a WMS mosaic layer.
678
         */
679
        private void drawTile(Graphics2D g, ViewPort vp, Cancellable cancel) throws DriverException {
680
                callCount++;
681
                // Compute the query geometry
682
                // 1. Check if it is within borders
683
                Rectangle2D extent = getFullExtent();
684
        if ((vp.getAdjustedExtent().getMinX() > extent.getMaxX()) ||
685
                (vp.getAdjustedExtent().getMinY() > extent.getMaxY()) ||
686
                (vp.getAdjustedExtent().getMaxX() < extent.getMinX()) ||
687
                (vp.getAdjustedExtent().getMaxY() < extent.getMinY())) {
688
            return;
689
        }
690

    
691
        // 2. Compute extent to be requested.
692
        Rectangle2D bBox = new Rectangle2D.Double();
693
        Rectangle2D.intersect(vp.getExtent(), extent, bBox);
694

    
695
        // 3. Compute size in pixels
696
        double scalex = vp.getAffineTransform().getScaleX();
697
        double scaley = vp.getAffineTransform().getScaleY();
698
        int wImg = (int) Math.ceil(Math.abs(bBox.getWidth() * scalex) + 1);
699
        int hImg = (int) Math.ceil(Math.abs(bBox.getHeight() * scaley) + 1);
700

    
701
        Dimension sz = new Dimension(wImg, hImg);
702

    
703
        if ((wImg <= 0) || (hImg <= 0)) {
704
            return;
705
        }
706
        MyCancellable c = new MyCancellable(cancel);
707

    
708
                try {
709
                        wImg = vp.getImageWidth();
710
                        hImg = vp.getImageHeight();
711
                        sz = new Dimension(vp.getImageWidth(), vp.getImageHeight());
712
                        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
713

    
714
                        wmsStatus.setExtent( bBox );
715
                        wmsStatus.setFormat(m_Format);
716
                        wmsStatus.setHeight( hImg );
717
                        wmsStatus.setWidth( wImg );
718
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
719
                        wmsStatus.setSrs(m_SRS);
720
                        wmsStatus.setStyles(styles);
721
                        wmsStatus.setDimensions(dimensions);
722
                        wmsStatus.setTransparency(wmsTransparency);
723
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
724

    
725
                        File f = getDriver().getMap(wmsStatus, c);
726
                        if (f == null)
727
                                return;
728
                        String nameWordFile = f.getPath() + getExtensionWorldFile();
729
                        com.iver.andami.Utilities.createTemp(nameWordFile, this.getDataWorldFile(bBox, sz));
730

    
731
                        if(status!=null && firstLoad){
732
                                status.applyStatus(this);
733
                                firstLoad = false;
734
                        }
735
                        ViewPortData vpData = new ViewPortData(
736
                                vp.getProjection(), new Extent(bBox), sz );
737
                        vpData.setMat(vp.getAffineTransform());
738

    
739
                        rasterProcess(g, vpData, f);
740

    
741
                } catch (ValidationException e) {
742
                        if (!c.isCanceled())
743
                                throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
744
                } catch (UnsupportedVersionException e) {
745
                        if (!c.isCanceled())
746
                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
747
                } catch (IOException e) {
748
                        if (!c.isCanceled())
749
                                if (callCount<MAX_RETRY_TIMES) {
750
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null);
751
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error
752
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0)
753
                                        drawFixedSize(g, vp, cancel);
754
                                }
755
                                if (callCount == 1) {
756
                                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
757
                                }
758
                } catch (WMSException e) {
759
                        if (!c.isCanceled()) {
760
                                if (callCount<MAX_RETRY_TIMES) {
761
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawTile() ] Failed in trying " + callCount + "/" + MAX_RETRY_TIMES +" \n", null);
762
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error
763
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0)
764
                                        drawTile(g, vp, cancel);
765
                                }
766
                                if (callCount == 1) {
767
                                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
768
                                        if (!isPrinting)
769
                                                this.setVisible(false);
770
                                }
771
                        }
772
                }
773
                callCount--;
774
        }
775

    
776
        /**
777
         * Obtiene la extensi?n del fichero de georreferenciaci?n
778
         * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
779
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
780
         */
781
        private String getExtensionWorldFile(){
782
                String extWorldFile = ".wld";
783
            if(m_Format.equals("image/tif") || m_Format.equals("image/tiff"))
784
                    extWorldFile = ".tfw";
785
            if(m_Format.equals("image/jpeg"))
786
                    extWorldFile = ".jpgw";
787
            return extWorldFile;
788
        }
789

    
790
        /**
791
         * Calcula el contenido del fichero de georreferenciaci?n de una imagen.
792
         * @param bBox Tama?o y posici?n de la imagen (en coordenadas de usuario)
793
         * @param sz Tama?o de la imagen en pixeles.
794
         * @return el 'WorldFile', como String.
795
         * @throws IOException
796
         */
797
        public String getDataWorldFile(Rectangle2D bBox, Dimension sz) throws IOException {
798
                StringBuffer data = new StringBuffer();
799
            data.append((bBox.getMaxX() - bBox.getMinX())/(sz.getWidth() - 1)+"\n");
800
            data.append("0.0\n");
801
            data.append("0.0\n");
802
            data.append((bBox.getMaxY() - bBox.getMinY())/(sz.getHeight() - 1)+"\n");
803
            data.append(""+bBox.getMinX()+"\n");
804
            data.append(""+bBox.getMinY()+"\n");
805
            return data.toString();
806
        }
807

    
808
        /**
809
         * Dibuja una imagen usando PxRaster
810
         * @param g        Graphics2D en el que hay que dibujar.
811
         * @param vpData Par?metros de visualizaci?n
812
         * @param file La imagen en cuesti?n.
813
         */
814
        private void rasterProcess(Graphics2D g, ViewPortData vpData, File file) {
815

    
816
                //Creamos el PxRaster
817
                rasterFile = new GdalFile(vpData.getProjection(), file.getAbsolutePath());
818
                raster = new PxRaster(rasterFile, null, rasterFile.getExtent());
819

    
820
                //Recuperamos la pila de filtros si ya hubiese sido cargado antes
821
                if(this.filterStack!=null)
822
                        raster.filterStack = this.filterStack;
823

    
824
                raster.setTransparency(false);
825

    
826
                //Asignamos transparencia y orden de bandas
827
                if(this.transparency==-1 && !firstLoad);
828
                else
829
                        raster.setTransparency(this.transparency);
830

    
831
                raster.setBand(GeoRasterFile.RED_BAND,rband);
832
                raster.setBand(GeoRasterFile.GREEN_BAND, gband);
833
                raster.setBand(GeoRasterFile.BLUE_BAND, bband);
834

    
835
                //Despues del primer pxRaster asignamos el stackManager guardado para los siguientes.
836
                //Con esto conseguimos asignar los cambios que se hayan producido desde el cuadro de
837
                //propiedades cuando creamos un nuevo pxRaster
838
                if(this.stackManager != null)
839
                        raster.setStackManager(this.stackManager);
840

    
841
                if(visualStatus != null){
842
                        visualStatus.bandCount = raster.getBandCount();
843
                        visualStatus.dataType = raster.getDataType();
844
                }
845

    
846
                raster.draw(g, vpData);
847

    
848
                //En el primer pxRaster de una imagen obtenemos el Stack Manager para poder modificarlo
849
                //si queremos desde las propiedades
850

    
851
                if(this.stackManager == null)
852
                        this.stackManager = raster.getStackManager();
853

    
854
                if(this.filterStack == null)
855
                        this.filterStack = raster.filterStack;
856

    
857
                //rasterFile.close();
858
        }
859

    
860
        /**
861
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D,
862
         *                 com.iver.cit.gvsig.fmap.ViewPort,
863
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
864
         */
865
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale)
866
                throws DriverException {
867
                if (isVisible() && isWithinScale(scale)){
868
                isPrinting = true;
869
                if (!mustTilePrint) {
870
                        draw(null, g, viewPort, cancel,scale);
871
                } else {
872
                // Para no pedir imagenes demasiado grandes, vamos
873
                // a hacer lo mismo que hace EcwFile: chunkear.
874
                // Llamamos a drawView con cuadraditos m?s peque?os
875
                // del BufferedImage ni caso, cuando se imprime viene con null
876

    
877
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipRect());
878
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
879
                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
880
                            // Parte que dibuja
881
                            try {
882
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
883
                                drawTile(g, vp, cancel);
884
                                } catch (NoninvertibleTransformException e) {
885
                                        e.printStackTrace();
886
                                }
887
                }
888
                }
889
            isPrinting = false;
890
                }
891
        }
892

    
893
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale)
894
                throws DriverException {
895
                draw(null, g, viewPort, cancel,scale);
896
        }
897

    
898
        /**
899
         * Devuelve el FMapWMSDriver.
900
         *
901
         * @return FMapWMSDriver
902
         *
903
         * @throws IllegalStateException
904
         * @throws ValidationException
905
         * @throws UnsupportedVersionException
906
         * @throws IOException
907
         */
908
        private FMapWMSDriver getDriver()
909
                throws IllegalStateException, ValidationException,
910
                        UnsupportedVersionException, IOException {
911
                return FMapWMSDriverFactory.getFMapDriverForURL(host);
912
        }
913

    
914
        /**
915
         * Devuelve el FMapWMSDriver.
916
         *
917
         * @return FMapWMSDriver
918
         *
919
         * @throws IllegalStateException
920
         * @throws ValidationException
921
         * @throws UnsupportedVersionException
922
         * @throws IOException
923
         */
924
        public void setDriver(FMapWMSDriver drv) {
925
                wms = drv;
926
        }
927

    
928
        /**
929
         * Devuelve el URL.
930
         *
931
         * @return URL.
932
         */
933
        public URL getHost() {
934
                return host;
935
        }
936

    
937
        /**
938
         * Inserta el URL.
939
         *
940
         * @param host URL.
941
         */
942
        public void setHost(URL host) {
943
                this.host = host;
944
        }
945

    
946
        /**
947
         * Devuelve la informaci?n de la consulta.
948
         *
949
         * @return String.
950
         */
951
        public String getInfoLayerQuery() {
952
                return infoLayerQuery;
953
        }
954

    
955
        /**
956
         * Inserta la informaci?n de la consulta.
957
         *
958
         * @param infoLayerQuery String.
959
         */
960
        public void setInfoLayerQuery(String infoLayerQuery) {
961
                this.infoLayerQuery = infoLayerQuery;
962
        }
963

    
964
        /**
965
         * Devuelve la consulta.
966
         *
967
         * @return String.
968
         */
969
        public String getLayerQuery() {
970
                return layerQuery;
971
        }
972

    
973
        /**
974
         * Inserta la consulta.
975
         *
976
         * @param layerQuery consulta.
977
         */
978
        public void setLayerQuery(String layerQuery) {
979
                this.layerQuery = layerQuery;
980
        }
981

    
982
        /**
983
         * Devuelve el formato.
984
         *
985
         * @return Formato.
986
         */
987
        public String getFormat() {
988
                return m_Format;
989
        }
990

    
991
        /**
992
         * Inserta el formato.
993
         *
994
         * @param format Formato.
995
         */
996
        public void setFormat(String format) {
997
                m_Format = format;
998
        }
999

    
1000
        /**
1001
         * Devuelve el SRS.
1002
         *
1003
         * @return SRS.
1004
         */
1005
        public String getSRS() {
1006
                return m_SRS;
1007
        }
1008

    
1009
        /**
1010
         * Inserta el SRS.
1011
         *
1012
         * @param m_srs SRS.
1013
         */
1014
        public void setSRS(String m_srs) {
1015
                m_SRS = m_srs;
1016
        }
1017

    
1018
        /**
1019
         * Inserta la extensi?n total de la capa.
1020
         *
1021
         * @param fullExtent Rect?ngulo.
1022
         */
1023
        public void setFullExtent(Rectangle2D fullExtent) {
1024
                this.fullExtent = fullExtent;
1025
        }
1026

    
1027
        public HashMap getProperties() {
1028
                HashMap info = new HashMap();
1029
        String[] layerNames = getLayerQuery().split(",");
1030
        Vector layers = new Vector(layerNames.length);
1031
        try {
1032
            if(getDriver().connect(null)){
1033
                for (int i = 0; i < layerNames.length; i++) {
1034
                    layers.add(i, getDriver().getLayer(layerNames[i]));
1035
                }
1036
                info.put("name", getName());
1037
                info.put("selectedLayers", layers);
1038
                info.put("host", getHost());
1039
                info.put("srs", getSRS());
1040
                info.put("format", getFormat());
1041
                info.put("wmsTransparency", new Boolean(wmsTransparency));
1042
                info.put("styles", styles);
1043
                info.put("dimensions", dimensions);
1044
                info.put("fixedSize", fixedSize);
1045
                return info;
1046
            }
1047
        } catch (Exception e) {
1048
            e.printStackTrace();
1049
        }
1050
        return null;
1051
        }
1052

    
1053
        /**
1054
         * Asignar el estado del raster
1055
         * @param status
1056
         */
1057
        public void setStatus(StatusRasterInterface status){
1058
                this.status = status;
1059
        }
1060

    
1061
        /**
1062
         * Obtiene el estado del raster
1063
         * @return
1064
         */
1065
        public StatusRasterInterface getStatus(){
1066
                return this.status;
1067
        }
1068

    
1069
        /* (non-Javadoc)
1070
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getAttributes()
1071
         */
1072
        public ArrayList getAttributes() {
1073
                if(rasterFile != null){
1074
                        ArrayList attr = new ArrayList();
1075
                        String dataType = "Byte";
1076
                        if (rasterFile.getDataType() == DataBuffer.TYPE_BYTE) dataType = "Byte";
1077
                        else if (visualStatus.dataType == DataBuffer.TYPE_SHORT)
1078
                                dataType = "Short";
1079
                        else if (visualStatus.dataType == DataBuffer.TYPE_USHORT)
1080
                                dataType = "Unsigned Short";
1081
                        else if (visualStatus.dataType == DataBuffer.TYPE_INT)
1082
                                dataType = "Integer";
1083
                        else if (visualStatus.dataType == DataBuffer.TYPE_FLOAT)
1084
                                dataType = "Float";
1085
                        else if (visualStatus.dataType == DataBuffer.TYPE_DOUBLE)
1086
                                dataType = "Double";
1087
                        else
1088
                                dataType = "Unknown";
1089

    
1090
                        Object [][] a = {
1091
                                {"Filename",rasterFile.getName().substring(rasterFile.getName().lastIndexOf("/")+1, rasterFile.getName().length())},
1092
                                {"Filesize",new Long(0)},
1093
                                {"Width",new Integer((int)this.getWidth())},
1094
                                {"Height", new Integer((int)this.getHeight())},
1095
                                {"Bands", new Integer(visualStatus.bandCount)},
1096
                                {"BandDataType", dataType}
1097
                        };
1098
                        for (int i=0; i<a.length; i++)
1099
                                attr.add(a[i]);
1100

    
1101
                        return attr;
1102
                }
1103
                return  null;
1104
        }
1105

    
1106
        /* (non-Javadoc)
1107
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getFilterStack()
1108
         */
1109
        public RasterFilterStack getFilterStack() {
1110
                if(raster!=null)
1111
                        return raster.filterStack;
1112
                return null;
1113
        }
1114
        /* (non-Javadoc)
1115
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getHeight()
1116
         */
1117
        public double getHeight() {
1118
                return visualStatus.height;
1119
        }
1120

    
1121
        /* (non-Javadoc)
1122
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxX()
1123
         */
1124
        public double getMaxX() {
1125
                return visualStatus.maxX;
1126
        }
1127

    
1128
        /* (non-Javadoc)
1129
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxY()
1130
         */
1131
        public double getMaxY() {
1132
                return visualStatus.maxY;
1133
        }
1134

    
1135
        /* (non-Javadoc)
1136
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinX()
1137
         */
1138
        public double getMinX() {
1139
                return visualStatus.minX;
1140
        }
1141

    
1142
        /* (non-Javadoc)
1143
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinY()
1144
         */
1145
        public double getMinY() {
1146
                return visualStatus.minY;
1147
        }
1148
        /* (non-Javadoc)
1149
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getPixel(double, double)
1150
         */
1151
        public int[] getPixel(double wcx, double wcy) {
1152
                if(getPxRaster() != null)
1153
                        return getPxRaster().getPixel(wcx, wcy);
1154
        return null;
1155
        }
1156
        /* (non-Javadoc)
1157
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getSource()
1158
         */
1159
        public RasterAdapter getSource() {
1160
                return null;
1161
        }
1162
        /* (non-Javadoc)
1163
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getWidth()
1164
         */
1165
        public double getWidth() {
1166
                return visualStatus.width;
1167
        }
1168
        /* (non-Javadoc)
1169
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setBand(int, int)
1170
         */
1171
        public void setBand(int flag, int nBand) {
1172
                switch(flag){
1173
                case GeoRasterFile.RED_BAND:setBandR(nBand);break;
1174
                case GeoRasterFile.GREEN_BAND:setBandG(nBand);break;
1175
                case GeoRasterFile.BLUE_BAND:setBandB(nBand);break;
1176
                }
1177
        }
1178
        /* (non-Javadoc)
1179
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setFilterStack(org.cresques.io.raster.RasterFilterStack)
1180
         */
1181
        public void setFilterStack(RasterFilterStack stack) {
1182
                this.filterStack = stack;
1183
        }
1184
        /* (non-Javadoc)
1185
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPos(int, int)
1186
         */
1187
        public void setPos(int x, int y) {
1188
                this.posX = x;
1189
                this.posY = y;
1190
        }
1191

    
1192
        /* (non-Javadoc)
1193
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPosWC(double, double)
1194
         */
1195
        public void setPosWC(double x, double y) {
1196
                this.posXWC = x;
1197
                this.posYWC = y;
1198
        }
1199

    
1200
        /* (non-Javadoc)
1201
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setRGB(int, int, int)
1202
         */
1203
        public void setRGB(int r, int g, int b) {
1204
                this.r = r;
1205
                this.g = g;
1206
                this.b = b;
1207
        }
1208
        /* (non-Javadoc)
1209
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setSource(com.iver.cit.gvsig.fmap.layers.RasterAdapter)
1210
         */
1211
        public void setSource(RasterAdapter ra) {
1212
        }
1213
        /**
1214
         * @return Returns the raster.
1215
         */
1216
        public PxRaster getPxRaster() {
1217
                return raster;
1218
        }
1219
        /**
1220
         * @return Returns the rasterFile.
1221
         */
1222
        public GeoRasterFile getGeoRasterFile() {
1223
                return rasterFile;
1224
        }
1225

    
1226
        public void setTransparency(int trans) {
1227
                this.transparency = trans;
1228
        }
1229

    
1230
        /**
1231
         * Sets the R-band.
1232
         *
1233
         * Asigna la banda R.
1234
         * @param r
1235
         */
1236
        public void setBandR(int r){
1237
                this.rband = r;
1238
        }
1239

    
1240
        /**
1241
         * Sets the G-band.
1242
         *
1243
         * Asigna la banda G
1244
         * @param g
1245
         */
1246
        public void setBandG(int g){
1247
                this.gband = g;
1248
        }
1249

    
1250
        /**
1251
         * Sets the B-band.
1252
         *
1253
         * Asigna la banda B
1254
         * @param b
1255
         */
1256
        public void setBandB(int b){
1257
                this.bband = b;
1258
        }
1259

    
1260
    /**
1261
     * @return Returns the wmsTransparency.
1262
     */
1263
    public boolean isWmsTransparent() {
1264
        return wmsTransparency;
1265
    }
1266

    
1267
    /**
1268
     * @param wmsTransparency The wmsTransparency to set.
1269
     */
1270
    public void setWmsTransparency(boolean wmsTransparency) {
1271
        this.wmsTransparency = wmsTransparency;
1272
    }
1273

    
1274
     /**
1275
     * @param styles
1276
     */
1277
    public void setStyles(Vector styles) {
1278
            //laura:
1279
            //layer query is built with the layer in reverse order
1280
            // so here we build the styles upside-down.
1281
            if (styles != null)
1282
            {
1283
                    this.styles = new Vector();
1284
                    for(int i = styles.size()-1; i>=0; i--)
1285
                    {
1286
                            this.styles.add(styles.elementAt(i));
1287
                    }
1288
            }
1289
    }
1290

    
1291
    /**
1292
     * Sets the dimension vector that is a list of key-value pairs containing
1293
     * the name of the dimension and the value for it
1294
     * @param dimensions
1295
     */
1296
    public void setDimensions(Vector dimensions) {
1297
        this.dimensions = dimensions;
1298
    }
1299

    
1300
    /**
1301
     * Sets the set of URLs that should be accessed for each operation performed
1302
     * to the server.
1303
     *
1304
     * @param onlineResources
1305
     */
1306
        public void setOnlineResources(Hashtable onlineResources) {
1307
                this.onlineResources = onlineResources;
1308
        }
1309

    
1310
        /**
1311
         * When a server is not fully featured and it only can serve constant map
1312
         * sizes this value must be set. It expresses the size in pixels (width, height)
1313
         * that the map will be requested.
1314
         * @param Dimension sz
1315
         */
1316
        public void setFixedSize(Dimension sz) {
1317
                fixedSize = sz;
1318
        }
1319

    
1320
        /**
1321
         * Tells whether if this layer must deal with the server with the constant-size
1322
         * limitations or not.
1323
         * @return boolean.
1324
         */
1325
        private boolean isSizeFixed() {
1326
                return fixedSize != null && fixedSize.getWidth() > 0 && fixedSize.getHeight() > 0;
1327
        }
1328

    
1329
        /**
1330
         * If it is true, this layer accepts GetFeatureInfo operations. This WMS operations
1331
         * maps to FMap's infoByPoint(p) operation.
1332
         * @param b
1333
         */
1334
        public void setQueryable(boolean b) {
1335
                queryable = b;
1336
        }
1337

    
1338
        /**
1339
         * Creates the part of a OGC's MapContext document that would describe this
1340
         * layer(s).
1341
         * @param version, The desired version of the resulting document. (1.1.0)
1342
         * @return String containing the xml.
1343
         * @throws UnsupportedVersionException
1344
         */
1345
        public String toMapContext(String mapContextVersion) {
1346
                XmlBuilder xml = new XmlBuilder();
1347
                FMapWMSDriver drv;
1348
                try {
1349
                        drv = getDriver();
1350
                } catch (Exception e) {
1351
                        return xml.toString();
1352
                }
1353
                String[] layerNames = getLayerQuery().split(",");
1354
                String[] styleNames = (String[]) styles.toArray(new String[0]);
1355
                for (int i = 0; i < layerNames.length; i++) {
1356
                        WMSLayerNode layer = drv.getLayer(layerNames[i]);
1357
                        HashMap xmlAttrs = new HashMap();
1358

    
1359
                        // <Layer>
1360
                        xmlAttrs.put(WebMapContextTags.HIDDEN, !isVisible()+"");
1361
                        xmlAttrs.put(WebMapContextTags.QUERYABLE, queryable+"");
1362
                        xml.openTag(WebMapContextTags.LAYER, xmlAttrs);
1363
                        xmlAttrs.clear();
1364
                        if (mapContextVersion.equals("1.1.0") || mapContextVersion.equals("1.0.0")) {
1365
                                // <Server>
1366
                                xmlAttrs.put(WebMapContextTags.SERVICE, WebMapContextTags.WMS);
1367
                                xmlAttrs.put(WebMapContextTags.VERSION, drv.getVersion());
1368
                                xmlAttrs.put(WebMapContextTags.SERVER_TITLE, drv.getServiceTitle());
1369
                                xml.openTag(WebMapContextTags.SERVER, xmlAttrs);
1370
                                xmlAttrs.clear();
1371

    
1372
                                        // <OnlineResource>
1373
                                        xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1374
                                        xmlAttrs.put(WebMapContextTags.XLINK_HREF, getHost().toString());
1375
                                        xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1376
                                        xmlAttrs.clear();
1377
                                        // </OnlineResource>
1378

    
1379
                                xml.closeTag();
1380
                                // </Server>
1381

    
1382
                                // <Name>
1383
                                xml.writeTag(WebMapContextTags.NAME, layer.getName().trim());
1384
                                // </Name>
1385

    
1386
                                // <Title>
1387
                                xml.writeTag(WebMapContextTags.TITLE, getName().trim());
1388
                                // </Title>
1389

    
1390
                                // <Abstract>
1391
                                if (layer.getAbstract() != null)
1392
                                        xml.writeTag(WebMapContextTags.ABSTRACT, layer.getAbstract());
1393
                                // </Abstract>
1394

    
1395
                                // <SRS> (a list of available SRS for the enclosing layer)
1396
                                String[] strings = (String[]) layer.getAllSrs().toArray(new String[0]);
1397
                                String mySRS = strings[0];
1398
                                for (int j = 1; j < strings.length; j++) {
1399
                                        mySRS += ","+strings[j];
1400
                                }
1401
                                xml.writeTag(WebMapContextTags.SRS, mySRS);
1402
                                // </SRS>
1403

    
1404
                                // <FormatList>
1405
                                xml.openTag(WebMapContextTags.FORMAT_LIST);
1406
                                        strings = (String[]) drv.getFormats().toArray(new String[0]);
1407
                                        for (int j = 0; j < strings.length; j++) {
1408
                    // <Format>
1409
                                                String str = strings[j].trim();
1410
                                                if (str.equals(getFormat()))
1411
                                                        xml.writeTag(WebMapContextTags.FORMAT, str, WebMapContextTags.CURRENT, "1");
1412
                                                else
1413
                                                        xml.writeTag(WebMapContextTags.FORMAT, str);
1414
                    // </Format>
1415
                                        }
1416
                                xml.closeTag();
1417
                                // </FormatList>
1418

    
1419
                                // <StyleList>
1420
                                xml.openTag(WebMapContextTags.STYLE_LIST);
1421

    
1422
                                        if (layer.getStyles().size()>0) {
1423
                                                for (int j = 0; j < layer.getStyles().size(); j++) {
1424
                                                        // <Style>
1425
                                                        FMapWMSStyle st = (FMapWMSStyle) layer.getStyles().get(j);
1426
                                                        if (st.name.equals(styleNames[i]))
1427
                                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1428
                                                        xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1429
                                                        xmlAttrs.clear();
1430

    
1431
                                                                // <Name>
1432
                                                                xml.writeTag(WebMapContextTags.NAME, st.name);
1433
                                                                // </Name>
1434

    
1435
                                                                // <Title>
1436
                                                                xml.writeTag(WebMapContextTags.TITLE, st.title);
1437
                                                                // </Title>
1438

    
1439
                                                                // <LegendURL width="180" format="image/gif" height="50">
1440
                                                                        // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1441
                                                                        // </OnlineResource>
1442
                                                                // </LegendURL>
1443
                                                        xml.closeTag();
1444
                                                        // </Style>
1445

    
1446
                                                }
1447

    
1448
                                        } else {
1449
                                                // Create fake style (for compatibility issues)
1450
                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1451
                                                // <Style>
1452
                                                xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1453
                                                        xmlAttrs.clear();
1454
                                                        // <Name>
1455
                                                        xml.writeTag(WebMapContextTags.NAME, "default");
1456
                                                        // </Name>
1457

    
1458
                                                        // <Title>
1459
                                                        xml.writeTag(WebMapContextTags.TITLE, "default");
1460
                                                        // </Title>
1461

    
1462
//                                                        // <LegendURL width="180" format="image/gif" height="50">
1463
//                                                        xmlAttrs.put(WebMapContextTags.WIDTH, "0");
1464
//                                                        xmlAttrs.put(WebMapContextTags.HEIGHT, "0");
1465
//                                                        xmlAttrs.put(WebMapContextTags.FORMAT.toLowerCase(), "image/gif");
1466
//                                                        xml.openTag(WebMapContextTags.LEGEND_URL, xmlAttrs);
1467
//                                                        xmlAttrs.clear();
1468
//                                                                // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1469
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1470
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_HREF, "http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif");
1471
//                                                                xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1472
//                                                                // </OnlineResource>
1473
//                                                    // </LegendURL>
1474
//                                                        xml.closeTag();
1475
                                                // </Style>
1476
                                                xml.closeTag();
1477
                                        }
1478
                                // </StyleList>
1479
                                xml.closeTag();
1480
                                if (mapContextVersion.compareTo("1.0.0") > 0) {
1481
                                // <DimensionList>
1482
                                        xml.openTag(WebMapContextTags.DIMENSION_LIST);
1483
                                        // <Dimension>
1484
                                        // </Dimension>
1485
                                        xml.closeTag();
1486
                                // </DimensionList>
1487
                                }
1488
                        } else {
1489
                                xml.writeTag("ERROR", PluginServices.getText(this, "unsupported_map_context_version"));
1490
                        }
1491
                        // </Layer>
1492
                        xml.closeTag();
1493
                }
1494
                return xml.getXML();
1495
        }
1496

    
1497
        public ImageIcon getTocImageIcon() {
1498
                return new ImageIcon(PluginServices.getPluginServices("com.iver.cit.gvsig.wms").getClassLoader().getResource("images/icoLayer.png"));
1499
        }
1500

    
1501
        /*
1502
         *  (non-Javadoc)
1503
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1504
         */
1505
        public int[] getTileSize() {
1506
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1507
                return size;
1508
        }
1509

    
1510
        /*
1511
         *  (non-Javadoc)
1512
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1513
         */
1514
        public boolean isTiled() {
1515
                return mustTileDraw;
1516
        }
1517

    
1518

    
1519
}