Statistics
| Revision:

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

History | View | Annotate | Download (27.6 KB)

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

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

    
64
import javax.swing.JOptionPane;
65

    
66
import org.cresques.filter.RasterFilterStack;
67
import org.cresques.filter.RasterFilterStackManager;
68
import org.cresques.geo.ViewPortData;
69
import org.cresques.io.GdalFile;
70
import org.cresques.io.GeoRasterFile;
71
import org.cresques.px.Extent;
72
import org.cresques.px.PxRaster;
73
import org.exolab.castor.xml.ValidationException;
74
import org.gvsig.remoteClient.wcs.WCSStatus;
75
import org.gvsig.remoteClient.wms.ICancellable;
76

    
77
import com.iver.andami.PluginServices;
78
import com.iver.cit.gvsig.fmap.DriverException;
79
import com.iver.cit.gvsig.fmap.ViewPort;
80
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
81
import com.iver.cit.gvsig.fmap.drivers.UnsupportedVersionException;
82
import com.iver.cit.gvsig.fmap.drivers.wcs.FMapWCSDriver;
83
import com.iver.cit.gvsig.fmap.drivers.wcs.FMapWCSDriverFactory;
84
import com.iver.cit.gvsig.fmap.drivers.wcs.WCSException;
85
import com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint;
86
import com.iver.cit.gvsig.fmap.layers.layerOperations.StringXMLItem;
87
import com.iver.cit.gvsig.fmap.layers.layerOperations.XMLItem;
88
import com.iver.utiles.StringUtilities;
89
import com.iver.utiles.XMLEntity;
90
import com.iver.utiles.swing.threads.Cancellable;
91

    
92

    
93
/**
94
 * Class for the WCS layer.
95
 *
96
 * Capa para el WCS.
97
 *
98
 * @author jaume - jaume.dominguez@iver.es
99
 */
100
public class FLyrWCS extends FLyrDefault implements RasterOperations, InfoByPoint{
101
        private FMapWCSDriver wcs = null;
102

    
103
        private URL                                                 host;
104
        private String                                                coverageName;
105
        private Rectangle2D                                        fullExtent;
106
        private String                                                format;
107
        private String                                                srs;
108
        private String                                                time;
109
        private String                                                parameter;
110
        private Point2D                                                maxRes;
111
        private Hashtable                                         onlineResources = new Hashtable();
112

    
113
        private WCSStatus                                        wcsStatus = new WCSStatus();
114

    
115
        private StatusRasterInterface                status = null;
116
        private int                                                 posX = 0, posY = 0;
117
        private double                                                 posXWC = 0, posYWC = 0;
118
        private int                                                 r = 0, g = 0, b = 0;
119
        private RasterFilterStackManager        stackManager = null;
120
        private PxRaster                                         raster = null;
121
        private GeoRasterFile                                 rasterFile = null;
122
        private RasterFilterStack                         filterStack;
123
        private boolean                                         firstLoad = false;
124
        private int                                                        rband = 0, gband = 1, bband = 2;
125
        private VisualStatus                                visualStatus = new VisualStatus();
126

    
127
        private boolean                                         mustTileDraw = false;
128
        private int                                                 maxTileDrawWidth  = 1023;
129
        private int                                                        maxTileDrawHeight = 1023;
130
        private int                                                 maxTilePrintWidth  = 250;
131
        private int                                                        maxTilePrintHeight = 250;
132

    
133
        private FMapWCSDriver driver;
134

    
135
        private class MyCancellable implements ICancellable
136
        {
137

    
138
                private Cancellable original;
139
                public MyCancellable(Cancellable cancelOriginal)
140
                {
141
                        this.original = cancelOriginal;
142
                }
143
                public boolean isCanceled() {
144
                        return original.isCanceled();
145
                }
146

    
147
        }
148
        public FLyrWCS(){
149
                super();
150
        }
151

    
152
        public FLyrWCS(Map args) throws DriverIOException{
153
                String host = (String)args.get("HOST");
154
                String sCoverage = (String) args.get((String) "COVERAGE");
155

    
156
                try {
157
                        this.setHost(new URL(host));
158
                } catch (MalformedURLException e) {
159
                        //e.printStackTrace();
160
                        throw new DriverIOException("Malformed host URL, '" + host + "' (" + e.toString() + ").");
161
                }
162
                WCSLayer wcsNode = null;
163
                try{
164
                        if (!getDriver().connect(null)){
165
                                throw new DriverIOException("Can't connect to host '" + host + "'.");
166
                        }
167
                        wcsNode = getDriver().getLayer(sCoverage);
168
                }catch(Exception e){
169
                        throw new DriverIOException("Can't connect to host '" + host + "'.");
170
                }
171

    
172
                if (wcsNode == null){
173
                        throw new DriverIOException("The server '" + host + "' doesn't has the coverage '" + sCoverage + "'.");
174
                }
175

    
176
                try{
177
                        this.setFullExtent(getDriver().getFullExtent(sCoverage,
178
                                        (String) args.get((String) "CRS")));
179
                        this.setFormat((String) args.get((String) "FORMAT"));
180
                        this.setParameter("BANDS=" + (String) args.get((String) "BANDS"));
181
                        this.setSRS((String) args.get((String) "CRS"));
182
                        this.setName(sCoverage);
183
                        this.setCoverageName(sCoverage);
184
                }catch (Exception e){
185
                        throw new DriverIOException("The server '" + host + "' is not able to load the coverage '" + sCoverage + "'.");
186
                }
187

    
188
        }
189

    
190
        /**
191
         * Clase que contiene los datos de visualizaci?n de WMS.
192
         * @author Nacho Brodin (brodin_ign@gva.es)
193
         */
194
        private class VisualStatus {
195
                /**
196
                 * Ancho y alto de la imagen o del conjunto de tiles si los tiene. Coincide con
197
                 * el ancho y alto del viewPort
198
                 */
199
                private        int                                                        width = 0, height = 0;
200
                private double                                                minX = 0D, minY = 0D, maxX = 0D, maxY = 0D;
201
                private int                                                 bandCount = 0;
202
                private int                                                        dataType = DataBuffer.TYPE_UNDEFINED;
203
        }
204

    
205
        /*
206
         *  (non-Javadoc)
207
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setRGB(int, int, int)
208
         */
209
        public void setRGB(int r, int g, int b) {
210
                this.r = r;
211
                this.g = g;
212
                this.b = b;
213
        }
214

    
215
        /*
216
         *  (non-Javadoc)
217
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getFilterStack()
218
         */
219
        public RasterFilterStack getFilterStack() {
220
                if(raster!=null)
221
                        return raster.filterStack;
222
                return null;
223
        }
224

    
225
        /*
226
         *  (non-Javadoc)
227
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setFilterStack(org.cresques.io.raster.RasterFilterStack)
228
         */
229
        public void setFilterStack(RasterFilterStack stack) {
230
                this.filterStack = stack;
231
        }
232

    
233
        /*
234
         *  (non-Javadoc)
235
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getSource()
236
         */
237
        public RasterAdapter getSource() {
238
                return null;
239
        }
240

    
241
        /*
242
         *  (non-Javadoc)
243
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setSource(com.iver.cit.gvsig.fmap.layers.RasterAdapter)
244
         */
245
        public void setSource(RasterAdapter ra) {
246
        }
247

    
248
        /*
249
         *  (non-Javadoc)
250
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPos(int, int)
251
         */
252
        public void setPos(int x, int y) {
253
                this.posX = x;
254
                this.posY = y;
255
        }
256

    
257
        /*
258
         *  (non-Javadoc)
259
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPosWC(double, double)
260
         */
261
        public void setPosWC(double x, double y) {
262
                this.posXWC = x;
263
                this.posYWC = y;
264
        }
265

    
266
        /*
267
         *  (non-Javadoc)
268
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getPixel(double, double)
269
         */
270
        public int[] getPixel(double wcx, double wcy) {
271
                if(getPxRaster() != null)
272
                        return getPxRaster().getPixel(wcx, wcy);
273
        return null;
274
        }
275

    
276
        /*
277
         *  (non-Javadoc)
278
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setBand(int, int)
279
         */
280
        public void setBand(int flag, int nBand) {
281
                switch(flag){
282
                case GeoRasterFile.RED_BAND:setBandR(nBand);break;
283
                case GeoRasterFile.GREEN_BAND:setBandG(nBand);break;
284
                case GeoRasterFile.BLUE_BAND:setBandB(nBand);break;
285
                }
286
        }
287

    
288
        /**
289
         * Sets the R-band.
290
         *
291
         * Asigna la banda R.
292
         * @param r
293
         */
294
        public void setBandR(int r){
295
                this.rband = r;
296
        }
297

    
298
        /**
299
         * Sets the G-band.
300
         *
301
         * Asigna la banda G
302
         * @param g
303
         */
304
        public void setBandG(int g){
305
                this.gband = g;
306
        }
307

    
308
        /**
309
         * Sets the B-band.
310
         *
311
         * Asigna la banda B
312
         * @param b
313
         */
314
        public void setBandB(int b){
315
                this.bband = b;
316
        }
317

    
318
        /*
319
         *  (non-Javadoc)
320
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getAttributes()
321
         */
322
        public ArrayList getAttributes() {
323
                if (rasterFile != null){
324
                        ArrayList attr = new ArrayList();
325
                        String dataType = "Byte";
326
                        if (rasterFile.getDataType() == DataBuffer.TYPE_BYTE) dataType = "Byte";
327
                        else if (visualStatus.dataType == DataBuffer.TYPE_SHORT)
328
                                dataType = "Short";
329
                        else if (visualStatus.dataType == DataBuffer.TYPE_USHORT)
330
                                dataType = "Unsigned Short";
331
                        else if (visualStatus.dataType == DataBuffer.TYPE_INT)
332
                                dataType = "Integer";
333
                        else if (visualStatus.dataType == DataBuffer.TYPE_FLOAT)
334
                                dataType = "Float";
335
                        else if (visualStatus.dataType == DataBuffer.TYPE_DOUBLE)
336
                                dataType = "Double";
337
                        else
338
                                dataType = "Unknown";
339

    
340
                        Object [][] a = {
341
                                {"Filename",rasterFile.getName().substring(rasterFile.getName().lastIndexOf("/")+1, rasterFile.getName().length())},
342
                                {"Filesize",new Long(0)},
343
                                {"Width",new Integer((int)this.getWidth())},
344
                                {"Height", new Integer((int)this.getHeight())},
345
                                {"Bands", new Integer(visualStatus.bandCount)},
346
                                {"BandDataType", dataType}
347
                        };
348
                        for (int i=0; i<a.length; i++)
349
                                attr.add(a[i]);
350

    
351
                        return attr;
352
                }
353
                return  null;
354
        }
355

    
356
        /*
357
         *  (non-Javadoc)
358
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxX()
359
         */
360
        public double getMaxX() {
361
                return visualStatus.maxX;
362
        }
363

    
364
        /*
365
         *  (non-Javadoc)
366
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMaxY()
367
         */
368
        public double getMaxY() {
369
                return visualStatus.maxY;
370
        }
371

    
372
        /*
373
         *  (non-Javadoc)
374
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinX()
375
         */
376
        public double getMinX() {
377
                return visualStatus.minX;
378
        }
379

    
380
        /*
381
         *  (non-Javadoc)
382
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getMinY()
383
         */
384
        public double getMinY() {
385
                return visualStatus.minY;
386
        }
387

    
388
        /*
389
         *  (non-Javadoc)
390
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getWidth()
391
         */
392
        public double getWidth() {
393
                return visualStatus.width;
394
        }
395

    
396
        /*
397
         *  (non-Javadoc)
398
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getHeight()
399
         */
400
        public double getHeight() {
401
                return visualStatus.height;
402
        }
403

    
404
        /**
405
         * @deprecated
406
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#getInfo
407
         */
408
        public String queryByPoint(Point p) throws DriverException {
409
                String data = "<file:"+getName().replaceAll("[^a-zA-Z0-9]","")+">\n";
410
                ArrayList attr = this.getAttributes();
411
                data += "  <raster\n";
412
                data += "    File=\""+getName()+"\"\n";
413
                for (int i=0; i<attr.size(); i++) {
414
                        Object [] a = (Object []) attr.get(i);
415

    
416
                        data += "    "+a[0].toString()+"=";
417
                        if (a[1].toString() instanceof String)
418
                                data += "\""+a[1].toString()+"\"\n";
419
                        else
420
                                data += a[1].toString()+"\n";
421
                }
422
                data += "    Point=\""+posX+" , "+posY+"\"\n";
423
                data += "    Point_WC=\""+posXWC+" , "+posYWC+"\"\n";
424
                data += "    RGB=\""+r+", "+g+", "+b+"\"\n";
425
                data += "  />\n";
426

    
427
                data += "</file:"+getName().replaceAll("[^a-zA-Z0-9]","")+">\n";
428
                System.out.println(data);
429
                return data;
430
        }
431
        /**
432
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#getInfo
433
         */
434
        public XMLItem[] getInfo(Point point, double tolerance ) throws DriverException {
435
                String data = "<file:"+getName().replaceAll("[^a-zA-Z0-9]","")+">\n";
436
                ArrayList attr = this.getAttributes();
437
                data += "  <raster\n";
438
                data += "    File=\""+getName()+"\"\n";
439
                for (int i=0; i<attr.size(); i++) {
440
                        Object [] a = (Object []) attr.get(i);
441

    
442
                        data += "    "+a[0].toString()+"=";
443
                        if (a[1].toString() instanceof String)
444
                                data += "\""+a[1].toString()+"\"\n";
445
                        else
446
                                data += a[1].toString()+"\n";
447
                }
448
                data += "    Point=\""+posX+" , "+posY+"\"\n";
449
                data += "    Point_WC=\""+posXWC+" , "+posYWC+"\"\n";
450
                data += "    RGB=\""+r+", "+g+", "+b+"\"\n";
451
                data += "  />\n";
452

    
453
                data += "</file:"+getName().replaceAll("[^a-zA-Z0-9]","")+">\n";
454
                System.out.println(data);
455

    
456
                //return data;
457
                XMLItem[] item =  new XMLItem[1];
458
                item[0]= new StringXMLItem(data, this);
459
                return item;
460
        }
461

    
462
        /*
463
         *  (non-Javadoc)
464
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent()
465
         */
466
        public Rectangle2D getFullExtent() {
467
                return fullExtent;
468
        }
469

    
470
        /*
471
         *  (non-Javadoc)
472
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#draw(java.awt.image.BufferedImage, java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort, com.iver.cit.gvsig.fmap.operations.Cancellable, double)
473
         */
474
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale) throws DriverException {
475

    
476
                if (isWithinScale(scale)){
477
                        Point2D p = viewPort.getOffset();
478
                        // p will be (0, 0) when drawing a view or other when painting onto
479
                        // the Layout.
480
                        visualStatus.width =  viewPort.getImageWidth();
481
                        visualStatus.height =  viewPort.getImageHeight();
482
                        visualStatus.minX = viewPort.getAdjustedExtent().getMinX();
483
                        visualStatus.minY = viewPort.getAdjustedExtent().getMinY();
484
                        visualStatus.maxX = viewPort.getAdjustedExtent().getMaxX();
485
                        visualStatus.maxY = viewPort.getAdjustedExtent().getMaxY();
486

    
487
                        if(mustTileDraw){
488
                                if(viewPort.getImageWidth()<= maxTileDrawWidth && viewPort.getImageHeight()<=maxTileDrawHeight)
489
                                        drawTile(g, viewPort, cancel);
490
                                else{
491
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), viewPort.getImageWidth(), viewPort.getImageHeight());
492
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
493
                                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
494
                                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
495
                                                // drawing part
496
                                                try {
497
                                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
498
                                                        drawTile(g, vp, cancel);
499
                                                } catch (NoninvertibleTransformException e) {
500
                                                        e.printStackTrace();
501
                                                }
502
                                        }
503
                                }
504
                        }else
505
                                drawTile(g, viewPort, cancel);
506
                }
507
                Runtime r = Runtime.getRuntime();
508
                long mem = r.totalMemory() - r.freeMemory();
509
                System.err.println("Memoria total: " + (mem / 1024) +"KB");
510
        }
511

    
512
        /**
513
         * This is the method used to draw a tile in a WMS mosaic layer.
514
         */
515
        private void drawTile(Graphics2D g, ViewPort vp, Cancellable cancel) throws DriverException {
516

    
517
                // Compute the query geometry
518
                // 1. Check if it is within borders
519
                Rectangle2D extent = getFullExtent();
520
        if ((vp.getAdjustedExtent().getMinX() > extent.getMaxX()) ||
521
                (vp.getAdjustedExtent().getMinY() > extent.getMaxY()) ||
522
                (vp.getAdjustedExtent().getMaxX() < extent.getMinX()) ||
523
                (vp.getAdjustedExtent().getMaxY() < extent.getMinY())) {
524
            return;
525
        }
526

    
527
        // 2. Compute extent to be requested.
528
        Rectangle2D bBox = new Rectangle2D.Double();
529
        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
530

    
531
        // 3. Compute size in pixels
532
        double scalex = vp.getAffineTransform().getScaleX();
533
        double scaley = vp.getAffineTransform().getScaleY();
534
        int wImg = (int) Math.ceil(Math.abs(bBox.getWidth() * scalex) + 1);
535
        int hImg = (int) Math.ceil(Math.abs(bBox.getHeight() * scaley) + 1);
536
        Dimension sz = new Dimension(wImg, hImg);
537

    
538
        if ((wImg <= 0) || (hImg <= 0)) {
539
            return;
540
        }
541

    
542
                try {
543
                        wcsStatus.setCoveraName( coverageName );
544
                        wcsStatus.setExtent( bBox );
545
                        wcsStatus.setFormat( format );
546
                        wcsStatus.setHeight( hImg );
547
                        wcsStatus.setWidth( wImg );
548
                        wcsStatus.setSrs(srs);
549
                        wcsStatus.setParameters( parameter );
550
                        wcsStatus.setTime( time );
551
                        wcsStatus.setOnlineResource((String) onlineResources.get("GetCoverage"));
552

    
553
                        File f = getDriver().getCoverage(wcsStatus, new MyCancellable(cancel));
554
                        if (f == null)
555
                                return;
556
                        String nameWordFile = f.getPath() + getExtensionWorldFile();
557
                        com.iver.andami.Utilities.createTemp(nameWordFile, this.getDataWorldFile(bBox, sz));
558

    
559
                        if(status!=null && firstLoad){
560
                                status.applyStatus(this);
561
                                firstLoad = false;
562
                        }
563
                        ViewPortData vpData = new ViewPortData(
564
                                vp.getProjection(), new Extent(bBox), sz );
565
                        vpData.setMat(vp.getAffineTransform());
566

    
567
                        rasterProcess(g, vpData, f);
568

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

    
581
        /**
582
         * Devuelve el FMapWMSDriver.
583
         *
584
         * @return FMapWMSDriver
585
         *
586
         * @throws IllegalStateException
587
         * @throws ValidationException
588
         * @throws UnsupportedVersionException
589
         * @throws IOException
590
         */
591
        private FMapWCSDriver getDriver() throws IllegalStateException, ValidationException, UnsupportedVersionException, IOException {
592
                if (wcs == null) {
593
                        wcs =wcs = FMapWCSDriverFactory.getFMapDriverForURL(host);
594
                }
595
                return wcs;
596
        }
597

    
598
        /**
599
         * Calcula el contenido del fichero de georreferenciaci?n de una imagen.
600
         * @param bBox Tama?o y posici?n de la imagen (en coordenadas de usuario)
601
         * @param sz Tama?o de la imagen en pixeles.
602
         * @return el 'WorldFile', como String.
603
         * @throws IOException
604
         */
605
        public String getDataWorldFile(Rectangle2D bBox, Dimension sz) throws IOException {
606
                StringBuffer data = new StringBuffer();
607
            data.append((bBox.getMaxX() - bBox.getMinX())/(sz.getWidth() - 1)+"\n");
608
            data.append("0.0\n");
609
            data.append("0.0\n");
610
            data.append((bBox.getMaxY() - bBox.getMinY())/(sz.getHeight() - 1)+"\n");
611
            data.append(""+bBox.getMinX()+"\n");
612
            data.append(""+bBox.getMinY()+"\n");
613
            return data.toString();
614
        }
615

    
616
        /**
617
         * Dibuja una imagen usando PxRaster
618
         * @param g        Graphics2D en el que hay que dibujar.
619
         * @param vpData Par?metros de visualizaci?n
620
         * @param file La imagen en cuesti?n.
621
         */
622
        private void rasterProcess(Graphics2D g, ViewPortData vpData, File file) {
623

    
624
                //Creamos el PxRaster
625
                rasterFile = new GdalFile(vpData.getProjection(), file.getAbsolutePath());
626
                raster = new PxRaster(rasterFile, null, rasterFile.getExtent());
627

    
628
                //Recuperamos la pila de filtros si ya hubiese sido cargado antes
629
                if (this.filterStack!=null)
630
                        raster.filterStack = this.filterStack;
631

    
632
                raster.setTransparency(false);
633

    
634
                //Asignamos transparencia y orden de bandas
635
                if (getTransparency() == -1 && !firstLoad);
636
                else
637
                        raster.setTransparency(getTransparency());
638

    
639
                raster.setBand(GeoRasterFile.RED_BAND,rband);
640
                raster.setBand(GeoRasterFile.GREEN_BAND, gband);
641
                raster.setBand(GeoRasterFile.BLUE_BAND, bband);
642

    
643
                //Despues del primer pxRaster asignamos el stackManager guardado para los siguientes.
644
                //Con esto conseguimos asignar los cambios que se hayan producido desde el cuadro de
645
                //propiedades cuando creamos un nuevo pxRaster
646
                if (this.stackManager != null)
647
                        raster.setStackManager(this.stackManager);
648

    
649
                if (visualStatus != null){
650
                        visualStatus.bandCount = raster.getBandCount();
651
                        visualStatus.dataType = raster.getDataType();
652
                }
653

    
654
                raster.draw(g, vpData);
655

    
656
                //En el primer pxRaster de una imagen obtenemos el Stack Manager para poder modificarlo
657
                //si queremos desde las propiedades
658

    
659
                if (this.stackManager == null)
660
                        this.stackManager = raster.getStackManager();
661

    
662
                if (this.filterStack == null)
663
                        this.filterStack = raster.filterStack;
664

    
665
                rasterFile.close();
666
        }
667

    
668
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale) throws DriverException {
669
                draw(null, g, viewPort, cancel, scale);
670
        }
671

    
672
        /**
673
         * @return Returns the raster.
674
         */
675
        public PxRaster getPxRaster() {
676
                return raster;
677
        }
678

    
679
        /**
680
         * Returns the XMLEntity containing the necessary info for reproduce
681
         * the layer.
682
         *
683
         * Devuelve el XMLEntity con la informaci?n necesaria para reproducir
684
         * la capa.
685
         *
686
         * @return XMLEntity.
687
         * @throws XMLException
688
         */
689
        public XMLEntity getXMLEntity() throws XMLException {
690
                XMLEntity xml = super.getXMLEntity();
691

    
692
                xml.putProperty("wcs.host", getHost());
693
                xml.putProperty("wcs.fullExtent", StringUtilities.rect2String( fullExtent ));
694
                xml.putProperty("wcs.layerQuery", coverageName );
695
                xml.putProperty("wcs.format", format );
696
                xml.putProperty("wcs.srs", srs );
697
                xml.putProperty("wcs.time", time );
698
                xml.putProperty("wcs.parameter", parameter );
699
                xml.putProperty("wcs.coverageName", coverageName );
700
                xml.putProperty("wcs.maxResX", maxRes.getX());
701
                xml.putProperty("wcs.maxResY", maxRes.getY());
702
                if (status!=null)
703
                        status.getXMLEntity(xml, true, this);
704
                else{
705
                        status = new StatusLayerRaster();
706
                        status.getXMLEntity(xml, true, this);
707
                }
708
                return xml;
709
        }
710

    
711
        /**
712
         * Reproduces the layer from an XMLEntity.
713
         *
714
         * A partir del XMLEntity reproduce la capa.
715
         *
716
          * @param xml XMLEntity
717
         *
718
         * @throws XMLException
719
         * @throws DriverException
720
         * @throws DriverIOException
721
         */
722
        public void setXMLEntity(XMLEntity xml) throws XMLException {
723
                super.setXMLEntity(xml);
724

    
725
                // host
726
                try {
727
                        host = new URL(xml.getStringProperty("wcs.host"));
728
                } catch (MalformedURLException e) {
729
                        throw new XMLException(e);
730
                }
731

    
732
                // full extent
733
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty("wcs.fullExtent"));
734

    
735
                // coverageQuery
736
                coverageName = xml.getStringProperty("wcs.layerQuery");
737

    
738
                // format
739
                format = xml.getStringProperty("wcs.format");
740

    
741
                // srs
742
                srs = xml.getStringProperty("wcs.srs");
743

    
744
                // time
745
                time = xml.getStringProperty("wcs.time");
746

    
747
                // parameter
748
                parameter = xml.getStringProperty("wcs.parameter");
749

    
750
                // coverage name
751
                coverageName = xml.getStringProperty("wcs.coverageName");
752

    
753
                // max resolution
754
                if (xml.contains("wcs.maxRes"))
755
                        maxRes = new Point2D.Double(xml.getDoubleProperty("wcs.maxRes"), xml.getDoubleProperty("wcs.maxRes"));
756
                else if (xml.contains("wcs.maxResX") && xml.contains("wcs.maxResY"))
757
                        maxRes = new Point2D.Double(xml.getDoubleProperty("wcs.maxResX"), xml.getDoubleProperty("wcs.maxResY"));
758

    
759
                // OnlineResources
760
        if (xml.contains("onlineResources")) {
761
                String[] operations = xml.getStringProperty("onlineResources").split("~##SEP1##~");
762
                for (int i = 0; i < operations.length; i++) {
763
                                String[] resources = operations[i].split("~##SEP2##~");
764
                                if (resources.length==2 && resources[1]!="")
765
                                        onlineResources.put(resources[0], resources[1]);
766
                        }
767
        }
768
                String claseStr = null;
769
                if (xml.contains("raster.class")) {
770
                        claseStr = xml.getStringProperty("raster.class");
771
                }
772
                if (status!=null)
773
                        status.setXMLEntity(xml, this);
774
                else {
775
                        //Cuando cargamos un proyecto
776

    
777
                        if(claseStr!=null && !claseStr.equals("")){
778
                                try{
779
                                        Class clase = Class.forName(claseStr);
780
                                        Constructor constr = clase.getConstructor(null);
781
                                        status = (StatusRasterInterface)constr.newInstance(null);
782
                                        if(status!=null)
783
                                                status.setXMLEntity(xml, this);
784
                                } catch(ClassNotFoundException exc) {
785
                                        exc.printStackTrace();
786
                                } catch(InstantiationException exc) {
787
                                        exc.printStackTrace();
788
                                } catch(IllegalAccessException exc) {
789
                                        exc.printStackTrace();
790
                                } catch(NoSuchMethodException exc) {
791
                                        exc.printStackTrace();
792
                                } catch(InvocationTargetException exc) {
793
                                        exc.printStackTrace();
794
                                }
795
                        }
796
                }
797
                firstLoad = true;
798
        }
799

    
800
        public void setCoverageName(String coverageName) {
801
                this.coverageName = coverageName;
802
        }
803

    
804
        public void setParameter(String parametersString) {
805
                this.parameter = parametersString;
806
        }
807

    
808
        public void setTime(String time) {
809
                this.time = time;
810
        }
811

    
812
        public void setSRS(String srs) {
813
                this.srs = srs;
814
        }
815

    
816
        public void setFormat(String format) {
817
                this.format = format;
818
        }
819

    
820

    
821
        /**
822
         * Inserta el URL.
823
         *
824
         * @param host String.
825
         * @throws MalformedURLException
826
         */
827
        public void setHost(String host) {
828
                try {
829
                        setHost(new URL(host));
830
                } catch (MalformedURLException e) {
831

    
832
                }
833
        }
834

    
835
        /**
836
         * Inserta el URL.
837
         *
838
         * @param host URL.
839
         */
840
        public void setHost(URL host) {
841
                this.host = host;
842
        }
843

    
844
        /**
845
         * Sets the layer's full extent.
846
         *
847
         * Establece la extensi?n m?xima de la capa.
848
         *
849
         * @param rect
850
         */
851
        public void setFullExtent(Rectangle2D rect) {
852
                this.fullExtent = rect;
853
        }
854

    
855
        /**
856
         * Devuelve el URL.
857
         *
858
         * @return URL.
859
         */
860
        public URL getHost() {
861
                return host;
862
        }
863

    
864
        /**
865
         * Remote source layers have a bunch of properties that are required for get them from
866
         * the servers. This method supplies a hash table containing any needed field. This hash
867
         * table may be used to let the client to connect to a server and restore a previously saved
868
         * layer. So, the layer itself may not be saved to the disk since the actual saved
869
         * info is just its properties.
870
         *
871
         * @return Returns a hash table containing all the required information for
872
         * set up a wms layer
873
         */
874
        public Hashtable getProperties(){
875
                Hashtable info = new Hashtable();
876
                info.put(   "name", coverageName);
877
                info.put(   "host", getHost());
878
                info.put(    "crs", srs);
879
                info.put( "format", format);
880
                String str = time;
881
                if (str==null)
882
                        str = "";
883
                info.put(   "time", str);
884
                str = parameter;
885
                if (str==null)
886
                        str = "";
887
                info.put("parameter", str);
888

    
889
                return info;
890
        }
891

    
892
        /**
893
         * Obtiene la extensi?n del fichero de georreferenciaci?n
894
         * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
895
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
896
         */
897
        private String getExtensionWorldFile(){
898
                String extWorldFile = ".wld";
899
            if (format.equals("image/tif") || format.equals("image/tiff"))
900
                    extWorldFile = ".tfw";
901
            if (format.equals("image/jpeg"))
902
                    extWorldFile = ".jpgw";
903
            return extWorldFile;
904
        }
905

    
906
        public void setMaxResolution(Point2D maxResolution) {
907
                this.maxRes = maxResolution;
908
        }
909

    
910
        /**
911
         * Gets the last open GeoRasterFile against the temp file received
912
         *
913
         * Obtiene el ?ltimo GeoRasterFile abierto sobre el temporal recibido
914
         * @return
915
         */
916
        public GeoRasterFile getGeoRasterFile(){
917
                return rasterFile;
918
        }
919

    
920

    
921
        /**
922
         * Asignar el estado del raster
923
         * @param status
924
         */
925
        public void setStatus(StatusRasterInterface status){
926
                this.status = status;
927
        }
928

    
929
        /**
930
         * Obtiene el estado del raster
931
         * @return
932
         */
933
        public StatusRasterInterface getStatus(){
934
                return this.status;
935
        }
936

    
937
        /**
938
         * Gets the max resolution allowed by the coverage. Requesting a higher resolution
939
         * than this value does not cause any error, but the info responsed is just an
940
         * interpolation.
941
         *
942
         * In exchange for obtaining a greater file and without additional information,
943
         * we can easily connect it at the View.
944
         *
945
         *
946
         * Obtiene la resoluci?n m?xima soportada por la cobertura. La petici?n
947
         * de una resoluci?n superior a la soportada no provoca ning?n error, aunque
948
         * la informaci?n obtenida s?lo es una mera interpolaci?n de informaci?n.
949
         *
950
         * A cambio de obtener un archivo mayor y sin informaci?n adicional, podemos
951
         * f?cilmente acoplarlo a la vista.
952
         *
953
         * @return double
954
         */
955
        public Point2D getMaxResolution() {
956
                if (maxRes==null)
957
                        maxRes = wcs.getMaxResolution(coverageName);
958
                return maxRes;
959
        }
960

    
961

    
962
        public void setDriver(FMapWCSDriver driver) {
963
                this.driver = driver;
964
        }
965

    
966
        /*
967
         *  (non-Javadoc)
968
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
969
         */
970
        public int[] getTileSize() {
971
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
972
                return size;
973
        }
974

    
975
        /*
976
         *  (non-Javadoc)
977
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
978
         */
979
        public boolean isTiled() {
980
                return mustTileDraw;
981
        }
982
}