Statistics
| Revision:

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

History | View | Annotate | Download (46.8 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
*
108
*/
109
public class FLyrWMS extends FLyrDefault implements InfoByPoint, RasterOperations {
110
        private boolean                                         isPrinting = false;
111
        private boolean                                         mustTileDraw = true;
112
        private boolean                                         mustTilePrint = true;
113
        private final int                                         maxTileDrawWidth = 1023;
114
        private final int                                         maxTileDrawHeight = 1023;
115
        private final int                                         maxTilePrintWidth = 1023;
116
        private final int                                         maxTilePrintHeight = 1023;
117
        private final int                                        minTilePrintWidth = 12;
118
        private final int                                        minTilePrintHeight = 12;
119

    
120
    public URL                                                         host;
121
    public String                                                 m_Format;
122

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

    
148

    
149
        private class MyCancellable implements ICancellable
150
        {
151

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

    
161
        }
162

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

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

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

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

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

    
208

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

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

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

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

    
254

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
364
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
365
                layerQuery = xml.getStringProperty("layerQuery");
366
                m_Format = xml.getStringProperty("format");
367
                m_SRS = xml.getStringProperty("srs");
368
        }
369

    
370
        /**
371
         * A partir del XMLEntity reproduce la capa.
372
         *
373
         * @param xml XMLEntity
374
         *
375
         * @throws XMLException
376
         * @throws DriverException
377
         * @throws DriverIOException
378
         */
379
        public void setXMLEntity(XMLEntity xml)
380
                throws XMLException {
381
                super.setXMLEntity(xml);
382
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty(
383
                                        "fullExtent"));
384

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
568

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

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

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

    
603

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

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

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

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

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

    
639
                        rasterProcess(g, vpData, f);
640

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

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

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

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

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

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

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

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

    
715

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

    
727
                        // begin patch
728

    
729
                        if (wImg < minTilePrintWidth) {
730
                                double wScale = (double) minTilePrintWidth / wImg;
731
                                wmsStatus.setWidth(minTilePrintWidth);
732
                                Rectangle2D sExtent = wmsStatus.getExtent();
733
                                Point2D initialPoint = new Point2D.Double(sExtent.getX(), sExtent.getY());
734
                                sExtent.setRect(sExtent.getX()*wScale, sExtent.getY(), sExtent.getWidth()*wScale, sExtent.getHeight());
735
                                if (!bBox.contains(initialPoint)) {
736
                                        sExtent.setRect(sExtent.getX() - initialPoint.getX(), sExtent.getY(), sExtent.getWidth(), sExtent.getHeight());
737
                                }
738
                        }
739

    
740
                        if (hImg < minTilePrintHeight) {
741
                                double hScale = (double) minTilePrintHeight / hImg;
742
                                wmsStatus.setHeight(minTilePrintHeight);
743
                                Rectangle2D sExtent = wmsStatus.getExtent();
744
                                Point2D initialPoint = new Point2D.Double(sExtent.getX(), sExtent.getY());
745
                                sExtent.setRect(sExtent.getX(), sExtent.getY()*hScale, sExtent.getWidth(), sExtent.getHeight()*hScale);
746
                                if (!bBox.contains(initialPoint)) {
747
                                        sExtent.setRect(sExtent.getX(), sExtent.getY() - initialPoint.getY(), sExtent.getWidth(), sExtent.getHeight());
748
                                }
749
                        }
750

    
751
                        // end patch
752
                        File f = getDriver().getMap(wmsStatus, c);
753
                        if (f == null)
754
                                return;
755
                        String nameWordFile = f.getPath() + getExtensionWorldFile();
756
                        com.iver.andami.Utilities.createTemp(nameWordFile, this.getDataWorldFile(bBox, sz));
757

    
758
                        ViewPortData vpData = new ViewPortData(
759
                                vp.getProjection(), new Extent(bBox), sz );
760
                        vpData.setMat(vp.getAffineTransform());
761

    
762
                        rasterProcess(g, vpData, f);
763

    
764
                } catch (ValidationException e) {
765
                        if (!c.isCanceled())
766
                                throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
767
                } catch (UnsupportedVersionException e) {
768
                        if (!c.isCanceled())
769
                                throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
770
                } catch (IOException e) {
771
                        if (!c.isCanceled())
772
                                if (callCount<MAX_RETRY_TIMES) {
773
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawFixedSize() ]  Failed in trying " + callCount + "/" + MAX_RETRY_TIMES + ")\n", null);
774
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error
775
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0)
776
                                        drawTile(g, vp, cancel);
777
                                }
778
                                if (callCount == 1) {
779
                                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
780
                                }
781
                } catch (WMSException e) {
782
                        if (!c.isCanceled()) {
783
                                if (callCount<MAX_RETRY_TIMES) {
784
                                        NotificationManager.addWarning("\n[ FLyrWMS.drawTile() ] Failed in trying " + callCount + "/" + MAX_RETRY_TIMES +" \n", null);
785
                                        // I'll try again requesting up to MAX_RETRY_TIMES times before throw an error
786
                                        // (this is mess code, should be replaced by a layer status handler which is scheduled for version > 1.0)
787
                                        drawTile(g, vp, cancel);
788
                                }
789
                                if (callCount == 1) {
790
                                        if (!isPrinting) {
791
                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
792
                                                this.setVisible(false);
793
                                        }
794
                                }
795
                        }
796
                }
797
                callCount--;
798
        }
799

    
800
        /**
801
         * Obtiene la extensi?n del fichero de georreferenciaci?n
802
         * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
803
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
804
         */
805
        private String getExtensionWorldFile(){
806
                String extWorldFile = ".wld";
807
            if(m_Format.equals("image/tif") || m_Format.equals("image/tiff"))
808
                    extWorldFile = ".tfw";
809
            if(m_Format.equals("image/jpeg"))
810
                    extWorldFile = ".jpgw";
811
            return extWorldFile;
812
        }
813

    
814
        /**
815
         * Calcula el contenido del fichero de georreferenciaci?n de una imagen.
816
         * @param bBox Tama?o y posici?n de la imagen (en coordenadas de usuario)
817
         * @param sz Tama?o de la imagen en pixeles.
818
         * @return el 'WorldFile', como String.
819
         * @throws IOException
820
         */
821
        public String getDataWorldFile(Rectangle2D bBox, Dimension sz) throws IOException {
822
                StringBuffer data = new StringBuffer();
823
            data.append((bBox.getMaxX() - bBox.getMinX())/(sz.getWidth() - 1)+"\n");
824
            data.append("0.0\n");
825
            data.append("0.0\n");
826
            data.append((bBox.getMaxY() - bBox.getMinY())/(sz.getHeight() - 1)+"\n");
827
            data.append(""+bBox.getMinX()+"\n");
828
            data.append(""+bBox.getMinY()+"\n");
829
            return data.toString();
830
        }
831

    
832
        /**
833
         * Dibuja una imagen usando PxRaster
834
         * @param g        Graphics2D en el que hay que dibujar.
835
         * @param vpData Par?metros de visualizaci?n
836
         * @param file La imagen en cuesti?n.
837
         */
838
        private void rasterProcess(Graphics2D g, ViewPortData vpData, File file) {
839

    
840
                //Creamos el PxRaster
841
                rasterFile = new GdalFile(vpData.getProjection(), file.getAbsolutePath());
842
                raster = new PxRaster(rasterFile, null, rasterFile.getExtent());
843

    
844
                if(status!=null && firstLoad){
845
                        status.applyStatus(this);
846
                        firstLoad = false;
847
                }
848

    
849
                //Recuperamos la pila de filtros si ya hubiese sido cargado antes
850
                if(this.filterStack!=null)
851
                        raster.filterStack = this.filterStack;
852

    
853
                raster.setTransparency(false);
854

    
855
                //Asignamos transparencia y orden de bandas
856
                if(this.transparency==-1 && !firstLoad);
857
                else
858
                        raster.setTransparency(this.transparency);
859

    
860
                raster.setBand(GeoRasterFile.RED_BAND,rband);
861
                raster.setBand(GeoRasterFile.GREEN_BAND, gband);
862
                raster.setBand(GeoRasterFile.BLUE_BAND, bband);
863

    
864
                //Despues del primer pxRaster asignamos el stackManager guardado para los siguientes.
865
                //Con esto conseguimos asignar los cambios que se hayan producido desde el cuadro de
866
                //propiedades cuando creamos un nuevo pxRaster
867
                if(this.stackManager != null)
868
                        raster.setStackManager(this.stackManager);
869

    
870
                if(visualStatus != null){
871
                        visualStatus.bandCount = raster.getBandCount();
872
                        visualStatus.dataType = raster.getDataType();
873
                }
874

    
875
                raster.draw(g, vpData);
876

    
877
                //En el primer pxRaster de una imagen obtenemos el Stack Manager para poder modificarlo
878
                //si queremos desde las propiedades
879

    
880
                if(this.stackManager == null)
881
                        this.stackManager = raster.getStackManager();
882

    
883
                if(this.filterStack == null)
884
                        this.filterStack = raster.filterStack;
885

    
886
                //rasterFile.close();
887
        }
888

    
889
        /**
890
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D,
891
         *                 com.iver.cit.gvsig.fmap.ViewPort,
892
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
893
         */
894
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale)
895
                throws DriverException {
896
                if (isVisible() && isWithinScale(scale)){
897
                isPrinting = true;
898
                if (!mustTilePrint) {
899
                        draw(null, g, viewPort, cancel,scale);
900
                } else {
901
                // Para no pedir imagenes demasiado grandes, vamos
902
                // a hacer lo mismo que hace EcwFile: chunkear.
903
                // Llamamos a drawView con cuadraditos m?s peque?os
904
                // del BufferedImage ni caso, cuando se imprime viene con null
905

    
906
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
907
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
908
                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
909
                            // Parte que dibuja
910
                            try {
911
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
912
                                drawTile(g, vp, cancel);
913
                                } catch (NoninvertibleTransformException e) {
914
                                        e.printStackTrace();
915
                                }
916
                }
917
                }
918
            isPrinting = false;
919
                }
920
        }
921

    
922
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale)
923
                throws DriverException {
924
                draw(null, g, viewPort, cancel,scale);
925
        }
926

    
927
        /**
928
         * Devuelve el FMapWMSDriver.
929
         *
930
         * @return FMapWMSDriver
931
         *
932
         * @throws IllegalStateException
933
         * @throws ValidationException
934
         * @throws UnsupportedVersionException
935
         * @throws IOException
936
         */
937
        private FMapWMSDriver getDriver()
938
                throws IllegalStateException, ValidationException,
939
                        UnsupportedVersionException, IOException {
940
                return FMapWMSDriverFactory.getFMapDriverForURL(host);
941
        }
942

    
943
        /**
944
         * Devuelve el FMapWMSDriver.
945
         *
946
         * @return FMapWMSDriver
947
         *
948
         * @throws IllegalStateException
949
         * @throws ValidationException
950
         * @throws UnsupportedVersionException
951
         * @throws IOException
952
         */
953
        public void setDriver(FMapWMSDriver drv) {
954
                wms = drv;
955
        }
956

    
957
        /**
958
         * Devuelve el URL.
959
         *
960
         * @return URL.
961
         */
962
        public URL getHost() {
963
                return host;
964
        }
965

    
966
        /**
967
         * Inserta el URL.
968
         *
969
         * @param host URL.
970
         */
971
        public void setHost(URL host) {
972
                this.host = host;
973
        }
974

    
975
        /**
976
         * Devuelve la informaci?n de la consulta.
977
         *
978
         * @return String.
979
         */
980
        public String getInfoLayerQuery() {
981
                return infoLayerQuery;
982
        }
983

    
984
        /**
985
         * Inserta la informaci?n de la consulta.
986
         *
987
         * @param infoLayerQuery String.
988
         */
989
        public void setInfoLayerQuery(String infoLayerQuery) {
990
                this.infoLayerQuery = infoLayerQuery;
991
        }
992

    
993
        /**
994
         * Devuelve la consulta.
995
         *
996
         * @return String.
997
         */
998
        public String getLayerQuery() {
999
                return layerQuery;
1000
        }
1001

    
1002
        /**
1003
         * Inserta la consulta.
1004
         *
1005
         * @param layerQuery consulta.
1006
         */
1007
        public void setLayerQuery(String layerQuery) {
1008
                this.layerQuery = layerQuery;
1009
        }
1010

    
1011
        /**
1012
         * Devuelve el formato.
1013
         *
1014
         * @return Formato.
1015
         */
1016
        public String getFormat() {
1017
                return m_Format;
1018
        }
1019

    
1020
        /**
1021
         * Inserta el formato.
1022
         *
1023
         * @param format Formato.
1024
         */
1025
        public void setFormat(String format) {
1026
                m_Format = format;
1027
        }
1028

    
1029
        /**
1030
         * Devuelve el SRS.
1031
         *
1032
         * @return SRS.
1033
         */
1034
        public String getSRS() {
1035
                return m_SRS;
1036
        }
1037

    
1038
        /**
1039
         * Inserta el SRS.
1040
         *
1041
         * @param m_srs SRS.
1042
         */
1043
        public void setSRS(String m_srs) {
1044
                m_SRS = m_srs;
1045
        }
1046

    
1047
        /**
1048
         * Inserta la extensi?n total de la capa.
1049
         *
1050
         * @param fullExtent Rect?ngulo.
1051
         */
1052
        public void setFullExtent(Rectangle2D fullExtent) {
1053
                this.fullExtent = fullExtent;
1054
        }
1055

    
1056
        public HashMap getProperties() {
1057
                HashMap info = new HashMap();
1058
        String[] layerNames = getLayerQuery().split(",");
1059
        Vector layers = new Vector(layerNames.length);
1060
        try {
1061
            if(getDriver().connect(null)){
1062
                for (int i = 0; i < layerNames.length; i++) {
1063
                    layers.add(i, getDriver().getLayer(layerNames[i]));
1064
                }
1065
                info.put("name", getName());
1066
                info.put("selectedLayers", layers);
1067
                info.put("host", getHost());
1068
                info.put("srs", getSRS());
1069
                info.put("format", getFormat());
1070
                info.put("wmsTransparency", new Boolean(wmsTransparency));
1071
                info.put("styles", styles);
1072
                info.put("dimensions", dimensions);
1073
                info.put("fixedSize", fixedSize);
1074
                return info;
1075
            }
1076
        } catch (Exception e) {
1077
            e.printStackTrace();
1078
        }
1079
        return null;
1080
        }
1081

    
1082
        /**
1083
         * Asignar el estado del raster
1084
         * @param status
1085
         */
1086
        public void setStatus(StatusRasterInterface status){
1087
                this.status = status;
1088
        }
1089

    
1090
        /**
1091
         * Obtiene el estado del raster
1092
         * @return
1093
         */
1094
        public StatusRasterInterface getStatus(){
1095
                return this.status;
1096
        }
1097

    
1098
        /* (non-Javadoc)
1099
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getAttributes()
1100
         */
1101
        public ArrayList getAttributes() {
1102
                if(rasterFile != null){
1103
                        ArrayList attr = new ArrayList();
1104
                        String dataType = "Byte";
1105
                        if (rasterFile.getDataType() == DataBuffer.TYPE_BYTE) dataType = "Byte";
1106
                        else if (visualStatus.dataType == DataBuffer.TYPE_SHORT)
1107
                                dataType = "Short";
1108
                        else if (visualStatus.dataType == DataBuffer.TYPE_USHORT)
1109
                                dataType = "Unsigned Short";
1110
                        else if (visualStatus.dataType == DataBuffer.TYPE_INT)
1111
                                dataType = "Integer";
1112
                        else if (visualStatus.dataType == DataBuffer.TYPE_FLOAT)
1113
                                dataType = "Float";
1114
                        else if (visualStatus.dataType == DataBuffer.TYPE_DOUBLE)
1115
                                dataType = "Double";
1116
                        else
1117
                                dataType = "Unknown";
1118

    
1119
                        Object [][] a = {
1120
                                {"Filename",rasterFile.getName().substring(rasterFile.getName().lastIndexOf("/")+1, rasterFile.getName().length())},
1121
                                {"Filesize",new Long(0)},
1122
                                {"Width",new Integer((int)this.getWidth())},
1123
                                {"Height", new Integer((int)this.getHeight())},
1124
                                {"Bands", new Integer(visualStatus.bandCount)},
1125
                                {"BandDataType", dataType}
1126
                        };
1127
                        for (int i=0; i<a.length; i++)
1128
                                attr.add(a[i]);
1129

    
1130
                        return attr;
1131
                }
1132
                return  null;
1133
        }
1134

    
1135
        /* (non-Javadoc)
1136
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getFilterStack()
1137
         */
1138
        public RasterFilterStack getFilterStack() {
1139
                if(raster!=null)
1140
                        return raster.filterStack;
1141
                return null;
1142
        }
1143
        /* (non-Javadoc)
1144
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getHeight()
1145
         */
1146
        public double getHeight() {
1147
                return visualStatus.height;
1148
        }
1149

    
1150
        /* (non-Javadoc)
1151
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxX()
1152
         */
1153
        public double getMaxX() {
1154
                return visualStatus.maxX;
1155
        }
1156

    
1157
        /* (non-Javadoc)
1158
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxY()
1159
         */
1160
        public double getMaxY() {
1161
                return visualStatus.maxY;
1162
        }
1163

    
1164
        /* (non-Javadoc)
1165
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinX()
1166
         */
1167
        public double getMinX() {
1168
                return visualStatus.minX;
1169
        }
1170

    
1171
        /* (non-Javadoc)
1172
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinY()
1173
         */
1174
        public double getMinY() {
1175
                return visualStatus.minY;
1176
        }
1177
        /* (non-Javadoc)
1178
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getPixel(double, double)
1179
         */
1180
        public int[] getPixel(double wcx, double wcy) {
1181
                if(getPxRaster() != null)
1182
                        return getPxRaster().getPixel(wcx, wcy);
1183
        return null;
1184
        }
1185
        /* (non-Javadoc)
1186
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getSource()
1187
         */
1188
        public RasterAdapter getSource() {
1189
                return null;
1190
        }
1191
        /* (non-Javadoc)
1192
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getWidth()
1193
         */
1194
        public double getWidth() {
1195
                return visualStatus.width;
1196
        }
1197
        /* (non-Javadoc)
1198
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setBand(int, int)
1199
         */
1200
        public void setBand(int flag, int nBand) {
1201
                switch(flag){
1202
                case GeoRasterFile.RED_BAND:setBandR(nBand);break;
1203
                case GeoRasterFile.GREEN_BAND:setBandG(nBand);break;
1204
                case GeoRasterFile.BLUE_BAND:setBandB(nBand);break;
1205
                }
1206
        }
1207
        /* (non-Javadoc)
1208
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setFilterStack(org.cresques.io.raster.RasterFilterStack)
1209
         */
1210
        public void setFilterStack(RasterFilterStack stack) {
1211
                this.filterStack = stack;
1212
        }
1213
        /* (non-Javadoc)
1214
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPos(int, int)
1215
         */
1216
        public void setPos(int x, int y) {
1217
                this.posX = x;
1218
                this.posY = y;
1219
        }
1220

    
1221
        /* (non-Javadoc)
1222
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPosWC(double, double)
1223
         */
1224
        public void setPosWC(double x, double y) {
1225
                this.posXWC = x;
1226
                this.posYWC = y;
1227
        }
1228

    
1229
        /* (non-Javadoc)
1230
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setRGB(int, int, int)
1231
         */
1232
        public void setRGB(int r, int g, int b) {
1233
                this.r = r;
1234
                this.g = g;
1235
                this.b = b;
1236
        }
1237
        /* (non-Javadoc)
1238
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setSource(com.iver.cit.gvsig.fmap.layers.RasterAdapter)
1239
         */
1240
        public void setSource(RasterAdapter ra) {
1241
        }
1242
        /**
1243
         * @return Returns the raster.
1244
         */
1245
        public PxRaster getPxRaster() {
1246
                return raster;
1247
        }
1248
        /**
1249
         * @return Returns the rasterFile.
1250
         */
1251
        public GeoRasterFile getGeoRasterFile() {
1252
                return rasterFile;
1253
        }
1254

    
1255
        public void setTransparency(int trans) {
1256
                this.transparency = trans;
1257
        }
1258

    
1259
        /**
1260
         * Sets the R-band.
1261
         *
1262
         * Asigna la banda R.
1263
         * @param r
1264
         */
1265
        public void setBandR(int r){
1266
                this.rband = r;
1267
        }
1268

    
1269
        /**
1270
         * Sets the G-band.
1271
         *
1272
         * Asigna la banda G
1273
         * @param g
1274
         */
1275
        public void setBandG(int g){
1276
                this.gband = g;
1277
        }
1278

    
1279
        /**
1280
         * Sets the B-band.
1281
         *
1282
         * Asigna la banda B
1283
         * @param b
1284
         */
1285
        public void setBandB(int b){
1286
                this.bband = b;
1287
        }
1288

    
1289
    /**
1290
     * @return Returns the wmsTransparency.
1291
     */
1292
    public boolean isWmsTransparent() {
1293
        return wmsTransparency;
1294
    }
1295

    
1296
    /**
1297
     * @param wmsTransparency The wmsTransparency to set.
1298
     */
1299
    public void setWmsTransparency(boolean wmsTransparency) {
1300
        this.wmsTransparency = wmsTransparency;
1301
    }
1302

    
1303
     /**
1304
     * @param styles
1305
     */
1306
    public void setStyles(Vector styles) {
1307
            //laura:
1308
            //layer query is built with the layer in reverse order
1309
            // so here we build the styles upside-down.
1310
            if (styles != null)
1311
            {
1312
                    this.styles = new Vector();
1313
                    for(int i = styles.size()-1; i>=0; i--)
1314
                    {
1315
                            this.styles.add(styles.elementAt(i));
1316
                    }
1317
            }
1318
    }
1319

    
1320
    /**
1321
     * Sets the dimension vector that is a list of key-value pairs containing
1322
     * the name of the dimension and the value for it
1323
     * @param dimensions
1324
     */
1325
    public void setDimensions(Vector dimensions) {
1326
        this.dimensions = dimensions;
1327
    }
1328

    
1329
    /**
1330
     * Sets the set of URLs that should be accessed for each operation performed
1331
     * to the server.
1332
     *
1333
     * @param onlineResources
1334
     */
1335
        public void setOnlineResources(Hashtable onlineResources) {
1336
                this.onlineResources = onlineResources;
1337
        }
1338

    
1339
        /**
1340
         * When a server is not fully featured and it only can serve constant map
1341
         * sizes this value must be set. It expresses the size in pixels (width, height)
1342
         * that the map will be requested.
1343
         * @param Dimension sz
1344
         */
1345
        public void setFixedSize(Dimension sz) {
1346
                fixedSize = sz;
1347
        }
1348

    
1349
        /**
1350
         * Tells whether if this layer must deal with the server with the constant-size
1351
         * limitations or not.
1352
         * @return boolean.
1353
         */
1354
        private boolean isSizeFixed() {
1355
                return fixedSize != null && fixedSize.getWidth() > 0 && fixedSize.getHeight() > 0;
1356
        }
1357

    
1358
        /**
1359
         * If it is true, this layer accepts GetFeatureInfo operations. This WMS operations
1360
         * maps to FMap's infoByPoint(p) operation.
1361
         * @param b
1362
         */
1363
        public void setQueryable(boolean b) {
1364
                queryable = b;
1365
        }
1366

    
1367
        /**
1368
         * Creates the part of a OGC's MapContext document that would describe this
1369
         * layer(s).
1370
         * @param version, The desired version of the resulting document. (1.1.0)
1371
         * @return String containing the xml.
1372
         * @throws UnsupportedVersionException
1373
         */
1374
        public String toMapContext(String mapContextVersion) {
1375
                XmlBuilder xml = new XmlBuilder();
1376
                FMapWMSDriver drv;
1377
                try {
1378
                        drv = getDriver();
1379
                } catch (Exception e) {
1380
                        return xml.toString();
1381
                }
1382
                String[] layerNames = getLayerQuery().split(",");
1383
                String[] styleNames = (String[]) styles.toArray(new String[0]);
1384
                for (int i = 0; i < layerNames.length; i++) {
1385
                        WMSLayerNode layer = drv.getLayer(layerNames[i]);
1386
                        HashMap xmlAttrs = new HashMap();
1387

    
1388
                        // <Layer>
1389
                        xmlAttrs.put(WebMapContextTags.HIDDEN, !isVisible()+"");
1390
                        xmlAttrs.put(WebMapContextTags.QUERYABLE, queryable+"");
1391
                        xml.openTag(WebMapContextTags.LAYER, xmlAttrs);
1392
                        xmlAttrs.clear();
1393
                        if (mapContextVersion.equals("1.1.0") || mapContextVersion.equals("1.0.0")) {
1394
                                // <Server>
1395
                                xmlAttrs.put(WebMapContextTags.SERVICE, WebMapContextTags.WMS);
1396
                                xmlAttrs.put(WebMapContextTags.VERSION, drv.getVersion());
1397
                                xmlAttrs.put(WebMapContextTags.SERVER_TITLE, drv.getServiceTitle());
1398
                                xml.openTag(WebMapContextTags.SERVER, xmlAttrs);
1399
                                xmlAttrs.clear();
1400

    
1401
                                        // <OnlineResource>
1402
                                        xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1403
                                        xmlAttrs.put(WebMapContextTags.XLINK_HREF, getHost().toString());
1404
                                        xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1405
                                        xmlAttrs.clear();
1406
                                        // </OnlineResource>
1407

    
1408
                                xml.closeTag();
1409
                                // </Server>
1410

    
1411
                                // <Name>
1412
                                xml.writeTag(WebMapContextTags.NAME, layer.getName().trim());
1413
                                // </Name>
1414

    
1415
                                // <Title>
1416
                                xml.writeTag(WebMapContextTags.TITLE, getName().trim());
1417
                                // </Title>
1418

    
1419
                                // <Abstract>
1420
                                if (layer.getAbstract() != null)
1421
                                        xml.writeTag(WebMapContextTags.ABSTRACT, layer.getAbstract());
1422
                                // </Abstract>
1423

    
1424
                                // <SRS> (a list of available SRS for the enclosing layer)
1425
                                String[] strings = (String[]) layer.getAllSrs().toArray(new String[0]);
1426
                                String mySRS = strings[0];
1427
                                for (int j = 1; j < strings.length; j++) {
1428
                                        mySRS += ","+strings[j];
1429
                                }
1430
                                xml.writeTag(WebMapContextTags.SRS, mySRS);
1431
                                // </SRS>
1432

    
1433
                                // <FormatList>
1434
                                xml.openTag(WebMapContextTags.FORMAT_LIST);
1435
                                        strings = (String[]) drv.getFormats().toArray(new String[0]);
1436
                                        for (int j = 0; j < strings.length; j++) {
1437
                    // <Format>
1438
                                                String str = strings[j].trim();
1439
                                                if (str.equals(getFormat()))
1440
                                                        xml.writeTag(WebMapContextTags.FORMAT, str, WebMapContextTags.CURRENT, "1");
1441
                                                else
1442
                                                        xml.writeTag(WebMapContextTags.FORMAT, str);
1443
                    // </Format>
1444
                                        }
1445
                                xml.closeTag();
1446
                                // </FormatList>
1447

    
1448
                                // <StyleList>
1449
                                xml.openTag(WebMapContextTags.STYLE_LIST);
1450

    
1451
                                        if (layer.getStyles().size()>0) {
1452
                                                for (int j = 0; j < layer.getStyles().size(); j++) {
1453
                                                        // <Style>
1454
                                                        FMapWMSStyle st = (FMapWMSStyle) layer.getStyles().get(j);
1455
                                                        if (st.name.equals(styleNames[i]))
1456
                                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1457
                                                        xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1458
                                                        xmlAttrs.clear();
1459

    
1460
                                                                // <Name>
1461
                                                                xml.writeTag(WebMapContextTags.NAME, st.name);
1462
                                                                // </Name>
1463

    
1464
                                                                // <Title>
1465
                                                                xml.writeTag(WebMapContextTags.TITLE, st.title);
1466
                                                                // </Title>
1467

    
1468
                                                                // <LegendURL width="180" format="image/gif" height="50">
1469
                                                                        // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1470
                                                                        // </OnlineResource>
1471
                                                                // </LegendURL>
1472
                                                        xml.closeTag();
1473
                                                        // </Style>
1474

    
1475
                                                }
1476

    
1477
                                        } else {
1478
                                                // Create fake style (for compatibility issues)
1479
                                                xmlAttrs.put(WebMapContextTags.CURRENT, "1");
1480
                                                // <Style>
1481
                                                xml.openTag(WebMapContextTags.STYLE, xmlAttrs);
1482
                                                        xmlAttrs.clear();
1483
                                                        // <Name>
1484
                                                        xml.writeTag(WebMapContextTags.NAME, "default");
1485
                                                        // </Name>
1486

    
1487
                                                        // <Title>
1488
                                                        xml.writeTag(WebMapContextTags.TITLE, "default");
1489
                                                        // </Title>
1490

    
1491
//                                                        // <LegendURL width="180" format="image/gif" height="50">
1492
//                                                        xmlAttrs.put(WebMapContextTags.WIDTH, "0");
1493
//                                                        xmlAttrs.put(WebMapContextTags.HEIGHT, "0");
1494
//                                                        xmlAttrs.put(WebMapContextTags.FORMAT.toLowerCase(), "image/gif");
1495
//                                                        xml.openTag(WebMapContextTags.LEGEND_URL, xmlAttrs);
1496
//                                                        xmlAttrs.clear();
1497
//                                                                // <OnlineResource xlink:type="simple" xlink:href="http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif"/>
1498
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_TYPE, "simple");
1499
//                                                                xmlAttrs.put(WebMapContextTags.XLINK_HREF, "http://globe.digitalearth.gov/globe/en/icons/colorbars/NATIONAL.gif");
1500
//                                                                xml.writeTag(WebMapContextTags.ONLINE_RESOURCE, xmlAttrs);
1501
//                                                                // </OnlineResource>
1502
//                                                    // </LegendURL>
1503
//                                                        xml.closeTag();
1504
                                                // </Style>
1505
                                                xml.closeTag();
1506
                                        }
1507
                                // </StyleList>
1508
                                xml.closeTag();
1509
                                if (mapContextVersion.compareTo("1.0.0") > 0) {
1510
                                // <DimensionList>
1511
                                        xml.openTag(WebMapContextTags.DIMENSION_LIST);
1512
                                        // <Dimension>
1513
                                        // </Dimension>
1514
                                        xml.closeTag();
1515
                                // </DimensionList>
1516
                                }
1517
                        } else {
1518
                                xml.writeTag("ERROR", PluginServices.getText(this, "unsupported_map_context_version"));
1519
                        }
1520
                        // </Layer>
1521
                        xml.closeTag();
1522
                }
1523
                return xml.getXML();
1524
        }
1525

    
1526
        public ImageIcon getTocImageIcon() {
1527
                return new ImageIcon(PluginServices.getPluginServices("com.iver.cit.gvsig.wms").getClassLoader().getResource("images/icoLayer.png"));
1528
        }
1529

    
1530
        /*
1531
         *  (non-Javadoc)
1532
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1533
         */
1534
        public int[] getTileSize() {
1535
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1536
                return size;
1537
        }
1538

    
1539
        /*
1540
         *  (non-Javadoc)
1541
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1542
         */
1543
        public boolean isTiled() {
1544
                return mustTileDraw;
1545
        }
1546

    
1547

    
1548
}