Statistics
| Revision:

root / trunk / extensions / extWCS / src / com / iver / cit / gvsig / fmap / layers / FLyrWCS.java @ 6402

History | View | Annotate | Download (27.8 KB)

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

    
43
import java.awt.Component;
44
import java.awt.Dimension;
45
import java.awt.Graphics2D;
46
import java.awt.Point;
47
import java.awt.Rectangle;
48
import java.awt.geom.AffineTransform;
49
import java.awt.geom.NoninvertibleTransformException;
50
import java.awt.geom.Point2D;
51
import java.awt.geom.Rectangle2D;
52
import java.awt.image.BufferedImage;
53
import java.awt.image.DataBuffer;
54
import java.io.File;
55
import java.io.IOException;
56
import java.lang.reflect.Constructor;
57
import java.lang.reflect.InvocationTargetException;
58
import java.net.MalformedURLException;
59
import java.net.URL;
60
import java.util.ArrayList;
61
import java.util.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                                                 transparency = -1;
125
        private int                                                        rband = 0, gband = 1, bband = 2;
126
        private VisualStatus                                visualStatus = new VisualStatus();
127

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

    
134
        private FMapWCSDriver driver;
135

    
136
        private class MyCancellable implements ICancellable
137
        {
138

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

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

    
153
        public FLyrWCS(Map args) throws DriverIOException{
154
                FMapWCSDriver drv = null;
155
                String host = (String)args.get("HOST");
156
                String sCoverage = (String) args.get((String) "COVERAGE");
157

    
158
                try {
159
                        this.setHost(new URL(host));
160
                } catch (MalformedURLException e) {
161
                        //e.printStackTrace();
162
                        throw new DriverIOException("Malformed host URL, '" + host + "' (" + e.toString() + ").");
163
                }
164
                try {
165
                        drv = this.getDriver();
166
                } catch (Exception e) {
167
                        // e.printStackTrace();
168
                        throw new DriverIOException("Can't get driver to host '" + host + "' (" + e.toString() + ").");
169
                }
170

    
171
                try{
172
                        if (!drv.connect(null)){
173
                                throw new DriverIOException("Can't connect to host '" + host + "'.");
174
                        }
175
                }catch(Exception e){
176
                        throw new DriverIOException("Can't connect to host '" + host + "'.");
177
                }
178

    
179
                WCSLayer wcsNode = drv.getLayer(sCoverage);
180

    
181
                if (wcsNode == null){
182
                        throw new DriverIOException("The server '" + host + "' doesn't has the coverage '" + sCoverage + "'.");
183
                }
184

    
185
                try{
186
                        this.setFullExtent(drv.getFullExtent(sCoverage,
187
                                        (String) args.get((String) "CRS")));
188
                        this.setFormat((String) args.get((String) "FORMAT"));
189
                        this.setParameter("BANDS=" + (String) args.get((String) "BANDS"));
190
                        this.setSRS((String) args.get((String) "CRS"));
191
                        this.setName(sCoverage);
192
                        this.setCoverageName(sCoverage);
193
                }catch (Exception e){
194
                        throw new DriverIOException("The server '" + host + "' is not able to load the coverage '" + sCoverage + "'.");
195
                }
196

    
197
        }
198

    
199
        /**
200
         * Clase que contiene los datos de visualizaci?n de WMS.
201
         * @author Nacho Brodin (brodin_ign@gva.es)
202
         */
203
        private class VisualStatus {
204
                /**
205
                 * Ancho y alto de la imagen o del conjunto de tiles si los tiene. Coincide con
206
                 * el ancho y alto del viewPort
207
                 */
208
                private        int                                                        width = 0, height = 0;
209
                private double                                                minX = 0D, minY = 0D, maxX = 0D, maxY = 0D;
210
                private int                                                 bandCount = 0;
211
                private int                                                        dataType = DataBuffer.TYPE_UNDEFINED;
212
        }
213

    
214
        /*
215
         *  (non-Javadoc)
216
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setRGB(int, int, int)
217
         */
218
        public void setRGB(int r, int g, int b) {
219
                this.r = r;
220
                this.g = g;
221
                this.b = b;
222
        }
223

    
224
        /*
225
         *  (non-Javadoc)
226
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getFilterStack()
227
         */
228
        public RasterFilterStack getFilterStack() {
229
                if(raster!=null)
230
                        return raster.filterStack;
231
                return null;
232
        }
233

    
234
        /*
235
         *  (non-Javadoc)
236
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setFilterStack(org.cresques.io.raster.RasterFilterStack)
237
         */
238
        public void setFilterStack(RasterFilterStack stack) {
239
                this.filterStack = stack;
240
        }
241

    
242
        /*
243
         *  (non-Javadoc)
244
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getSource()
245
         */
246
        public RasterAdapter getSource() {
247
                return null;
248
        }
249

    
250
        /*
251
         *  (non-Javadoc)
252
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setSource(com.iver.cit.gvsig.fmap.layers.RasterAdapter)
253
         */
254
        public void setSource(RasterAdapter ra) {
255
        }
256

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

    
266
        /*
267
         *  (non-Javadoc)
268
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setPosWC(double, double)
269
         */
270
        public void setPosWC(double x, double y) {
271
                this.posXWC = x;
272
                this.posYWC = y;
273
        }
274

    
275
        /*
276
         *  (non-Javadoc)
277
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getPixel(double, double)
278
         */
279
        public int[] getPixel(double wcx, double wcy) {
280
                if(getPxRaster() != null)
281
                        return getPxRaster().getPixel(wcx, wcy);
282
        return null;
283
        }
284

    
285
        /*
286
         *  (non-Javadoc)
287
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#setBand(int, int)
288
         */
289
        public void setBand(int flag, int nBand) {
290
                switch(flag){
291
                case GeoRasterFile.RED_BAND:setBandR(nBand);break;
292
                case GeoRasterFile.GREEN_BAND:setBandG(nBand);break;
293
                case GeoRasterFile.BLUE_BAND:setBandB(nBand);break;
294
                }
295
        }
296

    
297
        /**
298
         * Sets the R-band.
299
         *
300
         * Asigna la banda R.
301
         * @param r
302
         */
303
        public void setBandR(int r){
304
                this.rband = r;
305
        }
306

    
307
        /**
308
         * Sets the G-band.
309
         *
310
         * Asigna la banda G
311
         * @param g
312
         */
313
        public void setBandG(int g){
314
                this.gband = g;
315
        }
316

    
317
        /**
318
         * Sets the B-band.
319
         *
320
         * Asigna la banda B
321
         * @param b
322
         */
323
        public void setBandB(int b){
324
                this.bband = b;
325
        }
326

    
327
        /*
328
         *  (non-Javadoc)
329
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getAttributes()
330
         */
331
        public ArrayList getAttributes() {
332
                if (rasterFile != null){
333
                        ArrayList attr = new ArrayList();
334
                        String dataType = "Byte";
335
                        if (rasterFile.getDataType() == DataBuffer.TYPE_BYTE) dataType = "Byte";
336
                        else if (visualStatus.dataType == DataBuffer.TYPE_SHORT)
337
                                dataType = "Short";
338
                        else if (visualStatus.dataType == DataBuffer.TYPE_USHORT)
339
                                dataType = "Unsigned Short";
340
                        else if (visualStatus.dataType == DataBuffer.TYPE_INT)
341
                                dataType = "Integer";
342
                        else if (visualStatus.dataType == DataBuffer.TYPE_FLOAT)
343
                                dataType = "Float";
344
                        else if (visualStatus.dataType == DataBuffer.TYPE_DOUBLE)
345
                                dataType = "Double";
346
                        else
347
                                dataType = "Unknown";
348

    
349
                        Object [][] a = {
350
                                {"Filename",rasterFile.getName().substring(rasterFile.getName().lastIndexOf("/")+1, rasterFile.getName().length())},
351
                                {"Filesize",new Long(0)},
352
                                {"Width",new Integer((int)this.getWidth())},
353
                                {"Height", new Integer((int)this.getHeight())},
354
                                {"Bands", new Integer(visualStatus.bandCount)},
355
                                {"BandDataType", dataType}
356
                        };
357
                        for (int i=0; i<a.length; i++)
358
                                attr.add(a[i]);
359

    
360
                        return attr;
361
                }
362
                return  null;
363
        }
364

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

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

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

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

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

    
405
        /*
406
         *  (non-Javadoc)
407
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getHeight()
408
         */
409
        public double getHeight() {
410
                return visualStatus.height;
411
        }
412

    
413
        /**
414
         * @deprecated
415
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#getInfo
416
         */
417
        public String queryByPoint(Point p) throws DriverException {
418
                String data = "<file:"+getName().replaceAll("[^a-zA-Z0-9]","")+">\n";
419
                ArrayList attr = this.getAttributes();
420
                data += "  <raster\n";
421
                data += "    File=\""+getName()+"\"\n";
422
                for (int i=0; i<attr.size(); i++) {
423
                        Object [] a = (Object []) attr.get(i);
424

    
425
                        data += "    "+a[0].toString()+"=";
426
                        if (a[1].toString() instanceof String)
427
                                data += "\""+a[1].toString()+"\"\n";
428
                        else
429
                                data += a[1].toString()+"\n";
430
                }
431
                data += "    Point=\""+posX+" , "+posY+"\"\n";
432
                data += "    Point_WC=\""+posXWC+" , "+posYWC+"\"\n";
433
                data += "    RGB=\""+r+", "+g+", "+b+"\"\n";
434
                data += "  />\n";
435

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

    
451
                        data += "    "+a[0].toString()+"=";
452
                        if (a[1].toString() instanceof String)
453
                                data += "\""+a[1].toString()+"\"\n";
454
                        else
455
                                data += a[1].toString()+"\n";
456
                }
457
                data += "    Point=\""+posX+" , "+posY+"\"\n";
458
                data += "    Point_WC=\""+posXWC+" , "+posYWC+"\"\n";
459
                data += "    RGB=\""+r+", "+g+", "+b+"\"\n";
460
                data += "  />\n";
461

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

    
465
                //return data;
466
                XMLItem[] item =  new XMLItem[1];
467
                item[0]= new StringXMLItem(data, this);
468
                return item;
469
        }
470

    
471
        /*
472
         *  (non-Javadoc)
473
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent()
474
         */
475
        public Rectangle2D getFullExtent() {
476
                return fullExtent;
477
        }
478

    
479
        /*
480
         *  (non-Javadoc)
481
         * @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)
482
         */
483
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale) throws DriverException {
484
                setUnavailable(false);
485

    
486
                if (isWithinScale(scale)){
487
                        Point2D p = viewPort.getOffset();
488
                        // p will be (0, 0) when drawing a view or other when painting onto
489
                        // the Layout.
490
                        visualStatus.width =  viewPort.getImageWidth();
491
                        visualStatus.height =  viewPort.getImageHeight();
492
                        visualStatus.minX = viewPort.getAdjustedExtent().getMinX();
493
                        visualStatus.minY = viewPort.getAdjustedExtent().getMinY();
494
                        visualStatus.maxX = viewPort.getAdjustedExtent().getMaxX();
495
                        visualStatus.maxY = viewPort.getAdjustedExtent().getMaxY();
496

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

    
522
        /**
523
         * This is the method used to draw a tile in a WMS mosaic layer.
524
         */
525
        private void drawTile(Graphics2D g, ViewPort vp, Cancellable cancel) throws DriverException {
526

    
527
                // Compute the query geometry
528
                // 1. Check if it is within borders
529
                Rectangle2D extent = getFullExtent();
530
        if ((vp.getExtent().getMinX() > extent.getMaxX()) ||
531
                (vp.getExtent().getMinY() > extent.getMaxY()) ||
532
                (vp.getExtent().getMaxX() < extent.getMinX()) ||
533
                (vp.getExtent().getMaxY() < extent.getMinY())) {
534
            return;
535
        }
536

    
537
        // 2. Compute extent to be requested.
538
        Rectangle2D bBox = new Rectangle2D.Double();
539
        Rectangle2D.intersect(vp.getExtent(), extent, bBox);
540

    
541
        // 3. Compute size in pixels
542
        double scalex = vp.getAffineTransform().getScaleX();
543
        double scaley = vp.getAffineTransform().getScaleY();
544
        int wImg = (int) Math.ceil(Math.abs(bBox.getWidth() * scalex) + 1);
545
        int hImg = (int) Math.ceil(Math.abs(bBox.getHeight() * scaley) + 1);
546
        Dimension sz = new Dimension(wImg, hImg);
547

    
548
        if ((wImg <= 0) || (hImg <= 0)) {
549
            return;
550
        }
551

    
552
                try {
553
                        wcsStatus.setCoveraName( coverageName );
554
                        wcsStatus.setExtent( bBox );
555
                        wcsStatus.setFormat( format );
556
                        wcsStatus.setHeight( hImg );
557
                        wcsStatus.setWidth( wImg );
558
                        wcsStatus.setSrs(srs);
559
                        wcsStatus.setParameters( parameter );
560
                        wcsStatus.setTime( time );
561
                        wcsStatus.setOnlineResource((String) onlineResources.get("GetCoverage"));
562

    
563
                        File f = getDriver().getCoverage(wcsStatus, new MyCancellable(cancel));
564
                        if (f == null)
565
                                return;
566
                        String nameWordFile = f.getPath() + getExtensionWorldFile();
567
                        com.iver.andami.Utilities.createTemp(nameWordFile, this.getDataWorldFile(bBox, sz));
568

    
569
                        if(status!=null && firstLoad){
570
                                status.applyStatus(this);
571
                                firstLoad = false;
572
                        }
573
                        ViewPortData vpData = new ViewPortData(
574
                                vp.getProjection(), new Extent(bBox), sz );
575
                        vpData.setMat(vp.getAffineTransform());
576

    
577
                        rasterProcess(g, vpData, f);
578

    
579
                } catch (ValidationException e) {
580
                        throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
581
                } catch (UnsupportedVersionException e) {
582
                        throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
583
                } catch (IOException e) {
584
                        throw new DriverException(PluginServices.getText(this, "connect_error"), e);
585
                } catch (WCSException e) {
586
            JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
587
                        setUnavailable(true);
588
                }
589
        }
590

    
591
        /**
592
         * Devuelve el FMapWMSDriver.
593
         *
594
         * @return FMapWMSDriver
595
         *
596
         * @throws IllegalStateException
597
         * @throws ValidationException
598
         * @throws UnsupportedVersionException
599
         * @throws IOException
600
         */
601
        private FMapWCSDriver getDriver() throws IllegalStateException, ValidationException, UnsupportedVersionException, IOException {
602
                if (wcs == null) {
603
                        wcs =wcs = FMapWCSDriverFactory.getFMapDriverForURL(host);
604
                }
605
                return wcs;
606
        }
607

    
608
        /**
609
         * Calcula el contenido del fichero de georreferenciaci?n de una imagen.
610
         * @param bBox Tama?o y posici?n de la imagen (en coordenadas de usuario)
611
         * @param sz Tama?o de la imagen en pixeles.
612
         * @return el 'WorldFile', como String.
613
         * @throws IOException
614
         */
615
        public String getDataWorldFile(Rectangle2D bBox, Dimension sz) throws IOException {
616
                StringBuffer data = new StringBuffer();
617
            data.append((bBox.getMaxX() - bBox.getMinX())/(sz.getWidth() - 1)+"\n");
618
            data.append("0.0\n");
619
            data.append("0.0\n");
620
            data.append((bBox.getMaxY() - bBox.getMinY())/(sz.getHeight() - 1)+"\n");
621
            data.append(""+bBox.getMinX()+"\n");
622
            data.append(""+bBox.getMinY()+"\n");
623
            return data.toString();
624
        }
625

    
626
        /**
627
         * Dibuja una imagen usando PxRaster
628
         * @param g        Graphics2D en el que hay que dibujar.
629
         * @param vpData Par?metros de visualizaci?n
630
         * @param file La imagen en cuesti?n.
631
         */
632
        private void rasterProcess(Graphics2D g, ViewPortData vpData, File file) {
633

    
634
                //Creamos el PxRaster
635
                rasterFile = new GdalFile(vpData.getProjection(), file.getAbsolutePath());
636
                raster = new PxRaster(rasterFile, null, rasterFile.getExtent());
637

    
638
                //Recuperamos la pila de filtros si ya hubiese sido cargado antes
639
                if (this.filterStack!=null)
640
                        raster.filterStack = this.filterStack;
641

    
642
                raster.setTransparency(false);
643

    
644
                //Asignamos transparencia y orden de bandas
645
                if (this.transparency==-1 && !firstLoad);
646
                else
647
                        raster.setTransparency(this.transparency);
648

    
649
                raster.setBand(GeoRasterFile.RED_BAND,rband);
650
                raster.setBand(GeoRasterFile.GREEN_BAND, gband);
651
                raster.setBand(GeoRasterFile.BLUE_BAND, bband);
652

    
653
                //Despues del primer pxRaster asignamos el stackManager guardado para los siguientes.
654
                //Con esto conseguimos asignar los cambios que se hayan producido desde el cuadro de
655
                //propiedades cuando creamos un nuevo pxRaster
656
                if (this.stackManager != null)
657
                        raster.setStackManager(this.stackManager);
658

    
659
                if (visualStatus != null){
660
                        visualStatus.bandCount = raster.getBandCount();
661
                        visualStatus.dataType = raster.getDataType();
662
                }
663

    
664
                raster.draw(g, vpData);
665

    
666
                //En el primer pxRaster de una imagen obtenemos el Stack Manager para poder modificarlo
667
                //si queremos desde las propiedades
668

    
669
                if (this.stackManager == null)
670
                        this.stackManager = raster.getStackManager();
671

    
672
                if (this.filterStack == null)
673
                        this.filterStack = raster.filterStack;
674

    
675
                rasterFile.close();
676
        }
677

    
678
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale) throws DriverException {
679
                draw(null, g, viewPort, cancel, scale);
680
        }
681

    
682
        /**
683
         * @return Returns the raster.
684
         */
685
        public PxRaster getPxRaster() {
686
                return raster;
687
        }
688

    
689
        /**
690
         * Returns the XMLEntity containing the necessary info for reproduce
691
         * the layer.
692
         *
693
         * Devuelve el XMLEntity con la informaci?n necesaria para reproducir
694
         * la capa.
695
         *
696
         * @return XMLEntity.
697
         * @throws XMLException
698
         */
699
        public XMLEntity getXMLEntity() throws XMLException {
700
                XMLEntity xml = super.getXMLEntity();
701

    
702
                xml.putProperty("wcs.host", getHost());
703
                xml.putProperty("wcs.fullExtent", StringUtilities.rect2String( fullExtent ));
704
                xml.putProperty("wcs.layerQuery", coverageName );
705
                xml.putProperty("wcs.format", format );
706
                xml.putProperty("wcs.srs", srs );
707
                xml.putProperty("wcs.time", time );
708
                xml.putProperty("wcs.parameter", parameter );
709
                xml.putProperty("wcs.coverageName", coverageName );
710
                xml.putProperty("wcs.maxResX", maxRes.getX());
711
                xml.putProperty("wcs.maxResY", maxRes.getY());
712
                if (status!=null)
713
                        status.getXMLEntity(xml, true, this);
714
                else{
715
                        status = new StatusLayerRaster();
716
                        status.getXMLEntity(xml, true, this);
717
                }
718
                return xml;
719
        }
720

    
721
        /**
722
         * Reproduces the layer from an XMLEntity.
723
         *
724
         * A partir del XMLEntity reproduce la capa.
725
         *
726
          * @param xml XMLEntity
727
         *
728
         * @throws XMLException
729
         * @throws DriverException
730
         * @throws DriverIOException
731
         */
732
        public void setXMLEntity(XMLEntity xml) throws XMLException {
733
                super.setXMLEntity(xml);
734

    
735
                // host
736
                try {
737
                        host = new URL(xml.getStringProperty("wcs.host"));
738
                } catch (MalformedURLException e) {
739
                        throw new XMLException(e);
740
                }
741

    
742
                // full extent
743
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty("wcs.fullExtent"));
744

    
745
                // coverageQuery
746
                coverageName = xml.getStringProperty("wcs.layerQuery");
747

    
748
                // format
749
                format = xml.getStringProperty("wcs.format");
750

    
751
                // srs
752
                srs = xml.getStringProperty("wcs.srs");
753

    
754
                // time
755
                time = xml.getStringProperty("wcs.time");
756

    
757
                // parameter
758
                parameter = xml.getStringProperty("wcs.parameter");
759

    
760
                // coverage name
761
                coverageName = xml.getStringProperty("wcs.coverageName");
762

    
763
                // max resolution
764
                if (xml.contains("wcs.maxRes"))
765
                        maxRes = new Point2D.Double(xml.getDoubleProperty("wcs.maxRes"), xml.getDoubleProperty("wcs.maxRes"));
766
                else if (xml.contains("wcs.maxResX") && xml.contains("wcs.maxResY"))
767
                        maxRes = new Point2D.Double(xml.getDoubleProperty("wcs.maxResX"), xml.getDoubleProperty("wcs.maxResY"));
768

    
769
                // OnlineResources
770
        if (xml.contains("onlineResources")) {
771
                String[] operations = xml.getStringProperty("onlineResources").split("~##SEP1##~");
772
                for (int i = 0; i < operations.length; i++) {
773
                                String[] resources = operations[i].split("~##SEP2##~");
774
                                if (resources.length==2 && resources[1]!="")
775
                                        onlineResources.put(resources[0], resources[1]);
776
                        }
777
        }
778
                String claseStr = null;
779
                if (xml.contains("raster.class")) {
780
                        claseStr = xml.getStringProperty("raster.class");
781
                }
782
                if (status!=null)
783
                        status.setXMLEntity(xml, this);
784
                else {
785
                        //Cuando cargamos un proyecto
786

    
787
                        if(claseStr!=null && !claseStr.equals("")){
788
                                try{
789
                                        Class clase = Class.forName(claseStr);
790
                                        Constructor constr = clase.getConstructor(null);
791
                                        status = (StatusRasterInterface)constr.newInstance(null);
792
                                        if(status!=null)
793
                                                status.setXMLEntity(xml, this);
794
                                } catch(ClassNotFoundException exc) {
795
                                        exc.printStackTrace();
796
                                } catch(InstantiationException exc) {
797
                                        exc.printStackTrace();
798
                                } catch(IllegalAccessException exc) {
799
                                        exc.printStackTrace();
800
                                } catch(NoSuchMethodException exc) {
801
                                        exc.printStackTrace();
802
                                } catch(InvocationTargetException exc) {
803
                                        exc.printStackTrace();
804
                                }
805
                        }
806
                }
807
                firstLoad = true;
808
        }
809

    
810
        public void setCoverageName(String coverageName) {
811
                this.coverageName = coverageName;
812
        }
813

    
814
        public void setParameter(String parametersString) {
815
                this.parameter = parametersString;
816
        }
817

    
818
        public void setTime(String time) {
819
                this.time = time;
820
        }
821

    
822
        public void setSRS(String srs) {
823
                this.srs = srs;
824
        }
825

    
826
        public void setFormat(String format) {
827
                this.format = format;
828
        }
829

    
830

    
831
        /**
832
         * Inserta el URL.
833
         *
834
         * @param host String.
835
         * @throws MalformedURLException
836
         */
837
        public void setHost(String host) {
838
                try {
839
                        setHost(new URL(host));
840
                } catch (MalformedURLException e) {
841

    
842
                }
843
        }
844

    
845
        /**
846
         * Inserta el URL.
847
         *
848
         * @param host URL.
849
         */
850
        public void setHost(URL host) {
851
                this.host = host;
852
        }
853

    
854
        /**
855
         * Sets the layer's full extent.
856
         *
857
         * Establece la extensi?n m?xima de la capa.
858
         *
859
         * @param rect
860
         */
861
        public void setFullExtent(Rectangle2D rect) {
862
                this.fullExtent = rect;
863
        }
864

    
865
        /**
866
         * Devuelve el URL.
867
         *
868
         * @return URL.
869
         */
870
        public URL getHost() {
871
                return host;
872
        }
873

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

    
899
                return info;
900
        }
901

    
902
        /**
903
         * Obtiene la extensi?n del fichero de georreferenciaci?n
904
         * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
905
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
906
         */
907
        private String getExtensionWorldFile(){
908
                String extWorldFile = ".wld";
909
            if (format.equals("image/tif") || format.equals("image/tiff"))
910
                    extWorldFile = ".tfw";
911
            if (format.equals("image/jpeg"))
912
                    extWorldFile = ".jpgw";
913
            return extWorldFile;
914
        }
915

    
916
        public void setMaxResolution(Point2D maxResolution) {
917
                this.maxRes = maxResolution;
918
        }
919

    
920
        /**
921
         * Gets the last open GeoRasterFile against the temp file received
922
         *
923
         * Obtiene el ?ltimo GeoRasterFile abierto sobre el temporal recibido
924
         * @return
925
         */
926
        public GeoRasterFile getGeoRasterFile(){
927
                return rasterFile;
928
        }
929

    
930

    
931
        /**
932
         * Asignar el estado del raster
933
         * @param status
934
         */
935
        public void setStatus(StatusRasterInterface status){
936
                this.status = status;
937
        }
938

    
939
        /**
940
         * Obtiene el estado del raster
941
         * @return
942
         */
943
        public StatusRasterInterface getStatus(){
944
                return this.status;
945
        }
946

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

    
971

    
972
        public void setDriver(FMapWCSDriver driver) {
973
                this.driver = driver;
974
        }
975

    
976
        /*
977
         *  (non-Javadoc)
978
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
979
         */
980
        public int[] getTileSize() {
981
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
982
                return size;
983
        }
984

    
985
        /*
986
         *  (non-Javadoc)
987
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
988
         */
989
        public boolean isTiled() {
990
                return mustTileDraw;
991
        }
992
}