Statistics
| Revision:

root / branches / v05 / extensions / extWMS / src / com / iver / cit / gvsig / fmap / layers / FLyrWMS.java @ 4170

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
         * This is the method used to draw a tile in a WMS mosaic layer.
516
         */
517
        private void drawTile(Graphics2D g, ViewPort vp, Cancellable cancel) throws DriverException {
518

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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