Statistics
| Revision:

svn-gvsig-desktop / branches / v2_0_0_prep / extensions / extWCS / src / org / gvsig / wcs / fmap / layers / FLyrWCS.java @ 30008

History | View | Annotate | Download (42.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 org.gvsig.wcs.fmap.layers;
42

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

    
64
import javax.print.attribute.PrintRequestAttributeSet;
65
import javax.swing.ImageIcon;
66

    
67
import org.cresques.cts.ICoordTrans;
68
import org.exolab.castor.xml.ValidationException;
69
import org.gvsig.fmap.crs.CRSFactory;
70
import org.gvsig.fmap.dal.exception.ReadException;
71
import org.gvsig.fmap.geom.GeometryLocator;
72
import org.gvsig.fmap.geom.GeometryManager;
73
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
74
import org.gvsig.fmap.geom.Geometry.TYPES;
75
import org.gvsig.fmap.geom.exception.CreateEnvelopeException;
76
import org.gvsig.fmap.geom.exception.CreateGeometryException;
77
import org.gvsig.fmap.geom.primitive.Envelope;
78
import org.gvsig.fmap.mapcontext.MapContext;
79
import org.gvsig.fmap.mapcontext.ViewPort;
80
import org.gvsig.fmap.mapcontext.exceptions.ConnectionErrorLayerException;
81
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
82
import org.gvsig.fmap.mapcontext.exceptions.UnsupportedVersionLayerException;
83
import org.gvsig.fmap.mapcontext.exceptions.XMLLayerException;
84
import org.gvsig.fmap.mapcontext.layers.FLayer;
85
import org.gvsig.fmap.mapcontext.layers.Tiling;
86
import org.gvsig.fmap.mapcontext.layers.operations.XMLItem;
87
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
88
import org.gvsig.fmap.raster.layers.IRasterLayerActions;
89
import org.gvsig.fmap.raster.layers.IStatusRaster;
90
import org.gvsig.fmap.raster.layers.StatusLayerRaster;
91
import org.gvsig.raster.dataset.CompositeDataset;
92
import org.gvsig.raster.dataset.IBuffer;
93
import org.gvsig.raster.dataset.MosaicNotValidException;
94
import org.gvsig.raster.dataset.MultiRasterDataset;
95
import org.gvsig.raster.dataset.NotSupportedExtensionException;
96
import org.gvsig.raster.dataset.RasterDriverException;
97
import org.gvsig.raster.datastruct.ColorTable;
98
import org.gvsig.raster.datastruct.Extent;
99
import org.gvsig.raster.datastruct.ViewPortData;
100
import org.gvsig.raster.grid.GridTransparency;
101
import org.gvsig.raster.grid.filter.FilterTypeException;
102
import org.gvsig.raster.grid.filter.RasterFilterList;
103
import org.gvsig.raster.grid.filter.RasterFilterListManager;
104
import org.gvsig.remoteclient.wcs.WCSStatus;
105
import org.gvsig.remoteclient.wms.ICancellable;
106
import org.gvsig.tools.task.Cancellable;
107
import org.gvsig.utils.StringUtilities;
108
import org.gvsig.utils.XMLEntity;
109
import org.gvsig.utils.XMLException;
110
import org.gvsig.wcs.fmap.drivers.wcs.FMapWCSDriver;
111
import org.gvsig.wcs.fmap.drivers.wcs.FMapWCSDriverFactory;
112
import org.gvsig.wcs.fmap.drivers.wcs.WCSDriverException;
113

    
114

    
115

    
116
/**
117
 * Class for the WCS layer.
118
 *
119
 * Capa para el WCS.
120
 *
121
 * Las capas WCS son tileadas para descargarlas del servidor. Esto quiere decir que
122
 * est?n formadas por multiples ficheros raster. Por esto la fuente de datos raster (IRasterDatasource)
123
 * de la capa FLyrWCS es un objeto de tipo CompositeDataset. Este objeto est? compuesto por un array
124
 * bidimensional de MultiRasterDataset. Cada uno de los MultiRasterDataset corresponde con un tile
125
 * salvado en disco. Estos MultiRasterDataset se crean cada vez que se repinta ya que en WCS a cada
126
 * zoom varian los ficheros fuente. La secuencia de creaci?n de un CompositeDataset ser?a la siguiente:
127
 * <UL>
128
 * <LI>Se hace una petici?n de dibujado por parte del usuario llamando al m?todo draw de FLyrWCS</LI>
129
 * <LI>Se tilea la petici?n</LI>
130
 * <LI>Cada tile se dibuja abriendo una FLyrRaster para ese tile</LI>
131
 * <LI>Si es el primer dibujado se guarda una referencia en la capa WMS a las propiedades de renderizado, orden de bandas,
132
 * transparencia, filtros aplicados, ...</LI>
133
 * <LI>Si no es el primer dibujado se asignan las propiedades de renderizado cuya referencia se guarda en la capa WMS</LI>
134
 * <LI>Se guarda el MultiRasterDataset de cada tile</LI>
135
 * <LI>Al acabar todos los tiles creamos un CompositeDataset con los MultiRasterDataset de todos los tiles</LI>
136
 * <LI>Asignamos a la capa la referencia de las propiedades de renderizado que tenemos almacenadas. De esta forma si hay
137
 * alguna modificaci?n desde el cuadro de propiedades ser? efectiva sobre los tiles que se dibujan.</LI>
138
 * </UL>
139
 *
140
 * @author jaume - jaume.dominguez@iver.es
141
 */
142
public class FLyrWCS extends FLyrRasterSE {
143
        private FMapWCSDriver wcs = null;
144

    
145
        private URL                                                 host;
146
        private String                                                coverageName;
147
        private Envelope                                        fullEnvelope;
148
        private String                                                format;
149
        private String                                                srs;
150
        private String                                                time;
151
        private String                                                parameter;
152
        private Point2D                                                maxRes;
153
        private Hashtable                                         onlineResources = new Hashtable();
154

    
155
        private WCSStatus                                        wcsStatus = new WCSStatus();
156

    
157
        private int                                                 posX = 0, posY = 0;
158
        private double                                                 posXWC = 0, posYWC = 0;
159
        private int                                                 r = 0, g = 0, b = 0;
160
        private boolean                                         firstLoad = false;
161
        private VisualStatus                                visualStatus = new VisualStatus();
162

    
163
        private boolean                                         mustTileDraw = false;
164
        private int                                                 maxTileDrawWidth  = 1023;
165
        private int                                                        maxTileDrawHeight = 1023;
166
        //private int                                                 maxTilePrintWidth  = 250;
167
        //private int                                                        maxTilePrintHeight = 250;
168
        /**
169
         * Lista de filtros aplicada en la renderizaci?n
170
         */
171
        private RasterFilterList            filterList = null;
172
        private GridTransparency                        transparency = null;
173
        private int[]                       renderBands = null;
174
        private FLyrRasterSE[]                                layerRaster = null;
175
        private ArrayList                   filterArguments = null;
176
        private int                         lastNColumns = 0;
177
        private int                         lastNRows = 0;
178

    
179
        private class MyCancellable implements ICancellable
180
        {
181

    
182
                private Cancellable original;
183
                public MyCancellable(Cancellable cancelOriginal)
184
                {
185
                        this.original = cancelOriginal;
186
                }
187
                public boolean isCanceled() {
188
                        return original.isCanceled();
189
                }
190
                public Object getID() {
191
                        return this;
192
                }
193

    
194
        }
195

    
196
        public FLyrWCS(){
197
                super();
198
        }
199

    
200
        public FLyrWCS(Map args) throws ReadException {
201
                FMapWCSDriver drv = null;
202
                String host = (String)args.get("HOST");
203
                String sCoverage = (String) args.get("COVERAGE");
204

    
205
                try {
206
                        this.setHost(new URL(host));
207
                } catch (MalformedURLException e) {
208
                        //e.printStackTrace();
209
                        throw new ReadException("Malformed host URL, '" + host + "' ("
210
                                        + e.toString() + ").", e);
211
                }
212
                try {
213
                        drv = this.getDriver();
214
                } catch (Exception e) {
215
                        // e.printStackTrace();
216
                        throw new ReadException("Can't get driver to host '" + host + "' ("
217
                                        + e.toString() + ").", e);
218
                }
219

    
220
                try{
221
                        if (!drv.connect(false, null)){
222
                                throw new ReadException(
223
                                                "Can't connect to host '" + host + "'.", null);
224
                        }
225
                }catch(Exception e){
226
                        throw new ReadException("Can't connect to host '" + host + "'.", e);
227
                }
228

    
229
                WCSLayer wcsNode = drv.getLayer(sCoverage);
230

    
231
                if (wcsNode == null){
232
                        throw new ReadException("The server '" + host
233
                                        + "' doesn't has the coverage '" + sCoverage + "'.", null);
234
                }
235

    
236
                try{
237
                        this.setFullExtent(drv.getFullExtent(sCoverage,
238
                                        (String) args.get("CRS")));
239
                        this.setFormat((String) args.get("FORMAT"));
240
                        this.setParameter("BANDS=" + (String) args.get("BANDS"));
241
                        this.setSRS((String) args.get("CRS"));
242
                        this.setName(sCoverage);
243
                        this.setCoverageName(sCoverage);
244
                }catch (Exception e){
245
                        throw new ReadException("The server '" + host
246
                                        + "' is not able to load the coverage '"
247
                                                        + sCoverage + "'.", e);
248
                }
249

    
250
        }
251

    
252
        /**
253
         * Clase que contiene los datos de visualizaci?n de WCS. Tiene datos que representan al
254
         * raster en la vista. Este raster puede estar compuesto por tiles por lo que valores
255
         * como el ancho total o el m?nimo o m?ximo deben ser calculados a partir de todos los
256
         * tiles visualizados.
257
         * @author Nacho Brodin (brodin_ign@gva.es)
258
         */
259
        private class VisualStatus {
260
                /**
261
                 * Ancho y alto de la imagen o del conjunto de tiles si los tiene. Coincide con
262
                 * el ancho y alto del viewPort
263
                 */
264
                private        int                                                        width = 0, height = 0;
265
                private double                                                minX = 0D, minY = 0D, maxX = 0D, maxY = 0D;
266
                private int                                                 bandCount = 0;
267
                private int                                                        dataType = DataBuffer.TYPE_UNDEFINED;
268

    
269
                /**
270
                 * Ancho y alto total del raster que ser? la suma de todos los tiles.
271
                 */
272
                private        int                                                        rasterWidth = 0, rasterHeight = 0;
273
                private        double                                                rasterMinX = Double.MAX_VALUE, rasterMinY = Double.MAX_VALUE;
274
                private        double                                                rasterMaxX = 0, rasterMaxY = 0;
275
                /**
276
                 * Lista de nombre de fichero que componen toda la visualizaci?n.
277
                 */
278
                private String[]                                        fileNames = null;
279
        }
280

    
281
        /**
282
         * @deprecated
283
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#getInfo
284
         */
285
        public String queryByPoint(Point p) {
286
                String data = "<file:"+getName().replaceAll("[^a-zA-Z0-9]","")+">\n";
287
                ArrayList attr = this.getAttributes();
288
                data += "  <raster\n";
289
                data += "    File=\""+getName()+"\"\n";
290
                for (int i=0; i<attr.size(); i++) {
291
                        Object [] a = (Object []) attr.get(i);
292

    
293
                        data += "    "+a[0].toString()+"=";
294
                        if (a[1].toString() instanceof String) {
295
                                data += "\""+a[1].toString()+"\"\n";
296
                        } else {
297
                                data += a[1].toString()+"\n";
298
                        }
299
                }
300
                data += "    Point=\""+posX+" , "+posY+"\"\n";
301
                data += "    Point_WC=\""+posXWC+" , "+posYWC+"\"\n";
302
                data += "    RGB=\""+r+", "+g+", "+b+"\"\n";
303
                data += "  />\n";
304

    
305
                data += "</file:"+getName().replaceAll("[^a-zA-Z0-9]","")+">\n";
306
                System.out.println(data);
307
                return data;
308
        }
309

    
310
        /**
311
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#getInfo
312
         */
313
        public XMLItem[] getInfo(Point point, double tolerance, Cancellable cancel)
314
                        throws ReadException {
315
                return super.getInfo(point, tolerance, cancel);
316
        }
317

    
318
        /**
319
         * Devuelve el envelope en la proyeccion de la vista
320
         *
321
         */
322
        public Envelope getFullEnvelope() {
323
                Envelope rAux;
324
                rAux = this.fullEnvelope;
325
                GeometryManager geoMan = GeometryLocator.getGeometryManager();
326

    
327
                try {
328
                        rAux = geoMan.createEnvelope(SUBTYPES.GEOM2D);
329

    
330
                        // Esto es para cuando se crea una capa nueva con el fullExtent de
331
                        // ancho
332
                        // y alto 0.
333
                        if (rAux == null || rAux.getMaximum(0) - rAux.getMinimum(0) == 0
334
                                        && rAux.getMaximum(1) - rAux.getMinimum(1) == 0) {
335
                                rAux = geoMan.createEnvelope(SUBTYPES.GEOM2D);
336
                                org.gvsig.fmap.geom.primitive.Point pl = (org.gvsig.fmap.geom.primitive.Point) geoMan
337
                                                .create(TYPES.POINT, SUBTYPES.GEOM2D);
338
                                org.gvsig.fmap.geom.primitive.Point pu = (org.gvsig.fmap.geom.primitive.Point) geoMan
339
                                                .create(TYPES.POINT, SUBTYPES.GEOM2D);
340
                                pl.setX(0);
341
                                pl.setY(0);
342
                                pu.setX(100);
343
                                pu.setY(100);
344
                                rAux.setLowerCorner(pl);
345
                                rAux.setUpperCorner(pu);
346
                        }
347
                        // Si existe reproyecci?n, reproyectar el extent
348
                        ICoordTrans ct = getCoordTrans();
349
                        if (ct != null) {
350
                                Point2D pt1 = new Point2D.Double(rAux.getMinimum(0), rAux
351
                                                .getMinimum(1));
352
                                Point2D pt2 = new Point2D.Double(rAux.getMaximum(0), rAux
353
                                                .getMaximum(1));
354
                                pt1 = ct.convert(pt1, null);
355
                                pt2 = ct.convert(pt2, null);
356
                                org.gvsig.fmap.geom.primitive.Point pt1_geom = (org.gvsig.fmap.geom.primitive.Point) geoMan
357
                                                .create(TYPES.POINT, SUBTYPES.GEOM2D);
358
                                pt1_geom.setX(pt1.getX());
359
                                pt1_geom.setY(pt1.getY());
360
                                org.gvsig.fmap.geom.primitive.Point pt2_geom = (org.gvsig.fmap.geom.primitive.Point) geoMan
361
                                                .create(TYPES.POINT, SUBTYPES.GEOM2D);
362
                                pt2_geom.setX(pt2.getX());
363
                                pt2_geom.setY(pt2.getY());
364

    
365
                                rAux.setLowerCorner(pt1_geom);
366
                                rAux.setUpperCorner(pt2_geom);
367
                        }
368
                } catch (CreateEnvelopeException e) {
369
                        // TODO Auto-generated catch block
370
                        e.printStackTrace();
371
                        this.setAvailable(false);
372
                        return null;
373
                } catch (CreateGeometryException e) {
374
                        // TODO Auto-generated catch block
375
                        e.printStackTrace();
376
                        this.setAvailable(false);
377
                        return null;
378
                }
379
                return rAux;
380

    
381
        }
382

    
383
        /*
384
         *  (non-Javadoc)
385
         * @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)
386
         */
387
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
388
                        Cancellable cancel, double scale) throws ReadException {
389
                enableStopped();
390
                // callLegendChanged(null);
391
                 lastNColumns = lastNRows = 0;
392
                 
393
                 closeAndFree();
394
                
395
                if (isWithinScale(scale)) {
396
                        Point2D p = viewPort.getOffset();
397
                        // p will be (0, 0) when drawing a view or other when painting onto
398
                        // the Layout.
399
                        visualStatus.width = viewPort.getImageWidth();
400
                        visualStatus.height = viewPort.getImageHeight();
401
                        Envelope env = viewPort.getAdjustedExtent();
402
                        visualStatus.minX = env.getMinimum(0);
403
                        visualStatus.minY = env.getMinimum(1);
404
                        visualStatus.maxX = env.getMaximum(0);
405
                        visualStatus.maxY = env.getMaximum(1);
406
                        visualStatus.rasterWidth = 0;
407
                        visualStatus.rasterHeight = 0;
408
                        visualStatus.rasterMinX = Double.MAX_VALUE;
409
                        visualStatus.rasterMinY = Double.MAX_VALUE;
410
                        visualStatus.rasterMaxX = 0;
411
                        visualStatus.rasterMaxY = 0;
412
                        visualStatus.fileNames = new String[1];
413

    
414
                        try {
415
                                if (true) {
416
                                        if (viewPort.getImageWidth() <= maxTileDrawWidth && viewPort.getImageHeight() <= maxTileDrawHeight) {
417
                                                layerRaster = new FLyrRasterSE[1];
418
                                                drawTile(g, viewPort, cancel, 0, scale, 0);
419
                                                if(layerRaster != null && layerRaster[0] != null) {
420
                                                        dataset = layerRaster[0].getDataSource();
421
                                                        getRender().setLastRenderBuffer(layerRaster[0].getRender().getLastRenderBuffer());
422
                                                        initializeRasterLayer(null, new IBuffer[][] { { layerRaster[0].getRender().getLastRenderBuffer() } });
423
                                                }
424
                                        } else {
425
                                                Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), viewPort.getImageWidth(), viewPort.getImageHeight());
426
                                                Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
427
                                                tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
428
                                                MultiRasterDataset[][] datasets = new MultiRasterDataset[tiles.getNumRows()][tiles.getNumCols()];
429
                                                IBuffer[][] buf = new IBuffer[tiles.getNumRows()][tiles.getNumCols()];
430
                                                visualStatus.fileNames = new String[tiles.getNumTiles()];
431
                                                layerRaster = new FLyrRasterSE[tiles.getNumTiles()];
432
                                                lastNColumns = tiles.getNumCols();
433
                                                lastNRows = tiles.getNumRows();
434
                                                for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
435
                                                        // drawing part
436
                                                        try {
437
                                                                ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
438
                                                                boolean painted = drawTile(g, vp, cancel, tileNr, scale, tileNr);
439
                                                                if(        layerRaster != null && 
440
                                                                        layerRaster[tileNr] != null && 
441
                                                                        painted) {
442
                                                                        datasets[(int) (tileNr / tiles.getNumCols())][tileNr % tiles.getNumCols()] = (MultiRasterDataset) layerRaster[tileNr].getDataSource().newDataset();
443
                                                                        buf[(int) (tileNr / tiles.getNumCols())][tileNr % tiles.getNumCols()] = layerRaster[tileNr].getRender().getLastRenderBuffer();
444
                                                                }
445
                                                        } catch (NoninvertibleTransformException e) {
446
                                                                e.printStackTrace();
447
                                                        }
448
                                                }
449
                                                try {
450
                                                        if (datasets != null && datasets[0][0] != null) {
451
                                                                dataset = new CompositeDataset(datasets);
452
                                                                initializeRasterLayer(datasets, buf);
453
                                                                buf = null;
454
                                                        }
455
                                                } catch (MosaicNotValidException e) {
456
                                                        throw new ReadException(
457
                                                                        "No hay continuidad en el mosaico.", e);
458
                                                } catch (LoadLayerException e) {
459
                                                        throw new ReadException(
460
                                                                        "Error inicializando la capa.", e);
461
                                                }
462
                                        }
463
                                } else {
464
                                        layerRaster = new FLyrRasterSE[1];
465
                                        drawTile(g, viewPort, cancel, 0, scale, 0);
466
                                        if(layerRaster != null && layerRaster[0] != null) {
467
                                                dataset = layerRaster[0].getDataSource();
468
                                                getRender().setLastRenderBuffer(layerRaster[0].getRender().getLastRenderBuffer());
469
                                                initializeRasterLayer(null, new IBuffer[][] { { layerRaster[0].getRender().getLastRenderBuffer() } });
470
                                        }
471
                                }
472
                        } catch (ConnectionErrorLayerException e) {
473
                                e.printStackTrace();
474
                        } catch (UnsupportedVersionLayerException e) {
475
                                e.printStackTrace();
476
                        } catch (LoadLayerException e) {
477
                                e.printStackTrace();
478
                        }
479
                }
480
                disableStopped();
481
                // callLegendChanged(null);
482
                
483
                /*Runtime r = Runtime.getRuntime();
484
                System.err.println("********************WCS**********************");
485
                System.err.println("Memoria Total: " + (r.totalMemory() / 1024) +"KB");
486
                System.err.println("Memoria Usada: " + ((r.totalMemory() - r.freeMemory()) / 1024) +"KB");
487
                System.err.println("Memoria Libre: " + (r.freeMemory() / 1024) +"KB");
488
                System.err.println("Memoria MaxMemory: " + (r.maxMemory() / 1024) +"KB");
489
                System.err.println("*********************************************");*/
490
        }
491
        
492
        /**
493
         * Closes files and releases memory (pointers to null)
494
         */
495
        private void closeAndFree() {
496
                while(readingData != null && readingData.compareTo(Thread.currentThread().toString()) != 0)
497
                        try {
498
                                Thread.sleep(100);
499
                        } catch (InterruptedException e) {
500
                        }
501
                        
502
                if(dataset != null) {
503
                        dataset.close();
504
                        dataset = null;
505
                }
506
                
507
                //Cerramos el dataset asociado a la capa si est? abierto.
508
                if(layerRaster != null) {
509
                        for (int i = 0; i < layerRaster.length; i++) {
510
                                if(layerRaster[i] != null) {
511
                                        layerRaster[i].setRemoveRasterFlag(true);
512
                                        layerRaster[i].getDataSource().close();
513
                                        layerRaster[i].getRender().free();
514
                                        layerRaster[i].getBufferFactory().free();
515
                                        layerRaster[i] = null;
516
                                }
517
                        }
518
                }
519
                getRender().free();
520
                System.gc();
521
        }
522

    
523
        /**
524
         * Acciones que se realizan despu?s de asignar la fuente de datos a
525
         * la capa raster.
526
         *
527
         * @throws LoadLayerException
528
         */
529
        private void initializeRasterLayer(MultiRasterDataset[][] datasets, IBuffer[][] buf) throws LoadLayerException {
530
                if(this.filterList != null)
531
                        getRender().setFilterList(filterList);
532

    
533
                if(this.renderBands != null)
534
                        getRender().setRenderBands(renderBands);
535
                if(datasets != null) {
536
                        String[][] names = new String[datasets.length][datasets[0].length];
537
                        for (int i = 0; i < datasets.length; i++) {
538
                                for (int j = 0; j < datasets[i].length; j++) {
539
                                        if(datasets[i][j] != null)
540
                                                names[i][j] = datasets[i][j].getDataset(0)[0].getFName();
541
                                }
542
                        }
543
                        super.setLoadParams(names);
544
                }
545
                super.init();
546
                if(buf != null) {
547
                        int drawablesBandCount = layerRaster[0].getDataSource().getBands().getDrawableBandsCount();
548
                        IBuffer buff = null;
549
                        if(dataset instanceof CompositeDataset)
550
                                buff = ((CompositeDataset)dataset).generateBuffer(buf, drawablesBandCount);
551
                        else
552
                                buff = buf[0][0];
553
                                                        
554
                        if(getRender().getLastRenderBuffer() != null)
555
                                getRender().getLastRenderBuffer().free();
556
                        getRender().setLastRenderBuffer(buff);
557
                }
558

    
559
                if (transparency == null)
560
                        transparency = new GridTransparency(getDataSource().getTransparencyFilesStatus());
561

    
562
                if(getRender().getLastTransparency() != null)
563
                        getRender().getLastTransparency().free();
564
                getRender().setLastTransparency(transparency);
565
        }
566

    
567
        /**
568
         * This is the method used to draw a tile in a WCS mosaic layer.
569
         *
570
         * @param tile
571
         *            Tile number to draw
572
         * @throws ReadException
573
         * @return true when a tile has been painted
574
         */
575
        private boolean drawTile(Graphics2D g, ViewPort vp, Cancellable cancel,
576
                        int tile, double scale, int nLyr) throws LoadLayerException, ReadException {
577

    
578
                // Compute the query geometry
579
                // 1. Check if it is within borders
580
                Envelope envelope = getFullEnvelope();
581
                Envelope vpEnvelope = vp.getAdjustedExtent();
582
                if (!vpEnvelope.intersects(envelope)) {
583
                        return false;
584
                }
585

    
586
                // 2. Compute extent to be requested.
587
                Rectangle2D bBox = new Rectangle2D.Double();
588
                Rectangle2D.intersect(getRectable2DFromEnvelope(vpEnvelope),
589
                                getRectable2DFromEnvelope(envelope), bBox);
590

    
591
                // 3. Compute size in pixels
592
                double scalex = vp.getAffineTransform().getScaleX();
593
                double scaley = vp.getAffineTransform().getScaleY();
594
                int wImg = (int) Math.ceil(Math.abs(bBox.getWidth() * scalex) + 1);
595
                int hImg = (int) Math.ceil(Math.abs(bBox.getHeight() * scaley) + 1);
596
                Dimension sz = new Dimension(wImg, hImg);
597

    
598
                if ((wImg <= 0) || (hImg <= 0)) {
599
                        return false;
600
                }
601

    
602
                try {
603
                        sz = new Dimension(wImg, hImg);
604

    
605
                        wcsStatus.setCoveraName( coverageName );
606
                        wcsStatus.setExtent( bBox );
607
                        wcsStatus.setFormat( format );
608
                        wcsStatus.setHeight( hImg );
609
                        wcsStatus.setWidth( wImg );
610
                        wcsStatus.setSrs(srs);
611
                        wcsStatus.setParameters( parameter );
612
                        wcsStatus.setTime( time );
613
                        wcsStatus.setOnlineResource((String) onlineResources.get("GetCoverage"));
614

    
615
                        File f = getDriver().getCoverage(wcsStatus, new MyCancellable(cancel));
616
                        if (f == null) {
617
                                return false;
618
                        }
619
                        String nameWordFile = f.getPath() + getExtensionWorldFile();
620
                        org.gvsig.andami.Utilities.createTemp(nameWordFile, this.getDataWorldFile(bBox, sz));
621

    
622
                        IStatusRaster status = super.getStatus();
623
                        if(status!=null && firstLoad){
624
                                try {
625
                                        status.applyStatus(this);
626
                                } catch (NotSupportedExtensionException e) {
627
                                        throw new ReadException("", e);
628
                                } catch (RasterDriverException e) {
629
                                        throw new ReadException("", e);
630
                                } catch (FilterTypeException e) {
631
                                        throw new ReadException("", e);
632
                                }
633
                                firstLoad = false;
634
                        }
635
                        ViewPortData vpData = new ViewPortData(
636
                                vp.getProjection(), new Extent(bBox), sz );
637
                        vpData.setMat(vp.getAffineTransform());
638

    
639
                        String filePath = f.getAbsolutePath();
640
                        visualStatus.fileNames[tile] = filePath;
641

    
642
                        try {
643
                                rasterProcess(filePath, g, vp, scale, cancel, nLyr);
644
                        } catch (FilterTypeException e) {
645
                        }
646

    
647
//                        this.getRender().draw(g, vpData);
648
//                        rasterProcess(g, vpData, f);
649

    
650
//                } catch (ValidationException e) {
651
//                        UnknownResponseFormatExceptionType type =
652
//                                new UnknownResponseFormatExceptionType();
653
//                        type.setLayerName(getName());
654
//                        try {
655
//                                type.setDriverName(getDriver().getName());
656
//                        } catch (Exception e1) {
657
//                                e1.printStackTrace();
658
//                        }
659
//                        type.setFormat(format);
660
//                        type.setHost(host);
661
//                        type.setProtocol("WCS");
662
                        // ReadException exception = new
663
                        // ReadException("unknown_response_format",type);
664
//                        throw exception;
665
//        azabala                throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
666
//                }
667
//                catch (UnsupportedVersionLayerException e) {
668
//                        UnsuportedProtocolVersionExceptionType type =
669
//                                new UnsuportedProtocolVersionExceptionType();
670
//                        type.setLayerName(getName());
671
//                        try {
672
//                                type.setDriverName(getDriver().getName());
673
//                        } catch (Exception ex){
674
//                        }
675
//                        type.setUrl(host);
676
                        // throw new ReadException(PluginServices.getText(this,
677
                        // "version_conflict"), e, type);
678

    
679
//        azabala                throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
680
                } catch (IOException e) {
681
//                        ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
682
//                        type.setLayerName(getName());
683
//                        try {
684
//                                type.setDriverName(getDriver().getName());
685
//                        } catch (Exception e1) {
686
//                        }
687
//                        type.setHost(host);
688
                        throw new ConnectionErrorLayerException(getName(),e);
689
                }
690
//                catch (WCSLayerException e) {
691
////azabala: la capturamos y la convertimos en DriverException
692
//                        WCSDriverExceptionType type = new WCSDriverExceptionType();
693
//                        type.setLayerName(getName());
694
//                        try {
695
//                                type.setDriverName(getDriver().getName());
696
//                        } catch (Exception e1) {
697
//                        }
698
//                        type.setWcsStatus(wcsStatus);
699
//                        this.setVisible(false);
700
//                        throw new WDriverException("Error WCS", e,  type);
701
//
702
////            JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
703
//
704
//        }//
705
                catch (WCSDriverException e) {
706
                        throw new LoadLayerException(getName(),e);
707
                } catch (IllegalStateException e) {
708
                        throw new LoadLayerException(getName(),e);
709
                }
710
                return true;
711
        }
712

    
713
        /**
714
         * Devuelve el FMapWMSDriver.
715
         *
716
         * @return FMapWMSDriver
717
         *
718
         * @throws IllegalStateException
719
         * @throws ValidationException
720
         * @throws UnsupportedVersionLayerException
721
         * @throws IOException
722
         */
723
        private FMapWCSDriver getDriver() throws IllegalStateException, IOException {
724
                if (wcs == null) {
725
                        wcs = FMapWCSDriverFactory.getFMapDriverForURL(host);
726
                }
727
                return wcs;
728
        }
729

    
730
        /**
731
         * Calcula el contenido del fichero de georreferenciaci?n de una imagen.
732
         * @param bBox Tama?o y posici?n de la imagen (en coordenadas de usuario)
733
         * @param sz Tama?o de la imagen en pixeles.
734
         * @return el 'WorldFile', como String.
735
         * @throws IOException
736
         */
737
        public String getDataWorldFile(Rectangle2D bBox, Dimension sz) throws IOException {
738
                StringBuffer data = new StringBuffer();
739
                data.append((bBox.getMaxX() - bBox.getMinX())/(sz.getWidth() - 1)+"\n");
740
                data.append("0.0\n");
741
                data.append("0.0\n");
742
                data.append("-"+(bBox.getMaxY() - bBox.getMinY())/(sz.getHeight() - 1)+"\n");
743
                data.append(""+bBox.getMinX()+"\n");
744
                data.append(""+bBox.getMaxY()+"\n");
745
                return data.toString();
746
        }
747

    
748
        /**
749
         * Carga y dibuja el raster usando la librer?a
750
         *
751
         * @param filePath
752
         *            Ruta al fichero en disco
753
         * @param g
754
         *            Graphics2D
755
         * @param vp
756
         *            ViewPort
757
         * @param scale
758
         *            Escala para el draw
759
         * @param cancel
760
         *            Cancelaci?n para el draw
761
         * @throws ReadException
762
         * @throws LoadLayerException
763
         */
764
        private void rasterProcess(String filePath, Graphics2D g, ViewPort vp,
765
                        double scale, Cancellable cancel, int nLyr) throws ReadException,
766
                        LoadLayerException, FilterTypeException {
767
                //Cargamos el dataset con el raster de disco.
768
                layerRaster[nLyr] = FLyrRasterSE.createLayer("", filePath, vp.getProjection());
769
                //layerRaster[nLyr].getRender().setBufferFactory(layerRaster[nLyr].getBufferFactory());
770
                
771
                if(visualStatus.dataType == IBuffer.TYPE_UNDEFINED && layerRaster[nLyr].getDataType() != null)
772
                        visualStatus.dataType = layerRaster[nLyr].getDataType()[0];
773
                if(visualStatus.bandCount == 0 && layerRaster[nLyr].getBandCount() != 0)
774
                        visualStatus.bandCount = layerRaster[nLyr].getBandCount();
775

    
776
                if (getLegend() == null)
777
                        lastLegend = layerRaster[nLyr].getLegend();
778

    
779
                //En caso de cargar un proyecto con XMLEntity se crean los filtros
780
                if(filterArguments != null) {
781
                        RasterFilterList fl = new RasterFilterList();
782
                        fl.addEnvParam("IStatistics", layerRaster[nLyr].getDataSource().getStatistics());
783
                        fl.addEnvParam("MultiRasterDataset", layerRaster[nLyr].getDataSource());
784
                        fl.setInitDataType(layerRaster[nLyr].getDataType()[0]);
785
                        RasterFilterListManager filterListManager = new RasterFilterListManager(fl);
786
                        filterListManager.createFilterListFromStrings(filterArguments);
787
                        StatusLayerRaster.enhancedCompV10(filterArguments, layerRaster[nLyr], filterListManager);
788
                        filterArguments = null;
789
                        filterList = fl;
790
                }
791

    
792
                //Como el raster se carga a cada zoom el render se crea nuevamente y la lista de
793
                //filtros siempre estar? vacia a cada visualizaci?n. Para evitarlo tenemos que
794
                //guardar la lista de filtro aplicada en la visualizaci?n anterior.
795
                if (filterList != null)
796
                        layerRaster[nLyr].getRender().setFilterList(filterList);
797
                if (transparency == null)
798
                        transparency = layerRaster[nLyr].getRender().getLastTransparency();
799
                if (transparency != null)
800
                        layerRaster[nLyr].getRender().setLastTransparency(transparency);
801
                if (renderBands != null)
802
                        layerRaster[nLyr].getRender().setRenderBands(renderBands);
803

    
804
                //Dibujamos
805
                layerRaster[nLyr].draw(null, g, vp, cancel, scale);
806

    
807
                //La primera vez asignamos la lista de filtros asociada al renderizador. Guardamos una referencia
808
                //en esta clase para que a cada zoom no se pierda.
809
                if (filterList == null)
810
                        filterList = layerRaster[nLyr].getRender().getFilterList();
811
                if (renderBands == null)
812
                        renderBands = layerRaster[nLyr].getRender().getRenderBands();
813
        }
814

    
815
        /*
816
         * (non-Javadoc)
817
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#cloneLayer()
818
         */
819
        public FLayer cloneLayer() throws Exception {
820
                Object par = null;
821
                if (dataset instanceof CompositeDataset)
822
                        par = ((CompositeDataset) dataset).getFileNames();
823
                
824
                FLyrRasterSE newLayer = FLyrRasterSE.createLayer(this.getName(), par, this.getProjection());
825

    
826
                ArrayList filters = getRender().getFilterList().getStatusCloned();
827
                newLayer.getRender().getFilterList().setStatus(filters);
828

    
829
                return newLayer;
830
        }
831

    
832
        /*
833
         * (non-Javadoc)
834
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderFilterList()
835
         */
836
        public RasterFilterList getRenderFilterList(){
837
                return (filterList != null) ? filterList : getRender().getFilterList();
838
        }
839

    
840
        /*
841
         * (non-Javadoc)
842
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderFilterList(org.gvsig.raster.grid.filter.RasterFilterList)
843
         */
844
        public void setRenderFilterList(RasterFilterList filterList) {
845
                this.filterList = filterList;
846
                super.getRender().setFilterList(filterList);
847
        }
848

    
849
        /*
850
         * (non-Javadoc)
851
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderTransparency()
852
         */
853
        public GridTransparency getRenderTransparency() {
854
                return getRender().getLastTransparency();
855
//                return (transparency != null) ? transparency : getRender().getLastTransparency();
856
        }
857

    
858
        /*
859
         * (non-Javadoc)
860
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getRenderBands()
861
         */
862
        public int[] getRenderBands() {
863
                return (renderBands != null) ? renderBands : getRender().getRenderBands();
864
        }
865

    
866
        /*
867
         * (non-Javadoc)
868
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderBands(int[])
869
         */
870
        public void setRenderBands(int[] renderBands) {
871
                this.renderBands = renderBands;
872
                getRender().setRenderBands(renderBands);
873
        }
874

    
875
        /*
876
         * (non-Javadoc)
877
         * @see org.gvsig.fmap.raster.layers.FLyrRasterSE#print(java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort, com.iver.utiles.swing.threads.Cancellable, double, javax.print.attribute.PrintRequestAttributeSet)
878
         */
879
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
880
                        double scale, PrintRequestAttributeSet properties)
881
                        throws ReadException {
882
                if (isVisible() && isWithinScale(scale)){
883
                        draw(null, g, viewPort, cancel, scale);
884
                }
885
        }
886

    
887
        /**
888
         * Returns the XMLEntity containing the necessary info for reproduce
889
         * the layer.
890
         *
891
         * Devuelve el XMLEntity con la informaci?n necesaria para reproducir
892
         * la capa.
893
         *
894
         * @return XMLEntity.
895
         * @throws XMLException
896
         */
897
        public XMLEntity getXMLEntity() throws XMLException {
898
                XMLEntity xml = super.getXMLEntity();
899

    
900
                xml.putProperty("wcs.host", getHost());
901
                xml.putProperty("wcs.fullExtent", StringUtilities
902
                                .rect2String(getRectable2DFromEnvelope(this.fullEnvelope)));
903
                xml.putProperty("wcs.layerQuery", coverageName );
904
                xml.putProperty("wcs.format", format );
905
                xml.putProperty("wcs.srs", srs );
906
                xml.putProperty("wcs.time", time );
907
                xml.putProperty("wcs.parameter", parameter );
908
                xml.putProperty("wcs.coverageName", coverageName );
909
                xml.putProperty("wcs.maxResX", maxRes.getX());
910
                xml.putProperty("wcs.maxResY", maxRes.getY());
911

    
912
                Iterator it = onlineResources.keySet().iterator();
913
                String strOnlines = "";
914
                while (it.hasNext()) {
915
                        String key = (String) it.next();
916
                        String value = (String) onlineResources.get(key);
917
                        strOnlines += key+"~##SEP2##~"+value;
918
                        if (it.hasNext()) {
919
                                strOnlines += "~##SEP1##~";
920
                        }
921
                }
922
                xml.putProperty("onlineResources", strOnlines);
923

    
924
                IStatusRaster status = super.getStatus();
925
                if (status!=null) {
926
                        status.getXMLEntity(xml, true, this);
927
                } else{
928
                        status = new StatusLayerRaster();
929
                        status.getXMLEntity(xml, true, this);
930
                }
931
                return xml;
932
        }
933

    
934
        /**
935
         * Reproduces the layer from an XMLEntity.
936
         *
937
         * A partir del XMLEntity reproduce la capa.
938
         *
939
         * @param xml
940
         *            XMLEntity
941
         *
942
         * @throws XMLException
943
         * @throws DriverException
944
         * @throws ReadException
945
         */
946
        public void setXMLEntity(XMLEntity xml) throws XMLException {
947
                super.setXMLEntity(xml);
948

    
949
                // host
950
                try {
951
                        host = new URL(xml.getStringProperty("wcs.host"));
952
                } catch (MalformedURLException e) {
953
                        throw new XMLLayerException("", e);
954
                }
955

    
956
                // full extent
957
                fullEnvelope = getEnvelopeFromRectable2D(StringUtilities
958
                                .string2Rect(xml
959
                                .getStringProperty("wcs.fullExtent")));
960

    
961
                // coverageQuery
962
                coverageName = xml.getStringProperty("wcs.layerQuery");
963

    
964
                // format
965
                format = xml.getStringProperty("wcs.format");
966

    
967
                // srs
968
                srs = xml.getStringProperty("wcs.srs");
969

    
970
                // time
971
                time = xml.getStringProperty("wcs.time");
972

    
973
                // parameter
974
                parameter = xml.getStringProperty("wcs.parameter");
975

    
976
                // coverage name
977
                coverageName = xml.getStringProperty("wcs.coverageName");
978

    
979
                // max resolution
980
                if (xml.contains("wcs.maxRes")) {
981
                        maxRes = new Point2D.Double(xml.getDoubleProperty("wcs.maxRes"), xml.getDoubleProperty("wcs.maxRes"));
982
                } else if (xml.contains("wcs.maxResX") && xml.contains("wcs.maxResY")) {
983
                        maxRes = new Point2D.Double(xml.getDoubleProperty("wcs.maxResX"), xml.getDoubleProperty("wcs.maxResY"));
984
                }
985

    
986
                // OnlineResources
987
                                if (xml.contains("onlineResources")) {
988
                                        String[] operations = xml.getStringProperty("onlineResources").split("~##SEP1##~");
989
                                        for (int i = 0; i < operations.length; i++) {
990
                                String[] resources = operations[i].split("~##SEP2##~");
991
                                if (resources.length==2 && resources[1]!="") {
992
                                        onlineResources.put(resources[0], resources[1]);
993
                                }
994
                        }
995
                                }
996
                String claseStr = null;
997
                if (xml.contains("raster.class")) {
998
                        claseStr = xml.getStringProperty("raster.class");
999
                }
1000

    
1001
                IStatusRaster status = super.getStatus();
1002
                if (status!=null) {
1003
                        status.setXMLEntity(xml, this);
1004
                } else {
1005
                        //Cuando cargamos un proyecto
1006

    
1007
                        if(claseStr!=null && !claseStr.equals("")){
1008
                                try{
1009
                                        // Class clase =
1010
                                        // LayerFactory.getLayerClassForLayerClassName(claseStr);
1011
                                        Class clase = FLyrRasterSE.class;
1012
                                        Constructor constr = clase.getConstructor(null);
1013
                                        status = (IStatusRaster)constr.newInstance(null);
1014
                                        if(status != null) {
1015
                                                ((StatusLayerRaster)status).setNameClass(claseStr);
1016
                                                status.setXMLEntity(xml, this);
1017
                                                filterArguments = status.getFilterArguments();
1018
//                                                transparency = status.getTransparency();
1019
                                                renderBands = status.getRenderBands();
1020
                                                ColorTable ct = status.getColorTable();
1021
                                                if(ct != null) {
1022
                                                        setLastLegend(ct);
1023
                                                }
1024
                                        }
1025
                                        // } catch(ClassNotFoundException exc) {
1026
                                        // exc.printStackTrace();
1027
                                } catch(InstantiationException exc) {
1028
                                        exc.printStackTrace();
1029
                                } catch(IllegalAccessException exc) {
1030
                                        exc.printStackTrace();
1031
                                } catch(NoSuchMethodException exc) {
1032
                                        exc.printStackTrace();
1033
                                } catch(InvocationTargetException exc) {
1034
                                        exc.printStackTrace();
1035
                                } catch (FilterTypeException exc) {
1036
                                        exc.printStackTrace();
1037
                                }
1038
                        }
1039
                }
1040
                firstLoad = true;
1041
        }
1042

    
1043
        public void setCoverageName(String coverageName) {
1044
                this.coverageName = coverageName;
1045
        }
1046

    
1047
        public void setParameter(String parametersString) {
1048
                if (this.parameter == parametersString){
1049
                        return;
1050
                }
1051
                if (this.parameter != null && this.parameter.equals(parametersString)){
1052
                        return;
1053
                }
1054
                this.parameter = parametersString;
1055
                this.updateDrawVersion();
1056
        }
1057

    
1058
        public void setTime(String time) {
1059
                if (this.time == time){
1060
                        return;
1061
                }
1062
                if (this.time != null && this.time.equals(time)){
1063
                        return;
1064
                }
1065
                this.time = time;
1066
                this.updateDrawVersion();
1067
        }
1068

    
1069
        public void setSRS(String srs) {
1070
                if (this.srs == srs){
1071
                        return;
1072
                }
1073
                if (this.srs != null && this.srs.equals(srs)){
1074
                        return;
1075
                }
1076
                this.srs = srs;
1077
                this.updateDrawVersion();
1078
                setProjection(CRSFactory.getCRS(srs));
1079
        }
1080

    
1081
        public void setFormat(String format) {
1082
                if (this.format == format){
1083
                        return;
1084
                }
1085
                if (this.format != null && this.format.equals(format)){
1086
                        return;
1087
                }
1088
                this.format = format;
1089
                this.updateDrawVersion();
1090
        }
1091

    
1092

    
1093
        /**
1094
         * Inserta el URL.
1095
         *
1096
         * @param host String.
1097
         * @throws MalformedURLException
1098
         */
1099
        public void setHost(String host) {
1100
                try {
1101
                        setHost(new URL(host));
1102
                } catch (MalformedURLException e) {
1103

    
1104
                }
1105
        }
1106

    
1107
        /**
1108
         * Inserta el URL.
1109
         *
1110
         * @param host URL.
1111
         */
1112
        public void setHost(URL host) {
1113
                if (this.host == host){
1114
                        return;
1115
                }
1116
                if (this.host != null && this.host.equals(host)){
1117
                        return;
1118
                }
1119
                this.host = host;
1120
                this.updateDrawVersion();
1121
        }
1122

    
1123

    
1124
        /**
1125
         * Devuelve el URL.
1126
         *
1127
         * @return URL.
1128
         */
1129
        public URL getHost() {
1130
                return host;
1131
        }
1132

    
1133
        /**
1134
         * Remote source layers have a bunch of properties that are required for get them from
1135
         * the servers. This method supplies a hash table containing any needed field. This hash
1136
         * table may be used to let the client to connect to a server and restore a previously saved
1137
         * layer. So, the layer itself may not be saved to the disk since the actual saved
1138
         * info is just its properties.
1139
         *
1140
         * @return Returns a hash table containing all the required information for
1141
         * set up a wms layer
1142
         */
1143
        public Hashtable getProperties(){
1144
                Hashtable info = new Hashtable();
1145
                info.put(   "name", coverageName);
1146
                info.put(   "host", getHost());
1147
                info.put(    "crs", srs);
1148
                info.put( "format", format);
1149
                String str = time;
1150
                if (str==null) {
1151
                        str = "";
1152
                }
1153
                info.put(   "time", str);
1154
                str = parameter;
1155
                if (str==null) {
1156
                        str = "";
1157
                }
1158
                info.put("parameter", str);
1159

    
1160
                return info;
1161
        }
1162

    
1163
        /**
1164
         * Obtiene la extensi?n del fichero de georreferenciaci?n
1165
         * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
1166
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
1167
         */
1168
        private String getExtensionWorldFile(){
1169
                String extWorldFile = ".wld";
1170
                        if (format.equals("image/tif") || format.equals("image/tiff")) {
1171
                                extWorldFile = ".tfw";
1172
                        }
1173
                        if (format.equals("image/jpeg")) {
1174
                                extWorldFile = ".jpgw";
1175
                        }
1176
                        return extWorldFile;
1177
        }
1178

    
1179
        public void setMaxResolution(Point2D maxResolution) {
1180
                if (this.maxRes == maxResolution){
1181
                        return;
1182
                }
1183
                if (this.maxRes != null && this.maxRes.equals(maxResolution)){
1184
                        return;
1185
                }
1186
                this.maxRes = maxResolution;
1187
                this.updateDrawVersion();
1188
        }
1189

    
1190
        /**
1191
         * <p>
1192
         * Gets the max resolution allowed by the coverage. Requesting a higher resolution
1193
         * than this value does not cause any error, but the info responsed is just an
1194
         * interpolation. <br>
1195
         * </p>
1196
         *
1197
         * <p>
1198
         * In exchange for obtaining a greater file and without additional information,
1199
         * we can easily fit it into the View. <br>
1200
         * </p>
1201
         *
1202
         * <p>
1203
         * Obtiene la resoluci?n m?xima soportada por la cobertura. La petici?n
1204
         * de una resoluci?n superior a la soportada no provoca ning?n error, aunque
1205
         * la informaci?n obtenida s?lo es una mera interpolaci?n de informaci?n. <br>
1206
         * </p>
1207
         *
1208
         * <p>
1209
         * A cambio de obtener un archivo mayor y sin informaci?n adicional, podemos
1210
         * f?cilmente acoplarlo a la vista. <br>
1211
         * </p>
1212
         *
1213
         * @return double
1214
         */
1215
        public Point2D getMaxResolution() {
1216
                if (maxRes==null) {
1217
                        maxRes = wcs.getMaxResolution(coverageName);
1218
                }
1219
                return maxRes;
1220
        }
1221

    
1222

    
1223
        public void setDriver(FMapWCSDriver driver) {
1224
                if (driver == this.wcs){
1225
                        return;
1226
                }
1227
                this.wcs = driver;
1228
                this.updateDrawVersion();
1229
        }
1230

    
1231
        /*
1232
         *  (non-Javadoc)
1233
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1234
         */
1235
        public int[] getTileSize() {
1236
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1237
                return size;
1238
        }
1239

    
1240
        /*
1241
         * (non-Javadoc)
1242
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getTocImageIcon()
1243
         */
1244
        public String getTocImageIcon() {
1245
                return "ico-WCS-Layer";
1246
        }
1247

    
1248
        /*
1249
         *  (non-Javadoc)
1250
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1251
         */
1252
        public boolean isTiled() {
1253
                return mustTileDraw;
1254
        }
1255

    
1256
        /*
1257
         * (non-Javadoc)
1258
         * @see org.gvsig.fmap.raster.layers.FLyrRasterSE#isActionEnabled(int)
1259
         */
1260
        public boolean isActionEnabled(int action) {
1261
                switch (action) {
1262
                        case IRasterLayerActions.ZOOM_PIXEL_RESOLUTION:
1263
                        case IRasterLayerActions.FLYRASTER_BAR_TOOLS:
1264
                        case IRasterLayerActions.BANDS_FILE_LIST:
1265
                        case IRasterLayerActions.GEOLOCATION:
1266
                        case IRasterLayerActions.PANSHARPENING:
1267
                        case IRasterLayerActions.SAVE_COLORINTERP:
1268
                                return false;
1269
                        case IRasterLayerActions.BANDS_RGB:
1270
                        case IRasterLayerActions.REMOTE_ACTIONS:
1271
                                return true;
1272
                }
1273

    
1274
                return super.isActionEnabled(action);
1275
        }
1276

    
1277
        /*
1278
         * (non-Javadoc)
1279
         * @see org.gvsig.fmap.raster.layers.FLyrRasterSE#overviewsSupport()
1280
         */
1281
        public boolean overviewsSupport() {
1282
                return false;
1283
        }
1284

    
1285
        /**
1286
         * Inserta la extensi?n total de la capa.
1287
         *
1288
         * @param fullExtent
1289
         *            Rect?ngulo.
1290
         * @deprecated
1291
         */
1292
        public void setFullExtent(Rectangle2D fullExtent) {
1293
                this.setFullEnvelope(this.getEnvelopeFromRectable2D(fullExtent));
1294
        }
1295

    
1296
        /**
1297
         * Inserta la extensi?n total de la capa en la proyeccion original.
1298
         *
1299
         * @param fullExtent
1300
         *            Rect?ngulo.
1301
         */
1302
        public void setFullEnvelope(Envelope envelope) {
1303
                Envelope cur = this.getFullEnvelope();
1304
                if (cur == envelope) {
1305
                        return;
1306
                }
1307
                if (cur != null && cur.equals(envelope)) {
1308
                        return;
1309
                }
1310

    
1311
                this.fullEnvelope = envelope;
1312
                this.updateDrawVersion();
1313
        }
1314

    
1315
        private Rectangle2D.Double getRectable2DFromEnvelope(Envelope env) {
1316
                return new Rectangle2D.Double(env.getMinimum(0), env.getMinimum(1), env
1317
                                .getLength(0), env.getLength(1));
1318
        }
1319

    
1320
        private Envelope getEnvelopeFromRectable2D(Rectangle2D rect) {
1321
                GeometryManager geoMan = GeometryLocator.getGeometryManager();
1322
                Envelope rAux = null;
1323
                try {
1324
                        rAux = geoMan.createEnvelope(rect.getMinX(), rect.getMinY(), rect
1325
                                        .getMaxX(), rect.getMaxY(), SUBTYPES.GEOM2D);
1326

    
1327
                } catch (Exception e) {
1328
                        e.printStackTrace();
1329
                        return null;
1330
                }
1331
                return rAux;
1332
        }
1333
        
1334
        /*
1335
         * (non-Javadoc)
1336
         * @see org.gvsig.fmap.raster.layers.FLyrRasterSE#getFileLayer()
1337
         */
1338
        public FLayer getFileLayer() {
1339
                if(layerRaster != null && layerRaster[0] != null) {
1340
                        FLyrRasterSE ly = null;
1341
                        if(lastNColumns == 0 && lastNRows == 0) {  //Una capa sin tilear => MultirasterDataset
1342
                                try {
1343
                                        ly = createLayer(layerRaster[0].getName(), layerRaster[0].getLoadParams(), layerRaster[0].getProjection());
1344
                                } catch (LoadLayerException e) {
1345
                                        return null;
1346
                                }
1347
                        } else {  //Capa tileada ==> CompositeDataset
1348
                                String[][] s = new String[lastNRows][lastNColumns];
1349

    
1350
                                for (int i = 0; i < s.length; i++) {
1351
                                        for (int j = 0; j < s[0].length; j++) {
1352
                                                s[i][j] = ((FLyrRasterSE)layerRaster[i]).getDataSource().getNameDatasetStringList(i, j)[0];
1353
                                        }
1354
                                }
1355
                                try {
1356
                                        ly = createLayer("preview", s, getProjection());
1357
                                } catch (LoadLayerException e) {
1358
                                        return null;
1359
                                }
1360
                        }
1361
                        return ly;
1362
                }
1363
                return null;
1364
        }
1365

    
1366
}