Statistics
| Revision:

svn-gvsig-desktop / branches / v05 / extensions / extWMS / src / com / iver / cit / gvsig / fmap / layers / FLyrWMS.java @ 4187

History | View | Annotate | Download (33.5 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.io.File;
54
import java.io.IOException;
55
import java.lang.reflect.Constructor;
56
import java.lang.reflect.InvocationTargetException;
57
import java.net.MalformedURLException;
58
import java.net.URL;
59
import java.util.ArrayList;
60
import java.util.HashMap;
61
import java.util.Hashtable;
62
import java.util.Iterator;
63
import java.util.Vector;
64

    
65
import javax.swing.JOptionPane;
66

    
67
import org.cresques.geo.ViewPortData;
68
import org.cresques.io.GdalFile;
69
import org.cresques.io.GeoRasterFile;
70
import org.cresques.io.raster.RasterFilterStack;
71
import org.cresques.io.raster.RasterFilterStackManager;
72
import org.cresques.px.Extent;
73
import org.cresques.px.PxRaster;
74
import org.exolab.castor.xml.ValidationException;
75
import org.gvsig.remoteClient.utils.Utilities;
76
import org.gvsig.remoteClient.wms.WMSStatus;
77

    
78
import com.iver.andami.PluginServices;
79
import com.iver.andami.messages.NotificationManager;
80
import com.iver.cit.gvsig.fmap.DriverException;
81
import com.iver.cit.gvsig.fmap.ViewPort;
82
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
83
import com.iver.cit.gvsig.fmap.drivers.UnsupportedVersionException;
84
import com.iver.cit.gvsig.fmap.drivers.WMSException;
85
import com.iver.cit.gvsig.fmap.drivers.wms.FMapWMSDriver;
86
import com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint;
87
import com.iver.cit.gvsig.fmap.operations.Cancellable;
88
import com.iver.utiles.StringUtilities;
89
import com.iver.utiles.XMLEntity;
90

    
91

    
92
/**
93
* FMap's WMS Layer class.
94
*
95
* @author Jaume Dominguez Faus
96
*                   Nacho Brodin
97
* 
98
*/
99
public class FLyrWMS extends FLyrDefault implements InfoByPoint, RasterOperations {
100
        private boolean isPrinting = false;
101
        private boolean mustTileDraw = false;
102
        private boolean mustTilePrint = true;
103
        private final int maxTileDrawWidth = -1;
104
        private final int maxTileDrawHeight = -1;
105
        private final int maxTilePrintWidth = 1023;
106
        private final int maxTilePrintHeight = 1023;
107
    
108
    public URL host;
109
    public String m_Format;
110
    
111
        private String m_SRS;
112
        private String layerQuery;
113
        private String infoLayerQuery;
114
        private FMapWMSDriver wms;
115
        private WMSStatus wmsStatus = new WMSStatus();
116
        private Rectangle2D fullExtent;
117
        private boolean wmsTransparency;
118
    private Vector styles;
119
    private Vector dimensions;
120
        private StatusRasterInterface                status = null;
121
        private int                                                 posX = 0, posY = 0;
122
        private double                                                 posXWC = 0, posYWC = 0;
123
        private int                                                 r = 0, g = 0, b = 0;
124
        private GeoRasterFile                                 rasterFile = null;
125
        private PxRaster                                         raster = null;
126
        private RasterFilterStack                         filterStack = null;
127
        private boolean                                                firstLoad = false;
128
        private int                                                 transparency = -1;
129
        private int                                                 rband = 0, gband = 1, bband = 2;
130
        private RasterFilterStackManager        stackManager = null;
131
        private Hashtable onlineResources = new Hashtable();
132
        private Dimension fixedSize;
133
        private boolean queryable = true;
134

    
135

    
136

    
137
        /**
138
         * Devuelve el XMLEntity con la informaci�n necesaria para reproducir la
139
         * capa.
140
         *
141
         * @return XMLEntity.
142
         * @throws XMLException
143
         */
144
        public XMLEntity getXMLEntity() throws XMLException {
145
                XMLEntity xml = super.getXMLEntity();
146

    
147
                // Full extent
148
                xml.putProperty("fullExtent", StringUtilities.rect2String(fullExtent));
149
                
150
                // Host
151
                xml.putProperty("host", host.toExternalForm());
152
                
153
                // Part of the query that is not the host, or the
154
                // layer names, or other not listed bellow
155
                xml.putProperty("infoLayerQuery", infoLayerQuery);
156
                
157
                // Part of the query containing the layer names
158
                xml.putProperty("layerQuery", layerQuery);
159
                
160
                // Format
161
                xml.putProperty("format", m_Format);
162
                
163
                // SRS
164
                xml.putProperty("srs", m_SRS);
165
                if (status!=null)
166
                        status.getXMLEntity(xml, true, this);
167
                else{
168
                        status = new StatusLayerRaster();
169
                        status.getXMLEntity(xml, true, this);
170
                }
171
                
172
        // Transparency
173
        xml.putProperty("wms_transparency", wmsTransparency);
174
        
175
        // Styles
176
        if (styles!=null){
177
            String stylePr = "";
178
            for (int i = 0; i < styles.size(); i++) {
179
                stylePr += (String) styles.get(i);
180
                if (i<styles.size()-1)
181
                    stylePr += ",";
182
            }
183
            if (stylePr.endsWith(","))
184
                    stylePr += " ";
185
            xml.putProperty("styles", stylePr);
186
        }
187
        
188
        // Dimensions 
189
        if (dimensions!=null){
190
            String dim = "";
191
            for (int i = 0; i < dimensions.size(); i++) {
192
                dim += (String) dimensions.get(i);
193
                if (i<dimensions.size()-1)
194
                    dim += ",";
195
            }
196
            if (dim.endsWith(","))
197
                    dim += " ";
198
            xml.putProperty("dimensions", dim);
199
        }
200
        
201
        // OnlineResources
202
        Iterator it = onlineResources.keySet().iterator();
203
        String strOnlines = "";
204
        while (it.hasNext()) {
205
                String key = (String) it.next();
206
                String value = (String) onlineResources.get(key);
207
                strOnlines = key+"~##SEP2##~"+value;
208
                if (it.hasNext())
209
                        strOnlines += "~##SEP1##~";
210
        }
211
        xml.putProperty("onlineResources", strOnlines);
212
        
213
        // Queryable
214
        xml.putProperty("queryable", queryable);
215
        
216
        // fixedSize
217
        if (isSizeFixed()) {
218
                xml.putProperty("fixedSize", true);
219
                xml.putProperty("fixedWidth", fixedSize.width);
220
                xml.putProperty("fixedHeight", fixedSize.height);
221
        }
222
        return xml;
223
        }
224

    
225
        /**
226
         * A partir del XMLEntity reproduce la capa.
227
         *
228
         * @param xml XMLEntity
229
         *
230
         * @throws XMLException
231
         * @throws DriverException
232
         * @throws DriverIOException
233
         */
234
        public void setXMLEntity03(XMLEntity xml)
235
                throws XMLException {
236
                super.setXMLEntity(xml);
237
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty(
238
                                        "fullExtent"));
239

    
240
                try {
241
                        host = new URL(xml.getStringProperty("host"));
242
                } catch (MalformedURLException e) {
243
                        throw new XMLException(e);
244
                }
245

    
246
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
247
                layerQuery = xml.getStringProperty("layerQuery");
248
                m_Format = xml.getStringProperty("format");
249
                m_SRS = xml.getStringProperty("srs");
250
        }
251

    
252
        /**
253
         * A partir del XMLEntity reproduce la capa.
254
         *
255
         * @param xml XMLEntity
256
         *
257
         * @throws XMLException
258
         * @throws DriverException
259
         * @throws DriverIOException
260
         */
261
        public void setXMLEntity(XMLEntity xml)
262
                throws XMLException {
263
                super.setXMLEntity(xml);
264
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty(
265
                                        "fullExtent"));
266
                
267
                // Host
268
                try {
269
                        host = new URL(xml.getStringProperty("host"));
270
                } catch (MalformedURLException e) {
271
                        throw new XMLException(e);
272
                }
273

    
274
                // Part of the query that is not the host, or the
275
                // layer names, or other not listed bellow
276
                infoLayerQuery = xml.getStringProperty("infoLayerQuery");
277

    
278
                // Part of the query containing the layer names
279
                layerQuery = xml.getStringProperty("layerQuery");
280
                
281
                // Format
282
                m_Format = xml.getStringProperty("format");
283
                
284
                // SRS
285
                m_SRS = xml.getStringProperty("srs");
286
                
287
                String claseStr = StatusLayerRaster.defaultClass;
288
                if (xml.contains("raster.class")) {
289
                        claseStr = xml.getStringProperty("raster.class");
290
                }
291
                
292
                // Transparency
293
        if (xml.contains("wms_transparency"))
294
            wmsTransparency = xml.getBooleanProperty("wms_transparency");
295
        
296
        // Styles
297
        if (xml.contains("styles")){
298
            styles = new Vector();
299
            String[] stl = xml.getStringProperty("styles").split(",");
300
            
301
            for (int i = 0; i < stl.length; i++) {
302
                    if (stl[i].equals(" "))
303
                            stl[i]="";
304
                styles.add(stl[i]);
305
            }
306
        }
307
        
308
        // Dimensions
309
        if (xml.contains("dimensions")){
310
            dimensions = new Vector();
311
            String[] dims = xml.getStringProperty("dimensions").split(",");
312
            for (int i = 0; i < dims.length; i++){
313
                    if (dims[i].equals(" "))
314
                            dims[i]="";
315
                
316
                dimensions.add(dims[i]);
317
            }
318
        }
319
        
320
        // OnlineResources
321
        if (xml.contains("onlineResources")) {
322
                String[] operations = xml.getStringProperty("onlineResources").split("~##SEP1##~");
323
                for (int i = 0; i < operations.length; i++) {
324
                                String[] resources = operations[i].split("~##SEP2##~");
325
                                if (resources.length==2 && resources[1]!="")
326
                                        onlineResources.put(resources[0], resources[1]);
327
                        }
328
        }
329
        
330
        // Queryable
331
        queryable = true; // let's assume that the layer is queryable by default
332
        if (xml.contains("queryable"))
333
                queryable = xml.getBooleanProperty("queryable");
334
        
335
        // fixedSize
336
        if (xml.contains("fixedSize")) {
337
                fixedSize = new Dimension(xml.getIntProperty("fixedWidth"), 
338
                                                  xml.getIntProperty("fixedHeight"));
339
        }
340
        
341
                if(status!=null)
342
                        status.setXMLEntity(xml, this);
343
                else{
344
                        if(claseStr!=null && !claseStr.equals("")){
345
                                try{
346
                                        Class clase = Class.forName(claseStr);
347
                                        Constructor constr = clase.getConstructor(null);
348
                                        status = (StatusRasterInterface)constr.newInstance(null);
349
                                        if(status!=null)
350
                                                status.setXMLEntity(xml, this);
351
                                }catch(ClassNotFoundException exc){
352
                                        exc.printStackTrace();
353
                                }catch(InstantiationException exc){
354
                                        exc.printStackTrace();
355
                                }catch(IllegalAccessException exc){
356
                                        exc.printStackTrace();
357
                                }catch(NoSuchMethodException exc){
358
                                        exc.printStackTrace();
359
                                }catch(InvocationTargetException exc){
360
                                        exc.printStackTrace();
361
                                }                                        
362
                        }
363
                }
364
                firstLoad = true;
365
        }
366

    
367
        /**
368
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(com.iver.cit.gvsig.fmap.operations.QueriedPoint)
369
         */
370
        public String queryByPoint(Point p) throws DriverException {
371
                try {
372
                        if (queryable)
373
                        {
374
                                //TODO
375
                                // check if there are layers which are not queryable
376
                                ViewPort viewPort = getFMap().getViewPort();
377

    
378
                                Point tiledPoint = new Point((int) p.getX() % maxTilePrintWidth, (int) p.getY() % maxTilePrintHeight);
379
                                Rectangle rect = new Rectangle(0, 0, viewPort.getImageWidth() - 1, viewPort.getImageHeight() - 1);
380
                                Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, rect);
381
                                tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
382
                                int nCols = tiles.getNumCols();
383

    
384
                                int col = (int) p.getX() / maxTilePrintWidth;
385
                                int row = (int) p.getY() / maxTilePrintHeight;
386
                                int tileIndex = (row*nCols) + col;
387
                                
388
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileIndex);
389
                                wmsStatus.setExtent(vp.getExtent());
390
                                wmsStatus.setHeight(vp.getImageHeight());
391
                                wmsStatus.setWidth(vp.getImageWidth());
392
                                wmsStatus.setOnlineResource((String) onlineResources.get("GetFeatureInfo"));
393
                                return new String(getDriver()
394
                                                .getFeatureInfo(wmsStatus, (int) tiledPoint.getX(), (int) tiledPoint.getY(), Integer.MAX_VALUE));
395
                        }
396
                        else
397
                        {
398
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
399
                                                PluginServices.getText(this, "wms_not_queryable"));
400
                                return "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><info></info>";
401
                        }
402
                } catch (WMSException  e) {
403
                        return "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><exception>" +
404
                        e.getMessage() + "</exception>";
405
                } catch (ValidationException e) {
406
                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
407
                } catch (UnsupportedVersionException e) {
408
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
409
                } catch (IOException e) {
410
                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
411
                } catch (NoninvertibleTransformException e) {
412
                        NotificationManager.addError("NotinvertibleTransform", e);
413
                }
414
                return null;
415
        }
416

    
417
        /**
418
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent()
419
         */
420
        public Rectangle2D getFullExtent() {
421
                return fullExtent;
422
        }
423

    
424
        /**
425
         * 
426
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#draw(java.awt.image.BufferedImage,
427
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
428
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
429
         */
430
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
431
                        Cancellable cancel,double scale) throws DriverException {
432
                
433
                if (isWithinScale(scale)){
434
                        Point2D p = viewPort.getOffset();
435
                        // p will be (0, 0) when drawing a view or other when painting onto
436
                        // the Layout.
437
                        
438
                        if (isSizeFixed()) {
439
                                // This condition handles those situations in which the server can
440
                                // only give static extent and resolution maps despite we need
441
                                // a specific BBOX and pixel WIDTH and HEIGHT
442
                                drawFixedSize(g, viewPort, cancel);
443

    
444
                        } else {
445
                                Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), viewPort.getImageWidth() - 1, viewPort.getImageHeight() - 1);
446
                                Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, r);
447
                                tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
448
                                for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
449
                                        // drawing part
450
                                        try {
451
                                                ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
452
                                                drawTile(g, vp, cancel);
453
                                        } catch (NoninvertibleTransformException e) {
454
                                                e.printStackTrace();
455
                                        }
456
                                }
457
                        }
458
                }
459
                Runtime r = Runtime.getRuntime();
460
                long mem = r.totalMemory() - r.freeMemory();
461
                System.err.println("Memoria total: " + (mem / 1024) +"KB");
462
        }
463
        
464
        private void drawFixedSize(Graphics2D g, ViewPort vp, Cancellable cancel) throws DriverException {
465
                // This is the extent that will be requested
466
                Rectangle2D bBox = getFullExtent();
467
                
468
                try {                        
469
                        wmsStatus.setExtent( bBox );
470
                        wmsStatus.setFormat( m_Format );
471
                        wmsStatus.setHeight( fixedSize.height );
472
                        wmsStatus.setWidth( fixedSize.width );
473
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
474
                        wmsStatus.setSrs(m_SRS);
475
                        wmsStatus.setStyles(styles);
476
                        wmsStatus.setDimensions(dimensions);
477
                        wmsStatus.setTransparency(wmsTransparency);
478
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
479
                        
480
                        File f = getDriver().getMap(wmsStatus);
481
                        String nameWorldFile = f.getPath() + getExtensionWorldFile();
482
                        com.iver.andami.Utilities.createTemp(nameWorldFile, this.getDataWorldFile(bBox, fixedSize));
483
                        
484
                        if(status!=null && firstLoad){
485
                                status.applyStatus(this);
486
                                firstLoad = false;
487
                        }
488
                        
489
                        // And finally, obtain the extent intersecting the view and the BBox
490
                        // to draw to.
491
                        Rectangle2D extent = new Rectangle2D.Double();
492
                        Rectangle2D.intersect(vp.getAdjustedExtent(), bBox, extent);
493
                        
494
                        ViewPortData vpData = new ViewPortData(
495
                                vp.getProjection(), new Extent(extent), fixedSize );
496
                        vpData.setMat(vp.getAffineTransform());
497

    
498
                        rasterProcess(g, vpData, f);
499
                        
500
                } catch (ValidationException e) {
501
                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
502
                } catch (UnsupportedVersionException e) {
503
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
504
                } catch (IOException e) {
505
                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
506
                } catch (WMSException e) {
507
            JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
508
                        this.setVisible(false);
509
                }
510
                
511
                
512
        }
513
        
514
        /**
515
         *
516
         * This is the method used to draw a tile in a WMS mosaic layer.
517
         */
518
        private void drawTile(Graphics2D g, ViewPort vp, Cancellable cancel) throws DriverException {
519

    
520
                // Compute the query geometry 
521
                // 1. Check if it is within borders
522
                Rectangle2D extent = getFullExtent();
523
        if ((vp.getExtent().getMinX() > extent.getMaxX()) ||
524
                (vp.getExtent().getMinY() > extent.getMaxY()) ||
525
                (vp.getExtent().getMaxX() < extent.getMinX()) ||
526
                (vp.getExtent().getMaxY() < extent.getMinY())) {
527
            return;
528
        }
529
        
530
        // 2. Compute extent to be requested.
531
        Rectangle2D bBox = new Rectangle2D.Double();
532
        Rectangle2D.intersect(vp.getExtent(), extent, bBox);
533
        
534
        // 3. Compute size in pixels
535
        double scalex = vp.getAffineTransform().getScaleX(); 
536
        double scaley = vp.getAffineTransform().getScaleY(); 
537
        int wImg = (int) Math.ceil(Math.abs(bBox.getWidth() * scalex) + 1);
538
        int hImg = (int) Math.ceil(Math.abs(bBox.getHeight() * scaley) + 1);
539
        Dimension sz = new Dimension(wImg, hImg);
540

    
541
        if ((wImg <= 0) || (hImg <= 0)) {
542
            return;
543
        }
544
                
545
                try {                        
546
                        wmsStatus.setExtent( bBox );
547
                        wmsStatus.setFormat(m_Format);
548
                        wmsStatus.setHeight( hImg );
549
                        wmsStatus.setWidth( wImg );
550
                        wmsStatus.setLayerNames(Utilities.createVector(layerQuery,","));
551
                        wmsStatus.setSrs(m_SRS);
552
                        wmsStatus.setStyles(styles);
553
                        wmsStatus.setDimensions(dimensions);
554
                        wmsStatus.setTransparency(wmsTransparency);
555
                        wmsStatus.setOnlineResource((String) onlineResources.get("GetMap"));
556
                        
557
                        File f = getDriver().getMap(wmsStatus);
558
                        String nameWordFile = f.getPath() + getExtensionWorldFile();
559
                        com.iver.andami.Utilities.createTemp(nameWordFile, this.getDataWorldFile(bBox, sz));
560
                        
561
                        if(status!=null && firstLoad){
562
                                status.applyStatus(this);
563
                                firstLoad = false;
564
                        }
565
                        ViewPortData vpData = new ViewPortData(
566
                                vp.getProjection(), new Extent(bBox), sz );
567
                        vpData.setMat(vp.getAffineTransform());
568

    
569
                        rasterProcess(g, vpData, f);
570
                        
571
                } catch (ValidationException e) {
572
                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
573
                } catch (UnsupportedVersionException e) {
574
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
575
                } catch (IOException e) {
576
                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
577
                } catch (WMSException e) {
578
            JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
579
                        this.setVisible(false);
580
                }
581
                
582
        }
583

    
584
        /**
585
         * Obtiene la extensi�n del fichero de georreferenciaci�n
586
         * @return String con la extensi�n del fichero de georreferenciaci�n dependiendo
587
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld 
588
         */
589
        private String getExtensionWorldFile(){
590
                String extWorldFile = ".wld";
591
            if(m_Format.equals("image/tif") || m_Format.equals("image/tiff"))
592
                    extWorldFile = ".tfw";
593
            if(m_Format.equals("image/jpeg"))
594
                    extWorldFile = ".jpgw";
595
            return extWorldFile;
596
        }
597
        
598
        /**
599
         * Calcula el contenido del fichero de georreferenciaci�n de una imagen.
600
         * @param bBox Tama�o y posici�n de la imagen (en coordenadas de usuario)
601
         * @param sz Tama�o de la imagen en p�xeles.
602
         * @return el 'WorldFile', como String.
603
         * @throws IOException
604
         */
605
        public String getDataWorldFile(Rectangle2D bBox, Dimension sz) throws IOException {
606
                StringBuffer data = new StringBuffer();
607
            data.append((bBox.getMaxX() - bBox.getMinX())/(sz.getWidth() - 1)+"\n");
608
            data.append("0.0\n");
609
            data.append("0.0\n");
610
            data.append((bBox.getMaxY() - bBox.getMinY())/(sz.getHeight() - 1)+"\n");
611
            data.append(""+bBox.getMinX()+"\n");
612
            data.append(""+bBox.getMinY()+"\n");
613
            return data.toString();
614
        }
615
                
616
        /**
617
         * Dibuja una im�gen usando PxRaster
618
         * @param g        Graphics2D en el que hay que dibujar.
619
         * @param vpData Par�metros de visualizaci�n
620
         * @param file La im�gen en cuesti�n.
621
         */
622
        private void rasterProcess(Graphics2D g, ViewPortData vpData, File file) {
623
                
624
                //Creamos el PxRaster        
625
                rasterFile = new GdalFile(vpData.getProjection(), file.getAbsolutePath());
626
                raster = new PxRaster(rasterFile, null, rasterFile.getExtent());
627
                
628
                //Recuperamos la pila de filtros si ya hubiese sido cargado antes
629
                if(this.filterStack!=null)
630
                        raster.filterStack = this.filterStack;
631
                
632
                raster.setTransparency(false);
633
                                                
634
                //Asignamos transparencia y orden de bandas
635
                if(this.transparency==-1 && !firstLoad);
636
                else
637
                        raster.setTransparency(this.transparency);
638
                
639
                raster.setBand(GeoRasterFile.RED_BAND,rband);
640
                raster.setBand(GeoRasterFile.GREEN_BAND, gband);
641
                raster.setBand(GeoRasterFile.BLUE_BAND, bband);
642
        
643
                //Despues del primer pxRaster asignamos el stackManager guardado para los siguientes.
644
                //Con esto conseguimos asignar los cambios que se hayan producido desde el cuadro de 
645
                //propiedades cuando creamos un nuevo pxRaster
646
                if(this.stackManager != null)
647
                        raster.setStackManager(this.stackManager); 
648

    
649
                raster.draw(g, vpData);
650
                
651
                //En el primer pxRaster de una imagen obtenemos el Stack Manager para poder modificarlo
652
                //si queremos desde las propiedades
653
                
654
                if(this.stackManager == null)
655
                        this.stackManager = raster.getStackManager(); 
656
                
657
                if(this.filterStack == null)
658
                        this.filterStack = raster.filterStack;
659
        }
660
        
661
        /**
662
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D,
663
         *                 com.iver.cit.gvsig.fmap.ViewPort,
664
         *                 com.iver.cit.gvsig.fmap.operations.Cancellable)
665
         */
666
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale)
667
                throws DriverException {
668
                if (isVisible() && isWithinScale(scale)){        
669
                isPrinting = true;
670
                if (!mustTilePrint) {
671
                        draw(null, g, viewPort, cancel,scale);
672
                } else {
673
                // Para no pedir imagenes demasiado grandes, vamos
674
                // a hacer lo mismo que hace EcwFile: chunkear.
675
                // Llamamos a drawView con cuadraditos m�s peque�os
676
                // del BufferedImage ni caso, cuando se imprime viene con null
677
                        
678
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipRect());
679
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
680
                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
681
                            // Parte que dibuja
682
                            try {
683
                                ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
684
                                draw(null, g, vp, cancel,scale);
685
                                } catch (NoninvertibleTransformException e) {
686
                                        e.printStackTrace();
687
                                }
688
                }
689
                }
690
            isPrinting = false;
691
                }
692
        }
693
        
694
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale)
695
                throws DriverException {
696
                draw(null, g, viewPort, cancel,scale);
697
        }
698

    
699
        /**
700
         * Devuelve el FMapWMSDriver.
701
         *
702
         * @return FMapWMSDriver
703
         *
704
         * @throws IllegalStateException
705
         * @throws ValidationException
706
         * @throws UnsupportedVersionException
707
         * @throws IOException
708
         */
709
        private FMapWMSDriver getDriver()
710
                throws IllegalStateException, ValidationException, 
711
                        UnsupportedVersionException, IOException {
712
                if (wms == null) {
713
                        //wmsClient = WMSClientFactory.getClient(host);
714
                        wms = new FMapWMSDriver();
715
            wms.createClient(host);
716
            
717
                }
718

    
719
                return wms;
720
        }
721
        
722
        /**
723
         * Devuelve el FMapWMSDriver.
724
         *
725
         * @return FMapWMSDriver
726
         *
727
         * @throws IllegalStateException
728
         * @throws ValidationException
729
         * @throws UnsupportedVersionException
730
         * @throws IOException
731
         */
732
        public void setDriver(FMapWMSDriver drv) {
733
                wms = drv;
734
        }
735

    
736
        /**
737
         * Devuelve el URL.
738
         *
739
         * @return URL.
740
         */
741
        public URL getHost() {
742
                return host;
743
        }
744

    
745
        /**
746
         * Inserta el URL.
747
         *
748
         * @param host URL.
749
         */
750
        public void setHost(URL host) {
751
                this.host = host;
752
        }
753

    
754
        /**
755
         * Devuelve la informaci�n de la consulta.
756
         *
757
         * @return String.
758
         */
759
        public String getInfoLayerQuery() {
760
                return infoLayerQuery;
761
        }
762

    
763
        /**
764
         * Inserta la informaci�n de la consulta.
765
         *
766
         * @param infoLayerQuery String.
767
         */
768
        public void setInfoLayerQuery(String infoLayerQuery) {
769
                this.infoLayerQuery = infoLayerQuery;
770
        }
771

    
772
        /**
773
         * Devuelve la consulta.
774
         *
775
         * @return String.
776
         */
777
        public String getLayerQuery() {
778
                return layerQuery;
779
        }
780

    
781
        /**
782
         * Inserta la consulta.
783
         *
784
         * @param layerQuery consulta.
785
         */
786
        public void setLayerQuery(String layerQuery) {
787
                this.layerQuery = layerQuery;
788
        }
789

    
790
        /**
791
         * Devuelve el formato.
792
         *
793
         * @return Formato.
794
         */
795
        public String getFormat() {
796
                return m_Format;
797
        }
798

    
799
        /**
800
         * Inserta el formato.
801
         *
802
         * @param format Formato.
803
         */
804
        public void setFormat(String format) {
805
                m_Format = format;
806
        }
807

    
808
        /**
809
         * Devuelve el SRS.
810
         *
811
         * @return SRS.
812
         */
813
        public String getSRS() {
814
                return m_SRS;
815
        }
816

    
817
        /**
818
         * Inserta el SRS.
819
         *
820
         * @param m_srs SRS.
821
         */
822
        public void setSRS(String m_srs) {
823
                m_SRS = m_srs;
824
        }
825

    
826
        /**
827
         * Inserta la extensi�n total de la capa.
828
         *
829
         * @param fullExtent Rect�ngulo.
830
         */
831
        public void setFullExtent(Rectangle2D fullExtent) {
832
                this.fullExtent = fullExtent;
833
        }
834
        
835
        public HashMap getProperties() {
836
                HashMap info = new HashMap();
837
        String[] layerNames = getLayerQuery().split(",");
838
        Vector layers = new Vector(layerNames.length);
839
        try {
840
            if(getDriver().connect()){
841
                for (int i = 0; i < layerNames.length; i++) {
842
                    layers.add(i, wms.getLayer(layerNames[i]));
843
                }
844
                info.put("name", getName());
845
                info.put("selectedLayers", layers);
846
                info.put("host", getHost());
847
                info.put("srs", getSRS());
848
                info.put("format", getFormat());
849
                info.put("wmsTransparency", new Boolean(wmsTransparency));
850
                info.put("styles", styles);
851
                info.put("dimensions", dimensions);
852
                info.put("fixedSize", fixedSize);
853
                return info;
854
            }
855
        } catch (Exception e) {
856
            e.printStackTrace();
857
        }
858
        return null;
859
        }
860
        
861
        /**
862
         * Asignar el estado del raster
863
         * @param status
864
         */
865
        public void setStatus(StatusRasterInterface status){
866
                this.status = status;
867
        }
868
        
869
        /**
870
         * Obtiene el estado del raster
871
         * @return
872
         */
873
        public StatusRasterInterface getStatus(){
874
                return this.status;
875
        }
876
        
877
        /* (non-Javadoc)
878
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getAttributes()
879
         */
880
        public ArrayList getAttributes() {
881
                if(rasterFile != null){
882
                        ArrayList attr = new ArrayList();
883
/*                        String dataType = "Byte";
884
                        if (rasterFile.getDataType() == DataBuffer.TYPE_BYTE) dataType = "Byte";
885
                        else if (rasterFile.getDataType() == DataBuffer.TYPE_SHORT)
886
                                dataType = "Short";
887
                        else if (rasterFile.getDataType() == DataBuffer.TYPE_USHORT)
888
                                dataType = "Unsigned Short";
889
                        else if (rasterFile.getDataType() == DataBuffer.TYPE_INT)
890
                                dataType = "Integer";
891
                        else if (rasterFile.getDataType() == DataBuffer.TYPE_FLOAT)
892
                                dataType = "Float";
893
                        else if (rasterFile.getDataType() == DataBuffer.TYPE_DOUBLE)
894
                                dataType = "Double";
895
                        else
896
                                dataType = "Unknown";
897
*/
898
                        Object [][] a = {
899
                                {"Filename",rasterFile.getName().substring(rasterFile.getName().lastIndexOf("/")+1, rasterFile.getName().length())},
900
                                {"Filesize",new Long(rasterFile.getFileSize())},
901
                                {"Width",new Integer(rasterFile.getWidth())},
902
                                {"Height", new Integer(rasterFile.getHeight())},
903
                                {"Bands", new Integer(rasterFile.getBandCount())}
904
                                //{"BandDataType", dataType}
905
                        };
906
                        for (int i=0; i<a.length; i++){
907
                                System.out.println("===> "+a[i][0]+" "+a[i][1]);
908
                                attr.add(a[i]);
909
                        }
910
                        return attr;
911
                }
912
                return  null;
913
        }
914
        
915
        /* (non-Javadoc)
916
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getFilterStack()
917
         */
918
        public RasterFilterStack getFilterStack() {
919
                if(raster!=null)
920
                        return raster.filterStack;
921
                return null;
922
        }
923
        /* (non-Javadoc)
924
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getHeight()
925
         */
926
        public double getHeight() {
927
                if(getGeoRasterFile() != null)
928
                        return getGeoRasterFile().getHeight();
929
        return 0;
930
        }
931
        
932
        /* (non-Javadoc)
933
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxX()
934
         */
935
        public double getMaxX() {
936
                if(getPxRaster() != null)
937
                        return getPxRaster().getExtent().getMax().getX();
938
        return 0;
939
        }
940
        
941
        /* (non-Javadoc)
942
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxY()
943
         */
944
        public double getMaxY() {
945
                if(getPxRaster() != null)
946
                        return getPxRaster().getExtent().getMax().getY();
947
        return 0;
948
        }
949
        
950
        /* (non-Javadoc)
951
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinX()
952
         */
953
        public double getMinX() {
954
                if(getPxRaster() != null)
955
                        return getPxRaster().getExtent().getMin().getX();
956
        return 0;
957
        }
958
        
959
        /* (non-Javadoc)
960
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinY()
961
         */
962
        public double getMinY() {
963
                if(getPxRaster() != null)
964
                        return getPxRaster().getExtent().getMin().getY();
965
        return 0;
966
        }
967
        /* (non-Javadoc)
968
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getPixel(double, double)
969
         */
970
        public int[] getPixel(double wcx, double wcy) {
971
                if(getPxRaster() != null)
972
                        return getPxRaster().getPixel(wcx, wcy);
973
        return null;
974
        }
975
        /* (non-Javadoc)
976
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getSource()
977
         */
978
        public RasterAdapter getSource() {
979
                return null;
980
        }
981
        /* (non-Javadoc)
982
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getWidth()
983
         */
984
        public double getWidth() {
985
                if(getGeoRasterFile() != null)
986
                        return getGeoRasterFile().getWidth();
987
        return 0;
988
        }
989
        /* (non-Javadoc)
990
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setBand(int, int)
991
         */
992
        public void setBand(int flag, int nBand) {
993
                switch(flag){
994
                case GeoRasterFile.RED_BAND:setBandR(nBand);break;
995
                case GeoRasterFile.GREEN_BAND:setBandG(nBand);break;
996
                case GeoRasterFile.BLUE_BAND:setBandB(nBand);break;
997
                }
998
        }
999
        /* (non-Javadoc)
1000
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setFilterStack(org.cresques.io.raster.RasterFilterStack)
1001
         */
1002
        public void setFilterStack(RasterFilterStack stack) {
1003
                this.filterStack = stack;
1004
        }
1005
        /* (non-Javadoc)
1006
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPos(int, int)
1007
         */
1008
        public void setPos(int x, int y) {
1009
                this.posX = x;
1010
                this.posY = y;
1011
        }
1012
        
1013
        /* (non-Javadoc)
1014
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPosWC(double, double)
1015
         */
1016
        public void setPosWC(double x, double y) {
1017
                this.posXWC = x;
1018
                this.posYWC = y;
1019
        }
1020
        
1021
        /* (non-Javadoc)
1022
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setRGB(int, int, int)
1023
         */
1024
        public void setRGB(int r, int g, int b) {
1025
                this.r = r;
1026
                this.g = g;
1027
                this.b = b;
1028
        }
1029
        /* (non-Javadoc)
1030
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setSource(com.iver.cit.gvsig.fmap.layers.RasterAdapter)
1031
         */
1032
        public void setSource(RasterAdapter ra) {
1033
        }
1034
        /**
1035
         * @return Returns the raster.
1036
         */
1037
        public PxRaster getPxRaster() {
1038
                return raster;
1039
        }
1040
        /**
1041
         * @return Returns the rasterFile.
1042
         */
1043
        public GeoRasterFile getGeoRasterFile() {
1044
                return rasterFile;
1045
        }
1046
        
1047
        public void setTransparency(int trans) {
1048
                this.transparency = trans;
1049
        }
1050
        
1051
        /**
1052
         * Sets the R-band.
1053
         * 
1054
         * Asigna la banda R.
1055
         * @param r
1056
         */
1057
        public void setBandR(int r){
1058
                this.rband = r;
1059
        }
1060
        
1061
        /**
1062
         * Sets the G-band.
1063
         * 
1064
         * Asigna la banda G
1065
         * @param g
1066
         */
1067
        public void setBandG(int g){
1068
                this.gband = g;
1069
        }
1070
        
1071
        /**
1072
         * Sets the B-band.
1073
         * 
1074
         * Asigna la banda B
1075
         * @param b
1076
         */
1077
        public void setBandB(int b){
1078
                this.bband = b;
1079
        }
1080

    
1081
    /**
1082
     * @return Returns the wmsTransparency.
1083
     */
1084
    public boolean isWmsTransparent() {
1085
        return wmsTransparency;
1086
    }
1087

    
1088
    /**
1089
     * @param wmsTransparency The wmsTransparency to set.
1090
     */
1091
    public void setWmsTransparency(boolean wmsTransparency) {
1092
        this.wmsTransparency = wmsTransparency;
1093
    }
1094

    
1095
     /**
1096
     * @param styles
1097
     */
1098
    public void setStyles(Vector styles) {
1099
            //laura:
1100
            //layer query is built with the layer in reverse order
1101
            // so here we build the styles upside-down.
1102
            if (styles != null)
1103
            {
1104
                    this.styles = new Vector();
1105
                    for(int i = styles.size()-1; i>=0; i--)
1106
                    {
1107
                            this.styles.add(styles.elementAt(i));
1108
                    }
1109
            }
1110
    }
1111
    
1112
    /**
1113
     * Sets the dimension vector that is a list of key-value pairs containing
1114
     * the name of the dimension and the value for it
1115
     * @param dimensions
1116
     */
1117
    public void setDimensions(Vector dimensions) {
1118
        this.dimensions = dimensions;
1119
    }
1120

    
1121
    /**
1122
     * Sets the set of URLs that should be accessed for each operation performed
1123
     * to the server.
1124
     * 
1125
     * @param onlineResources
1126
     */
1127
        public void setOnlineResources(Hashtable onlineResources) {
1128
                this.onlineResources = onlineResources;
1129
        }
1130
        
1131
        /**
1132
         * When a server is not fully featured and it only can serve constant map
1133
         * sizes this value must be set. It expresses the size in pixels (width, height)
1134
         * that the map will be requested.
1135
         * @param Dimension sz
1136
         */
1137
        public void setFixedSize(Dimension sz) {
1138
                fixedSize = sz;
1139
        }
1140
        
1141
        /**
1142
         * Tells whether if this layer must deal with the server with the constant-size
1143
         * limitations or not.
1144
         * @return boolean.
1145
         */
1146
        private boolean isSizeFixed() {
1147
                return fixedSize != null && fixedSize.getWidth() > 0 && fixedSize.getHeight() > 0;
1148
        }
1149

    
1150
        /**
1151
         * If it is true, this layer accepts GetFeatureInfo operations. This WMS operations
1152
         * maps to FMap's infoByPoint(p) operation.
1153
         * @param b
1154
         */
1155
        public void setQueryable(boolean b) {
1156
                queryable = b;
1157
        }
1158
        
1159
}