Statistics
| Revision:

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

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

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

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

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

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

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

    
546
        if ((wImg <= 0) || (hImg <= 0)) {
547
            return;
548
        }
549

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

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

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

    
575
                        rasterProcess(g, vpData, f);
576

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

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

    
603
        }
604
                return wcs;
605
        }
606

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

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

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

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

    
641
                raster.setTransparency(false);
642

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

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

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

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

    
663
                raster.draw(g, vpData);
664

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

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

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

    
674
                rasterFile.close();
675
        }
676

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
829

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

    
841
                }
842
        }
843

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

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

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

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

    
898
                return info;
899
        }
900

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

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

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

    
929

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

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

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

    
970

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

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

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