Statistics
| Revision:

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

History | View | Annotate | Download (33.1 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
                        //e.printStackTrace();
414
                }
415
                return null;
416
        }
417

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

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

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

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

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

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

    
561
                        rasterProcess(g, vpData, f);
562
                        
563
                } catch (ValidationException e) {
564
                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
565
                } catch (UnsupportedVersionException e) {
566
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
567
                } catch (IOException e) {
568
                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
569
                } catch (WMSException e) {
570
            JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
571
                        this.setVisible(false);
572
                }
573
                
574
        }
575

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

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

    
691
        /**
692
         * Devuelve el FMapWMSDriver.
693
         *
694
         * @return FMapWMSDriver
695
         *
696
         * @throws IllegalStateException
697
         * @throws ValidationException
698
         * @throws UnsupportedVersionException
699
         * @throws IOException
700
         */
701
        private FMapWMSDriver getDriver()
702
                throws IllegalStateException, ValidationException, 
703
                        UnsupportedVersionException, IOException {
704
                if (wms == null) {
705
                        //wmsClient = WMSClientFactory.getClient(host);
706
                        wms = new FMapWMSDriver();
707
            wms.createClient(host);
708
            
709
                }
710

    
711
                return wms;
712
        }
713
        
714
        /**
715
         * Devuelve el FMapWMSDriver.
716
         *
717
         * @return FMapWMSDriver
718
         *
719
         * @throws IllegalStateException
720
         * @throws ValidationException
721
         * @throws UnsupportedVersionException
722
         * @throws IOException
723
         */
724
        public void setDriver(FMapWMSDriver drv) {
725
                wms = drv;
726
        }
727

    
728
        /**
729
         * Devuelve el URL.
730
         *
731
         * @return URL.
732
         */
733
        public URL getHost() {
734
                return host;
735
        }
736

    
737
        /**
738
         * Inserta el URL.
739
         *
740
         * @param host URL.
741
         */
742
        public void setHost(URL host) {
743
                this.host = host;
744
        }
745

    
746
        /**
747
         * Devuelve la informaci�n de la consulta.
748
         *
749
         * @return String.
750
         */
751
        public String getInfoLayerQuery() {
752
                return infoLayerQuery;
753
        }
754

    
755
        /**
756
         * Inserta la informaci�n de la consulta.
757
         *
758
         * @param infoLayerQuery String.
759
         */
760
        public void setInfoLayerQuery(String infoLayerQuery) {
761
                this.infoLayerQuery = infoLayerQuery;
762
        }
763

    
764
        /**
765
         * Devuelve la consulta.
766
         *
767
         * @return String.
768
         */
769
        public String getLayerQuery() {
770
                return layerQuery;
771
        }
772

    
773
        /**
774
         * Inserta la consulta.
775
         *
776
         * @param layerQuery consulta.
777
         */
778
        public void setLayerQuery(String layerQuery) {
779
                this.layerQuery = layerQuery;
780
        }
781

    
782
        /**
783
         * Devuelve el formato.
784
         *
785
         * @return Formato.
786
         */
787
        public String getFormat() {
788
                return m_Format;
789
        }
790

    
791
        /**
792
         * Inserta el formato.
793
         *
794
         * @param format Formato.
795
         */
796
        public void setFormat(String format) {
797
                m_Format = format;
798
        }
799

    
800
        /**
801
         * Devuelve el SRS.
802
         *
803
         * @return SRS.
804
         */
805
        public String getSRS() {
806
                return m_SRS;
807
        }
808

    
809
        /**
810
         * Inserta el SRS.
811
         *
812
         * @param m_srs SRS.
813
         */
814
        public void setSRS(String m_srs) {
815
                m_SRS = m_srs;
816
        }
817

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

    
1073
    /**
1074
     * @return Returns the wmsTransparency.
1075
     */
1076
    public boolean isWmsTransparent() {
1077
        return wmsTransparency;
1078
    }
1079

    
1080
    /**
1081
     * @param wmsTransparency The wmsTransparency to set.
1082
     */
1083
    public void setWmsTransparency(boolean wmsTransparency) {
1084
        this.wmsTransparency = wmsTransparency;
1085
    }
1086

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

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

    
1142
        /**
1143
         * If it is true, this layer accepts GetFeatureInfo operations. This WMS operations
1144
         * maps to FMap's infoByPoint(p) operation.
1145
         * @param b
1146
         */
1147
        public void setQueryable(boolean b) {
1148
                queryable = b;
1149
        }
1150
        
1151
}