Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extWCS / src / com / iver / cit / gvsig / fmap / layers / FLyrWCS.java @ 13312

History | View | Annotate | Download (30.4 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.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

    
66
import org.exolab.castor.xml.ValidationException;
67
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
68
import org.gvsig.fmap.raster.layers.IRasterLayerActions;
69
import org.gvsig.fmap.raster.layers.StatusLayerRaster;
70
import org.gvsig.fmap.raster.layers.StatusRasterInterface;
71
import org.gvsig.raster.dataset.FileNotOpenException;
72
import org.gvsig.raster.dataset.InvalidSetViewException;
73
import org.gvsig.raster.dataset.NotSupportedExtensionException;
74
import org.gvsig.raster.dataset.RasterDataset;
75
import org.gvsig.raster.dataset.RasterDriverException;
76
import org.gvsig.raster.datastruct.Extent;
77
import org.gvsig.raster.datastruct.ViewPortData;
78
import org.gvsig.raster.grid.filter.RasterFilterList;
79
import org.gvsig.remoteClient.wcs.WCSStatus;
80
import org.gvsig.remoteClient.wms.ICancellable;
81

    
82
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
83
import com.hardcode.gdbms.engine.data.driver.DriverException;
84
import com.iver.cit.gvsig.exceptions.layers.ConnectionErrorLayerException;
85
import com.iver.cit.gvsig.exceptions.layers.LoadLayerException;
86
import com.iver.cit.gvsig.exceptions.layers.UnsupportedVersionLayerException;
87
import com.iver.cit.gvsig.fmap.ViewPort;
88
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
89
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
90
import com.iver.cit.gvsig.fmap.drivers.wcs.FMapWCSDriver;
91
import com.iver.cit.gvsig.fmap.drivers.wcs.FMapWCSDriverFactory;
92
import com.iver.cit.gvsig.fmap.drivers.wcs.WCSDriverException;
93
import com.iver.cit.gvsig.fmap.layers.layerOperations.StringXMLItem;
94
import com.iver.cit.gvsig.fmap.layers.layerOperations.XMLItem;
95
import com.iver.utiles.DoubleUtilities;
96
import com.iver.utiles.StringUtilities;
97
import com.iver.utiles.XMLEntity;
98
import com.iver.utiles.swing.threads.Cancellable;
99

    
100

    
101
/**
102
 * Class for the WCS layer.
103
 *
104
 * Capa para el WCS.
105
 *
106
 * @author jaume - jaume.dominguez@iver.es
107
 */
108
public class FLyrWCS extends FLyrRasterSE {
109
        private FMapWCSDriver wcs = null;
110

    
111
        private URL                                                 host;
112
        private String                                                coverageName;
113
        private Rectangle2D                                        fullExtent;
114
        private String                                                format;
115
        private String                                                srs;
116
        private String                                                time;
117
        private String                                                parameter;
118
        private Point2D                                                maxRes;
119
        private Hashtable                                         onlineResources = new Hashtable();
120

    
121
        private WCSStatus                                        wcsStatus = new WCSStatus();
122

    
123
        private int                                                 posX = 0, posY = 0;
124
        private double                                                 posXWC = 0, posYWC = 0;
125
        private int                                                 r = 0, g = 0, b = 0;
126
        private boolean                                         firstLoad = false;
127
        private VisualStatus                                visualStatus = new VisualStatus();
128

    
129
        private boolean                                         mustTileDraw = false;
130
        private int                                                 maxTileDrawWidth  = 1023;
131
        private int                                                        maxTileDrawHeight = 1023;
132
        private int                                                 maxTilePrintWidth  = 250;
133
        private int                                                        maxTilePrintHeight = 250;
134
        /**
135
         * Lista de filtros aplicada en la renderizaci?n
136
         */
137
        private RasterFilterList            filterList = null;
138
        
139
        
140
        private class MyCancellable implements ICancellable
141
        {
142

    
143
                private Cancellable original;
144
                public MyCancellable(Cancellable cancelOriginal)
145
                {
146
                        this.original = cancelOriginal;
147
                }
148
                public boolean isCanceled() {
149
                        return original.isCanceled();
150
                }
151

    
152
        }
153
        
154
        public FLyrWCS(){
155
                super();
156
        }
157

    
158
        public FLyrWCS(Map args) throws DriverIOException{
159
                FMapWCSDriver drv = null;
160
                String host = (String)args.get("HOST");
161
                String sCoverage = (String) args.get((String) "COVERAGE");
162

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

    
176
                try{
177
                        if (!drv.connect(false, null)){
178
                                throw new DriverIOException("Can't connect to host '" + host + "'.");
179
                        }
180
                }catch(Exception e){
181
                        throw new DriverIOException("Can't connect to host '" + host + "'.");
182
                }
183

    
184
                WCSLayer wcsNode = drv.getLayer(sCoverage);
185

    
186
                if (wcsNode == null){
187
                        throw new DriverIOException("The server '" + host + "' doesn't has the coverage '" + sCoverage + "'.");
188
                }
189

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

    
202
        }
203

    
204
        /**
205
         * Clase que contiene los datos de visualizaci?n de WCS. Tiene datos que representan al
206
         * raster en la vista. Este raster puede estar compuesto por tiles por lo que valores
207
         * como el ancho total o el m?nimo o m?ximo deben ser calculados a partir de todos los
208
         * tiles visualizados.
209
         * @author Nacho Brodin (brodin_ign@gva.es)
210
         */
211
        private class VisualStatus {
212
                /**
213
                 * Ancho y alto de la imagen o del conjunto de tiles si los tiene. Coincide con
214
                 * el ancho y alto del viewPort
215
                 */
216
                private        int                                                        width = 0, height = 0;
217
                private double                                                minX = 0D, minY = 0D, maxX = 0D, maxY = 0D;
218
                private int                                                 bandCount = 0;
219
                private int                                                        dataType = DataBuffer.TYPE_UNDEFINED;
220

    
221
                /**
222
                 * Ancho y alto total del raster que ser? la suma de todos los tiles.
223
                 */
224
                private        int                                                        rasterWidth = 0, rasterHeight = 0;
225
                private        double                                                rasterMinX = Double.MAX_VALUE, rasterMinY = Double.MAX_VALUE;
226
                private        double                                                rasterMaxX = 0, rasterMaxY = 0;
227
                /**
228
                 * Lista de nombre de fichero que componen toda la visualizaci?n.
229
                 */
230
                private String[]                                        fileNames = null;
231
        }
232

    
233
        /**
234
         * @deprecated
235
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#getInfo
236
         */
237
        public String queryByPoint(Point p) {
238
                String data = "<file:"+getName().replaceAll("[^a-zA-Z0-9]","")+">\n";
239
                ArrayList attr = this.getAttributes();
240
                data += "  <raster\n";
241
                data += "    File=\""+getName()+"\"\n";
242
                for (int i=0; i<attr.size(); i++) {
243
                        Object [] a = (Object []) attr.get(i);
244

    
245
                        data += "    "+a[0].toString()+"=";
246
                        if (a[1].toString() instanceof String)
247
                                data += "\""+a[1].toString()+"\"\n";
248
                        else
249
                                data += a[1].toString()+"\n";
250
                }
251
                data += "    Point=\""+posX+" , "+posY+"\"\n";
252
                data += "    Point_WC=\""+posXWC+" , "+posYWC+"\"\n";
253
                data += "    RGB=\""+r+", "+g+", "+b+"\"\n";
254
                data += "  />\n";
255

    
256
                data += "</file:"+getName().replaceAll("[^a-zA-Z0-9]","")+">\n";
257
                System.out.println(data);
258
                return data;
259
        }
260
        
261
        /**
262
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#getInfo
263
         */
264
        public XMLItem[] getInfo(Point point, double tolerance, Cancellable cancel ) throws ReadDriverException {
265
                String data = "<file:"+getName().replaceAll("[^a-zA-Z0-9]","")+">\n";
266

    
267
                Point2D pReal = getMapContext().getViewPort().toMapPoint(point);
268
                Point2D px = null;
269
                if(        pReal.getX() > this.getMinX() &&
270
                        pReal.getX() < this.getMaxX() &&
271
                        pReal.getY() > this.getMinY() &&
272
                        pReal.getY() < this.getMaxY()){
273

    
274
                        px = new Point2D.Double();
275
                        double w = (visualStatus.rasterMaxX - visualStatus.rasterMinX);
276
                        double h = (visualStatus.rasterMaxY - visualStatus.rasterMinY);
277
                        px.setLocation(((pReal.getX() - visualStatus.rasterMinX) * visualStatus.rasterWidth) / w,
278
                                                        ((visualStatus.rasterMaxY - pReal.getY()) * visualStatus.rasterHeight) / h);
279
                }
280

    
281
                int[] rgb = this.getPixel(pReal.getX(), pReal.getY());
282

    
283
                StringXMLItem[] item = new StringXMLItem[1];
284

    
285
                data += "  <raster\n";
286
                data += "    View_Point=\""+point.getX()+" , "+point.getY()+"\"\n";
287
                data += "    World_Point=\""+DoubleUtilities.format(pReal.getX(), 3)+" , "+ DoubleUtilities.format(pReal.getY(), 3)+"\"\n";
288
                if(        px == null || px.getX() > visualStatus.rasterWidth || px.getX() < 0 ||
289
                        px.getY() > visualStatus.rasterHeight || px.getY() < 0)
290
                        data += "    Pixel_Point=\"Out\"\n";
291
                else
292
                        data += "    Pixel_Point=\""+(int)px.getX()+" , "+(int)px.getY()+"\"\n";
293
                if(rgb != null)
294
                        data += "    RGB=\""+rgb[1]+"  "+rgb[2]+"  "+rgb[3]+"\"\n";
295
                data += "    Band_Value=\"";
296

    
297
                try {
298
                        for (int file = 0; file < visualStatus.fileNames.length; file++) {
299
                                RasterDataset rd = RasterDataset.open(getMapContext().getViewPort().getProjection(), visualStatus.fileNames[file]);
300
                                Extent ex = rd.getExtent();
301
                                if (pReal.getX() >= ex.minX() && pReal.getX() <= ex.maxX() && pReal.getY() >= ex.minY() && pReal.getY() <= ex.maxY()) {
302
                                        if (visualStatus.dataType >= 0 && visualStatus.dataType <= 3) {
303
                                                for (int i = 0; i < visualStatus.bandCount; i++) {
304
                                                        Integer value = (Integer) rd.getData((int) px.getX(), (int) px.getY(), i);
305
                                                        if (value != null)
306
                                                                data += value.intValue() + "  ";
307
                                                }
308
                                        }
309
                                        if (visualStatus.dataType >= 4) {
310
                                                for (int i = 0; i < visualStatus.bandCount; i++) {
311
                                                        Float value = (Float) rd.getData((int) px.getX(), (int) px.getY(), i);
312
                                                        if (value != null)
313
                                                                data += value.floatValue() + "  ";
314
                                                }
315
                                        }
316
                                        if (visualStatus.dataType >= 5) {
317
                                                for (int i = 0; i < visualStatus.bandCount; i++) {
318
                                                        Double value = (Double) rd.getData((int) px.getX(), (int) px.getY(), i);
319
                                                        if (value != null)
320
                                                                data += value.doubleValue() + "  ";
321
                                                }
322
                                        }
323
                                }
324
                                rd.close();
325
                        }
326
                } catch (NotSupportedExtensionException e) {
327
                        throw new ReadDriverException("Extensi?n no soportada.", e);
328
                } catch (RasterDriverException e) {
329
                        throw new ReadDriverException("Error en la apertura del fichero.", e);
330
                } catch (FileNotOpenException e) {
331
                        throw new ReadDriverException("Error en la apertura del fichero.", e);
332
                } catch (InvalidSetViewException e) {
333
                        throw new ReadDriverException("Error al asignar la vista.", e);
334
                }
335

    
336
                data += "\"\n";
337
                data += "  />\n";
338
                data += "</file:"+getName().replaceAll("[^a-zA-Z0-9]","")+">\n";
339

    
340
                item[0] = new StringXMLItem(data, this);
341
                return item;
342
        }
343

    
344
        /*
345
         *  (non-Javadoc)
346
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent()
347
         */
348
        public Rectangle2D getFullExtent() {
349
                return fullExtent;
350
        }
351

    
352
        /*
353
         *  (non-Javadoc)
354
         * @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)
355
         */
356
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale) throws ReadDriverException {
357

    
358
                if (isWithinScale(scale)){
359
                        Point2D p = viewPort.getOffset();
360
                        // p will be (0, 0) when drawing a view or other when painting onto
361
                        // the Layout.
362
                        visualStatus.width =  viewPort.getImageWidth();
363
                        visualStatus.height =  viewPort.getImageHeight();
364
                        visualStatus.minX = viewPort.getAdjustedExtent().getMinX();
365
                        visualStatus.minY = viewPort.getAdjustedExtent().getMinY();
366
                        visualStatus.maxX = viewPort.getAdjustedExtent().getMaxX();
367
                        visualStatus.maxY = viewPort.getAdjustedExtent().getMaxY();
368
                        visualStatus.rasterWidth = 0;
369
                        visualStatus.rasterHeight = 0;
370
                        visualStatus.rasterMinX = Double.MAX_VALUE;
371
                        visualStatus.rasterMinY = Double.MAX_VALUE;
372
                        visualStatus.rasterMaxX = 0;
373
                        visualStatus.rasterMaxY = 0;
374
                        visualStatus.fileNames = new String[1];
375
                        try {
376
                        if(mustTileDraw){
377
                                if(viewPort.getImageWidth()<= maxTileDrawWidth && viewPort.getImageHeight()<=maxTileDrawHeight)
378
                                        drawTile(g, viewPort, cancel, 0, scale);
379
                                else{
380
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), viewPort.getImageWidth(), viewPort.getImageHeight());
381
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
382
                                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
383
                                        visualStatus.fileNames = new String[tiles.getNumTiles()];
384
                                        for (int tileNr=0; tileNr < tiles.getNumTiles(); tileNr++) {
385
                                                // drawing part
386
                                                try {
387
                                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
388
                                                        drawTile(g, vp, cancel, tileNr, scale);
389
                                                } catch (NoninvertibleTransformException e) {
390
                                                        e.printStackTrace();
391
                                                }
392
                                        }
393
                                }
394
                        }else
395
                                drawTile(g, viewPort, cancel, 0, scale);
396
                        }catch (ConnectionErrorLayerException e) {
397
                                e.printStackTrace();
398
                        }catch (UnsupportedVersionLayerException e) {
399
                                e.printStackTrace();
400
                        }catch (LoadLayerException e) {
401
                                e.printStackTrace();
402
                        }
403
                }
404
                Runtime r = Runtime.getRuntime();
405
                long mem = r.totalMemory() - r.freeMemory();
406
                System.err.println("Memoria total: " + (mem / 1024) +"KB");
407
        }
408

    
409
        /**
410
         * This is the method used to draw a tile in a WCS mosaic layer.
411
         * @param tile Tile number to draw
412
         * @throws ReadDriverException 
413
         */
414
        private void drawTile(Graphics2D g, ViewPort vp, Cancellable cancel, int tile, double scale) throws LoadLayerException, ReadDriverException {
415

    
416
                // Compute the query geometry
417
                // 1. Check if it is within borders
418
                Rectangle2D extent = getFullExtent();
419
        if ((vp.getAdjustedExtent().getMinX() > extent.getMaxX()) ||
420
                (vp.getAdjustedExtent().getMinY() > extent.getMaxY()) ||
421
                (vp.getAdjustedExtent().getMaxX() < extent.getMinX()) ||
422
                (vp.getAdjustedExtent().getMaxY() < extent.getMinY())) {
423
            return;
424
        }
425

    
426
        // 2. Compute extent to be requested.
427
        Rectangle2D bBox = new Rectangle2D.Double();
428
        Rectangle2D.intersect(vp.getAdjustedExtent(), extent, bBox);
429

    
430
        // 3. Compute size in pixels
431
        double scalex = vp.getAffineTransform().getScaleX();
432
        double scaley = vp.getAffineTransform().getScaleY();
433
        int wImg = (int) Math.ceil(Math.abs(bBox.getWidth() * scalex) + 1);
434
        int hImg = (int) Math.ceil(Math.abs(bBox.getHeight() * scaley) + 1);
435
        Dimension sz = new Dimension(wImg, hImg);
436

    
437
        if ((wImg <= 0) || (hImg <= 0)) {
438
            return;
439
        }
440

    
441
                try {
442
                        sz = new Dimension(wImg, hImg);
443
                        
444
                        wcsStatus.setCoveraName( coverageName );
445
                        wcsStatus.setExtent( bBox );
446
                        wcsStatus.setFormat( format );
447
                        wcsStatus.setHeight( hImg );
448
                        wcsStatus.setWidth( wImg );
449
                        wcsStatus.setSrs(srs);
450
                        wcsStatus.setParameters( parameter );
451
                        wcsStatus.setTime( time );
452
                        wcsStatus.setOnlineResource((String) onlineResources.get("GetCoverage"));
453

    
454
                        File f = getDriver().getCoverage(wcsStatus, new MyCancellable(cancel));
455
                        if (f == null)
456
                                return;
457
                        String nameWordFile = f.getPath() + getExtensionWorldFile();
458
                        com.iver.andami.Utilities.createTemp(nameWordFile, this.getDataWorldFile(bBox, sz));
459

    
460
                        StatusRasterInterface status = super.getStatus();
461
                        if(status!=null && firstLoad){
462
                                status.applyStatus(this);
463
                                firstLoad = false;
464
                        }
465
                        ViewPortData vpData = new ViewPortData(
466
                                vp.getProjection(), new Extent(bBox), sz );
467
                        vpData.setMat(vp.getAffineTransform());
468

    
469
                        String filePath = f.getAbsolutePath();
470
                        visualStatus.fileNames[tile] = filePath;
471
                        
472
                        rasterProcess(filePath, g, vp, scale, cancel);
473
                        
474
//                        this.getRender().draw(g, vpData);
475
//                        rasterProcess(g, vpData, f);
476

    
477
//                } catch (ValidationException e) {
478
//                        UnknownResponseFormatExceptionType type =
479
//                                new UnknownResponseFormatExceptionType();
480
//                        type.setLayerName(getName());
481
//                        try {
482
//                                type.setDriverName(getDriver().getName());
483
//                        } catch (Exception e1) {
484
//                                e1.printStackTrace();
485
//                        }
486
//                        type.setFormat(format);
487
//                        type.setHost(host);
488
//                        type.setProtocol("WCS");
489
//                        ReadDriverException exception = new ReadDriverException("unknown_response_format",type);
490
//                        throw exception;
491
//        azabala                throw new DriverException(PluginServices.getText(this, "unknown_response_format"), e);
492
//                }
493
//                catch (UnsupportedVersionLayerException e) {
494
//                        UnsuportedProtocolVersionExceptionType type =
495
//                                new UnsuportedProtocolVersionExceptionType();
496
//                        type.setLayerName(getName());
497
//                        try {
498
//                                type.setDriverName(getDriver().getName());
499
//                        } catch (Exception ex){
500
//                        }
501
//                        type.setUrl(host);
502
//                        throw new ReadDriverException(PluginServices.getText(this, "version_conflict"), e, type);
503

    
504
//        azabala                throw new DriverException(PluginServices.getText(this, "version_conflict"), e);
505
                } catch (IOException e) {
506
//                        ConnectionErrorExceptionType type = new ConnectionErrorExceptionType();
507
//                        type.setLayerName(getName());
508
//                        try {
509
//                                type.setDriverName(getDriver().getName());
510
//                        } catch (Exception e1) {
511
//                        }
512
//                        type.setHost(host);
513
                        throw new ConnectionErrorLayerException(getName(),e);
514
                }
515
//                catch (WCSLayerException e) {
516
////azabala: la capturamos y la convertimos en DriverException
517
//                        WCSDriverExceptionType type = new WCSDriverExceptionType();
518
//                        type.setLayerName(getName());
519
//                        try {
520
//                                type.setDriverName(getDriver().getName());
521
//                        } catch (Exception e1) {
522
//                        }
523
//                        type.setWcsStatus(wcsStatus);
524
//                        this.setVisible(false);
525
//                        throw new WDriverException("Error WCS", e,  type);
526
//
527
////            JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), e.getMessage());
528
//
529
//        }//
530
                catch (WCSDriverException e) {
531
                        throw new LoadLayerException(getName(),e);
532
                } catch (IllegalStateException e) {
533
                        throw new LoadLayerException(getName(),e);
534
                }
535
        }
536

    
537
        /**
538
         * Devuelve el FMapWMSDriver.
539
         *
540
         * @return FMapWMSDriver
541
         *
542
         * @throws IllegalStateException
543
         * @throws ValidationException
544
         * @throws UnsupportedVersionLayerException
545
         * @throws IOException
546
         */
547
        private FMapWCSDriver getDriver() throws IllegalStateException, IOException {
548
                if (wcs == null) {
549
                        wcs = FMapWCSDriverFactory.getFMapDriverForURL(host);
550
                }
551
                return wcs;
552
        }
553

    
554
        /**
555
         * Calcula el contenido del fichero de georreferenciaci?n de una imagen.
556
         * @param bBox Tama?o y posici?n de la imagen (en coordenadas de usuario)
557
         * @param sz Tama?o de la imagen en pixeles.
558
         * @return el 'WorldFile', como String.
559
         * @throws IOException
560
         */
561
        public String getDataWorldFile(Rectangle2D bBox, Dimension sz) throws IOException {
562
                StringBuffer data = new StringBuffer();
563
            data.append((bBox.getMaxX() - bBox.getMinX())/(sz.getWidth() - 1)+"\n");
564
            data.append("0.0\n");
565
            data.append("0.0\n");
566
            data.append("-"+(bBox.getMaxY() - bBox.getMinY())/(sz.getHeight() - 1)+"\n");
567
            data.append(""+bBox.getMinX()+"\n");
568
            data.append(""+bBox.getMaxY()+"\n");
569
            return data.toString();
570
        }
571

    
572
        /**
573
         * Carga y dibuja el raster usando la librer?a
574
         * @param filePath Ruta al fichero en disco
575
         * @param g Graphics2D
576
         * @param vp ViewPort
577
         * @param scale Escala para el draw
578
         * @param cancel Cancelaci?n para el draw
579
         * @throws ReadDriverException
580
         * @throws LoadLayerException
581
         */
582
        private void rasterProcess(String filePath, Graphics2D g, ViewPort vp, double scale, Cancellable cancel) throws ReadDriverException, LoadLayerException {
583
                //Cerramos el dataset asociado a la capa si est? abierto. 
584
                if(getMultiRasterDataset() != null) {
585
                        getMultiRasterDataset().close();
586
                        this.setRemoveRasterFlag(true);
587
                }
588
                
589
                //Cargamos el dataset con el raster de disco. 
590
                setLoadParams(filePath);
591
                load();
592
                getRender().setBufferFactory(bufferFactory);
593
                
594
                visualStatus.rasterWidth += getMultiRasterDataset().getWidth()[0];
595
                visualStatus.rasterHeight += getMultiRasterDataset().getHeight()[0];
596
                if(getMultiRasterDataset().getExtent().getMin().getX() < visualStatus.rasterMinX)
597
                        visualStatus.rasterMinX = getMultiRasterDataset().getExtent().getMin().getX();
598
                if(getMultiRasterDataset().getExtent().getMin().getY() < visualStatus.rasterMinY)
599
                        visualStatus.rasterMinY = getMultiRasterDataset().getExtent().getMin().getY();
600
                if(getMultiRasterDataset().getExtent().getMax().getX() > visualStatus.rasterMaxX)
601
                        visualStatus.rasterMaxX = getMultiRasterDataset().getExtent().getMax().getX();
602
                if(getMultiRasterDataset().getExtent().getMax().getY() > visualStatus.rasterMaxY)
603
                        visualStatus.rasterMaxY = getMultiRasterDataset().getExtent().getMax().getY();
604
                visualStatus.bandCount = getMultiRasterDataset().getBandCount();
605
                visualStatus.dataType = getMultiRasterDataset().getDataType()[0];
606
                
607
                //Como el raster se carga a cada zoom el render se crea nuevamente y la lista de
608
                //filtros siempre estar? vacia a cada visualizaci?n. Para evitarlo tenemos que
609
                //guardar la lista de filtro aplicada en la visualizaci?n anterior.
610
                if (this.filterList != null)
611
                        getRender().setFilterList(filterList);
612
                
613
                //Dibujamos
614
                super.draw(null, g, vp, cancel, scale);
615
                
616
                //La primera vez asignamos la lista de filtros asociada al renderizador. Guardamos una referencia
617
                //en esta clase para que a cada zoom no se pierda.
618
                if (this.filterList == null)
619
                        filterList = getRender().getFilterList();
620
        }
621

    
622
        /*
623
         * (non-Javadoc)
624
         * @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)
625
         */
626
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet properties) throws ReadDriverException {
627
                draw(null, g, viewPort, cancel, scale);
628
        }
629

    
630
        /**
631
         * Returns the XMLEntity containing the necessary info for reproduce
632
         * the layer.
633
         *
634
         * Devuelve el XMLEntity con la informaci?n necesaria para reproducir
635
         * la capa.
636
         *
637
         * @return XMLEntity.
638
         * @throws XMLException
639
         */
640
        public XMLEntity getXMLEntity() throws XMLException {
641
                XMLEntity xml = super.getXMLEntity();
642

    
643
                xml.putProperty("wcs.host", getHost());
644
                xml.putProperty("wcs.fullExtent", StringUtilities.rect2String( fullExtent ));
645
                xml.putProperty("wcs.layerQuery", coverageName );
646
                xml.putProperty("wcs.format", format );
647
                xml.putProperty("wcs.srs", srs );
648
                xml.putProperty("wcs.time", time );
649
                xml.putProperty("wcs.parameter", parameter );
650
                xml.putProperty("wcs.coverageName", coverageName );
651
                xml.putProperty("wcs.maxResX", maxRes.getX());
652
                xml.putProperty("wcs.maxResY", maxRes.getY());
653

    
654
                Iterator it = onlineResources.keySet().iterator();
655
                String strOnlines = "";
656
                while (it.hasNext()) {
657
                        String key = (String) it.next();
658
                        String value = (String) onlineResources.get(key);
659
                        strOnlines += key+"~##SEP2##~"+value;
660
                        if (it.hasNext())
661
                                strOnlines += "~##SEP1##~";
662
                }
663
                xml.putProperty("onlineResources", strOnlines);
664

    
665
                StatusRasterInterface status = super.getStatus();
666
                if (status!=null)
667
                        status.getXMLEntity(xml, true, this);
668
                else{
669
                        status = new StatusLayerRaster();
670
                        status.getXMLEntity(xml, true, this);
671
                }
672
                return xml;
673
        }
674

    
675
        /**
676
         * Reproduces the layer from an XMLEntity.
677
         *
678
         * A partir del XMLEntity reproduce la capa.
679
         *
680
          * @param xml XMLEntity
681
         *
682
         * @throws XMLException
683
         * @throws DriverException
684
         * @throws DriverIOException
685
         */
686
        public void setXMLEntity(XMLEntity xml) throws XMLException {
687
                super.setXMLEntity(xml);
688

    
689
                // host
690
                try {
691
                        host = new URL(xml.getStringProperty("wcs.host"));
692
                } catch (MalformedURLException e) {
693
                        throw new XMLException(e);
694
                }
695

    
696
                // full extent
697
                fullExtent = StringUtilities.string2Rect(xml.getStringProperty("wcs.fullExtent"));
698

    
699
                // coverageQuery
700
                coverageName = xml.getStringProperty("wcs.layerQuery");
701

    
702
                // format
703
                format = xml.getStringProperty("wcs.format");
704

    
705
                // srs
706
                srs = xml.getStringProperty("wcs.srs");
707

    
708
                // time
709
                time = xml.getStringProperty("wcs.time");
710

    
711
                // parameter
712
                parameter = xml.getStringProperty("wcs.parameter");
713

    
714
                // coverage name
715
                coverageName = xml.getStringProperty("wcs.coverageName");
716

    
717
                // max resolution
718
                if (xml.contains("wcs.maxRes"))
719
                        maxRes = new Point2D.Double(xml.getDoubleProperty("wcs.maxRes"), xml.getDoubleProperty("wcs.maxRes"));
720
                else if (xml.contains("wcs.maxResX") && xml.contains("wcs.maxResY"))
721
                        maxRes = new Point2D.Double(xml.getDoubleProperty("wcs.maxResX"), xml.getDoubleProperty("wcs.maxResY"));
722

    
723
                // OnlineResources
724
        if (xml.contains("onlineResources")) {
725
                String[] operations = xml.getStringProperty("onlineResources").split("~##SEP1##~");
726
                for (int i = 0; i < operations.length; i++) {
727
                                String[] resources = operations[i].split("~##SEP2##~");
728
                                if (resources.length==2 && resources[1]!="")
729
                                        onlineResources.put(resources[0], resources[1]);
730
                        }
731
        }
732
                String claseStr = null;
733
                if (xml.contains("raster.class")) {
734
                        claseStr = xml.getStringProperty("raster.class");
735
                }
736
                
737
                StatusRasterInterface status = super.getStatus();
738
                if (status!=null)
739
                        status.setXMLEntity(xml, this);
740
                else {
741
                        //Cuando cargamos un proyecto
742

    
743
                        if(claseStr!=null && !claseStr.equals("")){
744
                                try{
745
                                        Class clase = Class.forName(claseStr);
746
                                        Constructor constr = clase.getConstructor(null);
747
                                        status = (StatusRasterInterface)constr.newInstance(null);
748
                                        if(status!=null)
749
                                                status.setXMLEntity(xml, this);
750
                                } catch(ClassNotFoundException exc) {
751
                                        exc.printStackTrace();
752
                                } catch(InstantiationException exc) {
753
                                        exc.printStackTrace();
754
                                } catch(IllegalAccessException exc) {
755
                                        exc.printStackTrace();
756
                                } catch(NoSuchMethodException exc) {
757
                                        exc.printStackTrace();
758
                                } catch(InvocationTargetException exc) {
759
                                        exc.printStackTrace();
760
                                }
761
                        }
762
                }
763
                firstLoad = true;
764
        }
765

    
766
        public void setCoverageName(String coverageName) {
767
                this.coverageName = coverageName;
768
        }
769

    
770
        public void setParameter(String parametersString) {
771
                this.parameter = parametersString;
772
        }
773

    
774
        public void setTime(String time) {
775
                this.time = time;
776
        }
777

    
778
        public void setSRS(String srs) {
779
                this.srs = srs;
780
                setProjection(CRSFactory.getCRS(srs));
781
        }
782

    
783
        public void setFormat(String format) {
784
                this.format = format;
785
        }
786

    
787

    
788
        /**
789
         * Inserta el URL.
790
         *
791
         * @param host String.
792
         * @throws MalformedURLException
793
         */
794
        public void setHost(String host) {
795
                try {
796
                        setHost(new URL(host));
797
                } catch (MalformedURLException e) {
798

    
799
                }
800
        }
801

    
802
        /**
803
         * Inserta el URL.
804
         *
805
         * @param host URL.
806
         */
807
        public void setHost(URL host) {
808
                this.host = host;
809
        }
810

    
811
        /**
812
         * Sets the layer's full extent.
813
         *
814
         * Establece la extensi?n m?xima de la capa.
815
         *
816
         * @param rect
817
         */
818
        public void setFullExtent(Rectangle2D rect) {
819
                this.fullExtent = rect;
820
        }
821

    
822
        /**
823
         * Devuelve el URL.
824
         *
825
         * @return URL.
826
         */
827
        public URL getHost() {
828
                return host;
829
        }
830

    
831
        /**
832
         * Remote source layers have a bunch of properties that are required for get them from
833
         * the servers. This method supplies a hash table containing any needed field. This hash
834
         * table may be used to let the client to connect to a server and restore a previously saved
835
         * layer. So, the layer itself may not be saved to the disk since the actual saved
836
         * info is just its properties.
837
         *
838
         * @return Returns a hash table containing all the required information for
839
         * set up a wms layer
840
         */
841
        public Hashtable getProperties(){
842
                Hashtable info = new Hashtable();
843
                info.put(   "name", coverageName);
844
                info.put(   "host", getHost());
845
                info.put(    "crs", srs);
846
                info.put( "format", format);
847
                String str = time;
848
                if (str==null)
849
                        str = "";
850
                info.put(   "time", str);
851
                str = parameter;
852
                if (str==null)
853
                        str = "";
854
                info.put("parameter", str);
855

    
856
                return info;
857
        }
858

    
859
        /**
860
         * Obtiene la extensi?n del fichero de georreferenciaci?n
861
         * @return String con la extensi?n del fichero de georreferenciaci?n dependiendo
862
         * del valor del formato obtenido del servidor. Por defecto asignaremos un .wld
863
         */
864
        private String getExtensionWorldFile(){
865
                String extWorldFile = ".wld";
866
            if (format.equals("image/tif") || format.equals("image/tiff"))
867
                    extWorldFile = ".tfw";
868
            if (format.equals("image/jpeg"))
869
                    extWorldFile = ".jpgw";
870
            return extWorldFile;
871
        }
872

    
873
        public void setMaxResolution(Point2D maxResolution) {
874
                this.maxRes = maxResolution;
875
        }
876

    
877
        /**
878
         * <p>
879
         * Gets the max resolution allowed by the coverage. Requesting a higher resolution
880
         * than this value does not cause any error, but the info responsed is just an
881
         * interpolation. <br>
882
         * </p>
883
         * 
884
         * <p>
885
         * In exchange for obtaining a greater file and without additional information,
886
         * we can easily fit it into the View. <br>
887
         * </p>
888
         *
889
         * <p>
890
         * Obtiene la resoluci?n m?xima soportada por la cobertura. La petici?n
891
         * de una resoluci?n superior a la soportada no provoca ning?n error, aunque
892
         * la informaci?n obtenida s?lo es una mera interpolaci?n de informaci?n. <br>
893
         * </p>
894
         * 
895
         * <p>
896
         * A cambio de obtener un archivo mayor y sin informaci?n adicional, podemos
897
         * f?cilmente acoplarlo a la vista. <br>
898
         * </p>
899
         * 
900
         * @return double
901
         */
902
        public Point2D getMaxResolution() {
903
                if (maxRes==null)
904
                        maxRes = wcs.getMaxResolution(coverageName);
905
                return maxRes;
906
        }
907

    
908

    
909
        public void setDriver(FMapWCSDriver driver) {
910
                this.wcs = driver;
911
        }
912

    
913
        /*
914
         *  (non-Javadoc)
915
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
916
         */
917
        public int[] getTileSize() {
918
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
919
                return size;
920
        }
921

    
922
        /*
923
         *  (non-Javadoc)
924
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
925
         */
926
        public boolean isTiled() {
927
                return mustTileDraw;
928
        }
929
        
930
        /*
931
         * (non-Javadoc)
932
         * @see org.gvsig.fmap.raster.layers.FLyrRasterSE#isActionEnabled(int)
933
         */
934
        public boolean isActionEnabled(int action) {
935
                if(action == IRasterLayerActions.ZOOM_PIXEL_RESOLUTION)
936
                        return false;
937
                if(action == IRasterLayerActions.FLYRASTER_BAR_TOOLS)
938
                        return false;
939
                return super.isActionEnabled(action);
940
        }
941
}