Statistics
| Revision:

gvsig-raster / org.gvsig.raster.ermapper / branches / org.gvsig.raster.ermapper_dataaccess_refactoring / org.gvsig.raster.ermapper.io / src / main / java / org / gvsig / raster / ermapper / io / ErmapperProvider.java @ 2259

History | View | Annotate | Download (32.2 KB)

1
/* gvSIG. Geographic Information System of the Valencian Government
2
 *
3
 * Copyright (C) 2007-2008 Infrastructures and Transports Department
4
 * of the Valencian Government (CIT)
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 2
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 */
22
package org.gvsig.raster.ermapper.io;
23

    
24
import java.awt.geom.AffineTransform;
25
import java.awt.geom.Point2D;
26
import java.io.BufferedReader;
27
import java.io.File;
28
import java.io.FileReader;
29

    
30
import org.cresques.cts.ICoordTrans;
31
import org.gvsig.fmap.dal.DALFileLocator;
32
import org.gvsig.fmap.dal.DALLocator;
33
import org.gvsig.fmap.dal.DataStore;
34
import org.gvsig.fmap.dal.coverage.RasterLocator;
35
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
36
import org.gvsig.fmap.dal.coverage.datastruct.BandList;
37
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
38
import org.gvsig.fmap.dal.coverage.exception.BandAccessException;
39
import org.gvsig.fmap.dal.coverage.exception.FileNotOpenException;
40
import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
41
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
42
import org.gvsig.fmap.dal.coverage.exception.ParsingException;
43
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
44
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
45
import org.gvsig.fmap.dal.coverage.store.parameter.RasterDataParameters;
46
import org.gvsig.fmap.dal.coverage.store.parameter.RasterFileStoreParameters;
47
import org.gvsig.fmap.dal.coverage.store.props.Transparency;
48
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
49
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
50
import org.gvsig.metadata.MetadataLocator;
51
import org.gvsig.raster.cache.tile.provider.TileServer;
52
import org.gvsig.raster.impl.buffer.SpiRasterQuery;
53
import org.gvsig.raster.impl.datastruct.ExtentImpl;
54
import org.gvsig.raster.impl.process.RasterTask;
55
import org.gvsig.raster.impl.process.RasterTaskQueue;
56
import org.gvsig.raster.impl.provider.AbstractRasterProvider;
57
import org.gvsig.raster.impl.provider.RasterProvider;
58
import org.gvsig.raster.impl.provider.tile.FileTileServer;
59
import org.gvsig.raster.impl.store.AbstractRasterDataParameters;
60
import org.gvsig.raster.impl.store.DefaultRasterStore;
61
import org.gvsig.raster.impl.store.DefaultStoreFactory;
62
import org.gvsig.raster.impl.store.properties.DataStoreColorInterpretation;
63
import org.gvsig.raster.impl.store.properties.DataStoreTransparency;
64
import org.gvsig.tools.ToolsLocator;
65
import org.gvsig.tools.task.TaskStatus;
66

    
67
import com.ermapper.ecw.JNCSException;
68
import com.ermapper.ecw.JNCSFile;
69
import com.ermapper.ecw.JNCSFileNotOpenException;
70
import com.ermapper.ecw.JNCSInvalidSetViewException;
71
import com.ermapper.ecw.JNCSProgressiveUpdate;
72
/**
73
 * Driver de Ecw
74
 *
75
 * @author Nacho Brodin (nachobrodin@gmail.com)
76
 */
77
public class ErmapperProvider extends AbstractRasterProvider implements JNCSProgressiveUpdate {
78
        //private static final Logger           logger                   = LoggerFactory.getLogger(ErmapperProvider.class);
79
        public static String                  NAME                     = "Ermapper Store";
80
        public static String                  DESCRIPTION              = "Ermapper Raster file";
81
        public static final String            METADATA_DEFINITION_NAME = "ErmapperStore";
82
        private JNCSFile                                       file                     = null;
83
        protected Transparency                        fileTransparency         = null;
84
        private Extent                        viewRequest              = null;
85
        private DataStoreColorInterpretation  colorInterpr             = null;
86
        private boolean                       open                     = false;
87
        protected static String[]             formatList               = null;
88
        
89
        public static void register() {
90
                RasterLocator.getManager().getProviderServices().registerFileProvidersTiled(ErmapperProvider.class);
91
                registerFormats();
92
                
93
                DataManagerProviderServices dataman = (DataManagerProviderServices) DALLocator.getDataManager();
94
                if (dataman != null && !dataman.getStoreProviders().contains(NAME)) {
95
                        dataman.registerStoreProvider(NAME,
96
                                        ErmapperProvider.class, 
97
                                        ErmapperDataParameters.class);
98
                }
99
                
100
                if(DALFileLocator.getFilesystemServerExplorerManager() != null)
101
                        DALFileLocator.getFilesystemServerExplorerManager().registerProvider(
102
                                        NAME, 
103
                                        DESCRIPTION,
104
                                        ErmapperFilesystemServerExplorer.class);
105
                
106
            dataman.registerStoreFactory(NAME, DefaultStoreFactory.class);
107
        }
108
        
109
        private static void registerFormats() {
110
                formatList      = new String[] {
111
                                "ecw", 
112
                                "jp2"};
113
                for (int i = 0; i < formatList.length; i++) 
114
                        RasterLocator.getManager().getProviderServices().addFormat(formatList[i], ErmapperProvider.class);
115
        }
116
        
117
        /*
118
         * (non-Javadoc)
119
         * @see org.gvsig.raster.impl.provider.RasterProvider#getFormatList()
120
         */
121
        public String[] getFormatList() {
122
                return formatList;
123
        }
124
        
125
        /**
126
         * Returns true if the extension is supported and false if doesn't
127
         * @param ext
128
         * @return
129
         */
130
        public boolean isExtensionSupported(String ext) {
131
                if(ext.indexOf(".") != -1)
132
                        ext = ext.substring(ext.lastIndexOf(".") + 1, ext.length());
133
                for (int i = 0; i < formatList.length; i++) {
134
                        if(formatList[i].compareTo(ext) == 0)
135
                                return true;
136
                }
137
                return false;
138
        }
139
        
140
        /**
141
         * Mandatory constructor to instantiate an empty provider
142
         */
143
        public ErmapperProvider() {
144
        }
145
        
146
        /**
147
         * Constructor. Abre el dataset.
148
         * @param proj Proyecci?n
149
         * @param fName Nombre del fichero ecw
150
         * @throws NotSupportedExtensionException
151
         */
152
        public ErmapperProvider(String params) throws NotSupportedExtensionException {
153
                super(params);
154
                if(params instanceof String) {
155
                        ErmapperDataParameters p = new ErmapperDataParameters();
156
                        p.setURI((String)params);
157
                        super.init(p, null, ToolsLocator.getDynObjectManager()
158
                                        .createDynObject(
159
                                                        MetadataLocator.getMetadataManager().getDefinition(
160
                                                                        DataStore.METADATA_DEFINITION_NAME)));
161
                        init(p, null);
162
                }
163
        }
164
        
165
        public ErmapperProvider(ErmapperDataParameters params,
166
                        DataStoreProviderServices storeServices) throws NotSupportedExtensionException {
167
                super(params, storeServices, ToolsLocator.getDynObjectManager()
168
                                .createDynObject(
169
                                                MetadataLocator.getMetadataManager().getDefinition(
170
                                                                DataStore.METADATA_DEFINITION_NAME)));
171
                init(params, storeServices);
172
        }
173

    
174
        /**
175
         * Abre el dataset.
176
         * @param proj Proyecci?n
177
         * @param fName Nombre del fichero ecw
178
         * @throws NotSupportedExtensionException
179
         */
180
        public void init (AbstractRasterDataParameters params,
181
                        DataStoreProviderServices storeServices) throws NotSupportedExtensionException {
182
                setParam(storeServices, params);
183
                if (!((RasterFileStoreParameters)param).getFile().exists() && !((RasterDataParameters)param).getURI().startsWith("ecwp:"))
184
                        throw new NotSupportedExtensionException("Extension not supported");
185

    
186
                try {
187
                        file = new JNCSFile(((RasterDataParameters)param).getURI(), false);
188
                } catch (JNCSException e1) {
189
                        throw new NotSupportedExtensionException("Error loading the ecw file", e1);
190
                }
191
                
192
                /*
193
                 * TODO: Leer proyecciones ECW
194
                 * 
195
                 wktProjection = null;//getWKTFromEcw_csFile(file.projection);
196
                if(wktProjection != null && wktProjection != "") {
197
                        try {
198
                                proj = RasterLocator.getManager().getCRSUtils().convertWktToIProjection(wktProjection);
199
                        } catch (Exception e) {
200
                                logger.info("Error reading WKT from the raster provider", e);
201
                        }
202
                }*/
203
                
204
                load();
205
                bandCount = file.numBands;
206

    
207
                int[] dt = new int[bandCount];
208
                for (int i = 0; i < bandCount; i++)
209
                        dt[i] = Buffer.TYPE_BYTE;
210
                setDataType(dt);
211

    
212
                super.init();
213

    
214
                try {
215
                        loadFromRmf(getRmfBlocksManager());
216
                } catch (ParsingException e) {
217
                        //No lee desde rmf
218
                }
219
                open = true;
220
        }
221
        
222
        @SuppressWarnings("unused")
223
        private String getWKTFromEcw_csFile(String identifier) {
224
                File file = new File("./");
225
                file = new File(file.getAbsoluteFile() + File.separator + "data" + File.separator + "gdal" + File.separator + "ecw_cs.wkt");
226
                if(file.exists()) {
227
                        FileReader fr = null;
228
                        BufferedReader br = null;
229
                        try {
230
                                fr = new FileReader(file);
231
                                br = new BufferedReader(fr);
232

    
233
                                String line;
234
                                while((line = br.readLine()) != null) {
235
                                        if(line.startsWith(identifier + ",")) {
236
                                                int index = line.indexOf(",") + 1;
237
                                                return line.substring(index);
238
                                        }
239
                                }
240
                        } catch(Exception e){
241
                                return null;
242
                        } finally {
243
                                try {                   
244
                                        if(fr != null) 
245
                                                fr.close();                   
246
                                } catch (Exception e2){
247
                                        e2.printStackTrace();
248
                                }
249
                        }
250
                }
251
                return null;
252
        }
253

    
254
        public RasterProvider load() {
255
                ownTransformation = new AffineTransform(file.cellIncrementX, 0, 0, file.cellIncrementY, file.originX, file.originY);
256
                externalTransformation = (AffineTransform) ownTransformation.clone();
257
                return this;
258
        }
259
        
260
        public boolean isOpen() {
261
                return open;
262
        }
263

    
264
        public void close() {
265
                if(file != null) {
266
                        open = false;
267
                        //Cuando se abren varios datastores del mismo fichero y se cierra uno de ellos se cierra la aplicaci?n en el siguiente dibujado
268
                        //Se deber?a buscar una soluci?n ya que en los PrepareLayer se abre y cierra para hacer comprobaciones.
269
                        //file.close(false);
270
                        file = null;
271
                }
272
        }
273

    
274
        public Transparency getTransparency() {
275
                if(fileTransparency == null)
276
                        fileTransparency = new DataStoreTransparency();
277
                return fileTransparency;
278
        }
279

    
280
        public double getWidth() {
281
                return file.width;
282
        }
283

    
284
        public double getHeight() {
285
                return file.height;
286
        }
287

    
288
        public Extent getView() {
289
                return viewRequest;
290
        }
291

    
292
        public void setView(Extent e) {
293
                viewRequest = new ExtentImpl(e);
294
        }
295
        
296
        @Override
297
        public void loadBuffer(SpiRasterQuery query)
298
                        throws ProcessInterruptedException, RasterDriverException {
299
                setView(query.getAdjustedRequestBoundingBox());
300
                int bufWidth = query.getAdjustedBufWidth();
301
                int bufHeight = query.getAdjustedBufHeight();
302
                int[] stpBuffer = new int[]{0, 0 , bufWidth, bufHeight};
303
                loadBuffer(viewRequest, 
304
                                bufWidth, 
305
                                bufHeight, 
306
                                query.getBufferForProviders(), 
307
                                query.getBandList(), 
308
                                stpBuffer, 
309
                                query.getTaskStatus());
310
        }
311
        
312

    
313
        /*public Buffer getWindow(Extent ex, BandList bandList, Buffer rasterBuf, TaskStatus status) 
314
                throws ProcessInterruptedException, RasterDriverException {
315
                
316
                if(status != null && status.isCancelled())
317
                        return null;
318
                
319
                Point2D p1 = new Point2D.Double(ex.getULX(), ex.getULY());
320
                Point2D p2 = new Point2D.Double(ex.getLRX(), ex.getLRY());
321
                try {
322
                        externalTransformation.inverseTransform(p1, p1);
323
                        externalTransformation.inverseTransform(p2, p2);
324
                        ownTransformation.transform(p1, p1);
325
                        ownTransformation.transform(p2, p2);
326
                } catch (NoninvertibleTransformException e) {
327
                        throw new RasterDriverException("Noninvertible transform");
328
                }
329

330
                Extent selectedExtent = new ExtentImpl(p1.getX(), p1.getY(), p2.getX(), p2.getY());
331

332
                setView(selectedExtent);
333
                int wPx = rasterBuf.getWidth();
334
                int hPx = rasterBuf.getHeight();
335
                int[] stpBuffer = new int[]{0, 0 , wPx, hPx};
336

337
                loadBuffer(viewRequest, wPx, hPx, rasterBuf, bandList, stpBuffer, status);
338

339
                if(status != null && status.isCancelled())
340
                        return null;
341
                
342
                return rasterBuf;
343
        }*/
344

    
345
        /*public Buffer getWindow(double ulx, double uly, double w, double h, 
346
                        BandList bandList, Buffer rasterBuf, boolean adjustToExtent, TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
347
                //El incremento o decremento de las X e Y depende de los signos de rotaci?n y escala en la matriz de transformaci?n. Por esto
348
                //tenemos que averiguar si lrx es x + w o x -w, asi como si lry es y + h o y - h
349
                
350
                if(status != null && status.isCancelled())
351
                        return null;
352
                
353
                Extent ext = getExtent();
354
                Point2D pInit = rasterToWorld(new Point2D.Double(0, 0));
355
                Point2D pEnd = rasterToWorld(new Point2D.Double(getWidth(), getHeight()));
356
                double wRaster = Math.abs(pEnd.getX() - pInit.getX());
357
                double hRaster = Math.abs(pEnd.getY() - pInit.getY());
358
                double lrx = (((ext.getULX() - wRaster) > ext.maxX()) || ((ext.getULX() - wRaster) < ext.minX())) ? (ulx + w) : (ulx - w);
359
                double lry = (((ext.getULY() - hRaster) > ext.maxY()) || ((ext.getULY() - hRaster) < ext.minY())) ? (uly + h) : (uly - h);
360

361
                Point2D p1 = new Point2D.Double(ulx, uly);
362
                Point2D p2 = new Point2D.Double(lrx, lry);
363
                try {
364
                        externalTransformation.inverseTransform(p1, p1);
365
                        externalTransformation.inverseTransform(p2, p2);
366
                        p1.setLocation((int)p1.getX(), (int)p1.getY());
367
                        p2.setLocation((int)Math.ceil(p2.getX()), (int)Math.ceil(p2.getY()));
368
                        p1.setLocation(Math.max(p1.getX(), 0), Math.max(p1.getY(), 0));
369
                        p2.setLocation(Math.max(p2.getX(), 0), Math.max(p2.getY(), 0));
370
                        p1.setLocation(Math.min(p1.getX(), getWidth()), Math.min(p1.getY(), getHeight()));
371
                        p2.setLocation(Math.min(p2.getX(), getWidth()), Math.min(p2.getY(), getHeight()));
372
                        ownTransformation.transform(p1, p1);
373
                        ownTransformation.transform(p2, p2);
374
                } catch (NoninvertibleTransformException e) {
375
                        throw new RasterDriverException("Noninvertible transform");
376
                }
377

378
                Extent selectedExtent = new ExtentImpl(p1.getX(), p1.getY(), p2.getX(), p2.getY());
379

380
                setView(selectedExtent);
381
                int wPx = rasterBuf.getWidth();
382
                int hPx = rasterBuf.getHeight();
383
                int[] stpBuffer = new int[]{0, 0 , wPx, hPx};
384

385
                loadBuffer(viewRequest, wPx, hPx, rasterBuf, bandList, stpBuffer, status);
386

387
                if(status != null && status.isCancelled())
388
                        return null;
389
                
390
                return rasterBuf;
391
        }*/
392

    
393
        /*public Buffer getWindow(Extent extent, int bufWidth, int bufHeight,
394
                        BandList bandList, Buffer rasterBuf, boolean adjustToExtent, TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
395
                
396
                if(status != null && status.isCancelled())
397
                        return null;
398
                
399
                Point2D p1 = new Point2D.Double(extent.getULX(), extent.getULY());
400
                Point2D p2 = new Point2D.Double(extent.getLRX(), extent.getLRY());
401
                try {
402
                        externalTransformation.inverseTransform(p1, p1);
403
                        externalTransformation.inverseTransform(p2, p2);
404
                        p1.setLocation((int)p1.getX(), (int)p1.getY());
405
                        p2.setLocation((int)Math.ceil(p2.getX()), (int)Math.ceil(p2.getY()));
406
                        p1.setLocation(Math.max(p1.getX(), 0), Math.max(p1.getY(), 0));
407
                        p2.setLocation(Math.max(p2.getX(), 0), Math.max(p2.getY(), 0));
408
                        p1.setLocation(Math.min(p1.getX(), getWidth()), Math.min(p1.getY(), getHeight()));
409
                        p2.setLocation(Math.min(p2.getX(), getWidth()), Math.min(p2.getY(), getHeight()));
410
                        ownTransformation.transform(p1, p1);
411
                        ownTransformation.transform(p2, p2);
412
                } catch (NoninvertibleTransformException e) {
413
                        throw new RasterDriverException("Noninvertible transform");
414
                }
415
                Extent selectedExtent = new ExtentImpl(p1, p2);
416
                setView(selectedExtent);
417
                int[] stpBuffer = new int[]{0, 0 , bufWidth, bufHeight};
418

419
                //TODO: FUNCIONALIDAD: Implementar adjustToExtent = false
420

421
                loadBuffer(viewRequest, bufWidth, bufHeight, rasterBuf, bandList, stpBuffer, status);
422
                
423
                if(status != null && status.isCancelled())
424
                        return null;
425
                
426
                return rasterBuf;
427
        }*/
428
        
429
        /*public Buffer getWindow(int x, int y, int w, int h, 
430
                        BandList bandList, Buffer rasterBuf, TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
431
                
432
                if(status != null && status.isCancelled())
433
                        return null;
434
                
435
                Point2D init = this.rasterToWorld(new Point2D.Double(x, y));
436
                Point2D end = this.rasterToWorld(new Point2D.Double(x + w, y + h));
437
                Extent selectedExtent = new ExtentImpl(init.getX(), init.getY(), end.getX(), end.getY());
438
                setView(selectedExtent);
439
                int[] stpBuffer = new int[]{0, 0 , rasterBuf.getWidth(), rasterBuf.getHeight()};
440

441
                loadBuffer(viewRequest, rasterBuf.getWidth(), rasterBuf.getHeight(), rasterBuf, bandList, stpBuffer, status);
442
                
443
                if(status != null && status.isCancelled())
444
                        return null;
445
                
446
                return rasterBuf;
447
        }*/
448

    
449
        /**
450
         * Carga el buffer con las bandas RGB del raster con los par?metros especificados de extensi?n
451
         * y tama?o de buffer. El problema de ecw es que solo podemos leer 3 bandas de una vez ya que solo disponemos
452
         * de una llamada readLineRGBA. Para leer m?s bandas tendremos que hacer multiples llamadas a setView para leer
453
         * 3 cada vez.
454
         *
455
         * Si por ejemplo tenemos un ecw de 6 bandas [0, 1, 2, 3, 4, 5] y queremos cargar un buffer con el siguiente orden
456
         * [0, -, 2, -, 4, -] La variable readBandsFromECW har? la llamada a setView con los valores [0, 2, 4, 0, 0, 0]. La
457
         * funci?n drawRGB ser? la encargada de hacer el switch para obtener [0, -, 2, -, 4, -].
458
         *
459
         * Bug#1: Si se dispone de un ecw de m?s de tres bandas podemos llamar a setView con readBandsFromECW con el orden
460
         * que queramos, por ejemplo [3, 2, 5, 1, 0] pero para ecw de 3 bandas la llamada con las bandas cambiadas no
461
         * hace caso. El caso de readBandsFromECW = [2, 0, 1] ser? tomado siempre como [0, 1, 2].
462
         *
463
         * @param selectedExtent Extensi?n seleccionada
464
         * @param bufWidth Ancho de buffer
465
         * @param bufHeight Alto de buffer
466
         * @param rasterBuf Buffer de datos
467
         */
468
        private void loadBuffer(Extent selectedExtent, 
469
                        int bufWidth, 
470
                        int bufHeight, 
471
                        Buffer rasterBuf, 
472
                        BandList bandList, 
473
                        int[] stpBuffer,
474
                        TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
475
                try{
476
                        RasterTask task = RasterTaskQueue.get(Thread.currentThread().getId() + "");
477
                        
478
                        int[] readBandsFromECW = new int[Math.max(file.numBands, 3)];
479
                        
480
                        for(int i = 0; i < readBandsFromECW.length; i ++) {
481
                                readBandsFromECW[i] = i;
482
                        }
483

    
484
                        if(task.getEvent() != null)
485
                                task.manageEvent(task.getEvent());
486
                        if(status != null && status.isCancelled())
487
                                return;
488

    
489
                        if(bufWidth > Math.round(Math.abs(selectedExtent.width() / file.cellIncrementX)))
490
                                bufWidth = (int)Math.round(Math.abs(selectedExtent.width() / file.cellIncrementX));
491
                        if(bufHeight > Math.round(Math.abs(selectedExtent.height() / file.cellIncrementY)))
492
                                bufHeight = (int)Math.round(Math.abs(selectedExtent.height() / file.cellIncrementY));
493
                        file.setView(file.numBands, readBandsFromECW, selectedExtent.minX(), selectedExtent.maxY(), selectedExtent.maxX(), selectedExtent.minY(), bufWidth, bufHeight);
494
                        
495
                        //Escribimos el raster sobre un Buffer
496
                        int[] pRGBArray = new int[bufWidth];
497
                        drawRGB2(rasterBuf, pRGBArray, bandList, status);
498

    
499
                }catch(JNCSInvalidSetViewException exc){
500
                        throw new RasterDriverException("Error setting coords");
501
                }catch (JNCSFileNotOpenException e) {
502
                        throw new RasterDriverException("Error opening file");
503
                }catch (JNCSException ex) {
504
                        throw new RasterDriverException("Error reading data");
505
                }
506

    
507
        }
508
        
509
        private void drawRGB2(
510
                        Buffer rasterBuf, 
511
                        int[] pRGBArray, 
512
                        BandList bandList, 
513
                        TaskStatus status) throws JNCSException, ProcessInterruptedException {
514
                RasterTask task = RasterTaskQueue.get(Thread.currentThread().getId() + "");
515
                int[] drawableBands = null;
516
                
517
                for (int line = 0; line < rasterBuf.getHeight(); line++) {
518
                        try {
519
                                file.readLineRGBA(pRGBArray);
520
                                for(int col = 0; col < pRGBArray.length; col ++) {
521
                                        drawableBands = bandList.getBufferBandToDraw(getURIOfFirstProvider(), 0);
522
                                        if(drawableBands != null) {
523
                                                for (int i = 0; i < drawableBands.length; i++) {
524
                                                        if(drawableBands[i] != -1)
525
                                                                rasterBuf.setElem(line, col, drawableBands[i], (byte)((pRGBArray[col] & 0x00ff0000) >> 16));                                                        
526
                                                }
527
                                        }
528
                                        drawableBands = bandList.getBufferBandToDraw(getURIOfFirstProvider(), 1);
529
                                        if(drawableBands != null) {
530
                                                for (int i = 0; i < drawableBands.length; i++) {
531
                                                        if(drawableBands[i] != -1)
532
                                                                rasterBuf.setElem(line, col, drawableBands[i], (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
533
                                                }
534
                                        }
535
                                        drawableBands = bandList.getBufferBandToDraw(getURIOfFirstProvider(), 2);
536
                                        if(drawableBands != null) {
537
                                                for (int i = 0; i < drawableBands.length; i++) {
538
                                                        if(drawableBands[i] != -1)
539
                                                                rasterBuf.setElem(line, col, drawableBands[i], (byte)(pRGBArray[col] & 0x000000ff));
540
                                                }
541
                                        }
542
                                }
543
                        } catch (JNCSException exc) {
544
                        }
545
                        if(task.getEvent() != null)
546
                                task.manageEvent(task.getEvent());
547
                        if(status != null && status.isCancelled())
548
                                return;
549
                }
550
                return;
551
        }
552

    
553
        @SuppressWarnings("unused")
554
        private void drawRGB(Buffer rasterBuf, int[] pRGBArray, int[] readBands, BandList bandList, RasterTask task) throws JNCSException, ProcessInterruptedException {
555
                int bandR = readBands[0];
556
                int bandG = (readBands.length > 1) ? readBands[1] : -1;
557
                int bandB = (readBands.length > 2) ? readBands[2] : -1;
558

    
559
                //********* caso especial que resuelve Bug#1 **********************
560
                if(file.numBands == 3 && bandList.getDrawableBandsCount() < 3) {
561
                        for(int i = 0; i < 3; i ++) {
562
                                int[] b = bandList.getBand(i).getBufferBandListToDraw();
563
                                if(b != null){
564
                                        bandG = 1; bandR = 0; bandB = 2;
565
                                }
566
                        }
567
                }
568
                if(file.numBands == 3 && bandR == bandG && bandG == bandB) { //caso especial que resuelve Bug#1
569
                        for(int i = 0; i < 3; i ++) {
570
                                int[] b = bandList.getBand(i).getBufferBandListToDraw();
571
                                if(b != null) {
572
                                        if(i == 0) {
573
                                                for (int line = 0; line < rasterBuf.getHeight(); line++) {
574
                                                        try {
575
                                                                file.readLineRGBA(pRGBArray);
576
                                                                for(int col = 0; col < pRGBArray.length; col ++) {
577
                                                                        rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
578
                                                                        rasterBuf.setElem(line, col, bandG, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
579
                                                                        rasterBuf.setElem(line, col, bandB, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
580
                                                                }
581
                                                        } catch (JNCSException exc) {
582
                                                        }
583
                                                }
584
                                                return;
585
                                        }
586
                                        if(i == 1) {
587
                                                for (int line = 0; line < rasterBuf.getHeight(); line++) {
588
                                                        try {
589
                                                                file.readLineRGBA(pRGBArray);
590
                                                                for(int col = 0; col < pRGBArray.length; col ++) {
591
                                                                        rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
592
                                                                        rasterBuf.setElem(line, col, bandG, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
593
                                                                        rasterBuf.setElem(line, col, bandB, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
594
                                                                }
595
                                                        } catch (JNCSException exc) {
596
                                                        }
597
                                                }
598
                                                return;
599
                                        }
600
                                        if(i == 2) {
601
                                                for (int line = 0; line < rasterBuf.getHeight(); line++) {
602
                                                        try {
603
                                                                file.readLineRGBA(pRGBArray);
604
                                                                for(int col = 0; col < pRGBArray.length; col ++) {
605
                                                                        rasterBuf.setElem(line, col, bandR, (byte)(pRGBArray[col] & 0x000000ff));
606
                                                                        rasterBuf.setElem(line, col, bandG, (byte)(pRGBArray[col] & 0x000000ff));
607
                                                                        rasterBuf.setElem(line, col, bandB, (byte)(pRGBArray[col] & 0x000000ff));
608
                                                                }
609
                                                        } catch (JNCSException exc) {
610
                                                        }
611
                                                }
612
                                                return;
613
                                        }
614
                                }
615
                                if(task.getEvent() != null)
616
                                        task.manageEvent(task.getEvent());
617
                        }
618

    
619
                }
620
                //********* END caso especial que resuelve Bug#1 **********************
621

    
622
                if(bandR >= 0 && bandG >= 0 && bandB >= 0) {
623
                        for (int line = 0; line < rasterBuf.getHeight(); line++) {
624
                                try {
625
                                        file.readLineRGBA(pRGBArray);
626
                                        for(int col = 0; col < pRGBArray.length; col ++) {
627
                                                rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
628
                                                rasterBuf.setElem(line, col, bandG, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
629
                                                rasterBuf.setElem(line, col, bandB, (byte)(pRGBArray[col] & 0x000000ff));
630
                                        }
631
                                } catch (JNCSException exc) {
632
                                }
633
                        }
634
                        return;
635
                }
636

    
637
                if(task.getEvent() != null)
638
                        task.manageEvent(task.getEvent());
639

    
640
                if(bandR >= 0 && bandG >= 0) {
641
                        for (int line = 0; line < rasterBuf.getHeight(); line++) {
642
                                try {
643
                                        file.readLineRGBA(pRGBArray);
644
                                        for(int col = 0; col < pRGBArray.length; col ++) {
645
                                                rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
646
                                                rasterBuf.setElem(line, col, bandG, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
647
                                        }
648
                                } catch (JNCSException exc) {
649
                                }
650
                        }
651
                        return;
652
                }
653

    
654
                if(task.getEvent() != null)
655
                        task.manageEvent(task.getEvent());
656

    
657
                if(bandR >= 0){
658
                        for (int line = 0; line < rasterBuf.getHeight(); line++) {
659
                                try {
660
                                        file.readLineRGBA(pRGBArray);
661
                                        for(int col = 0; col < pRGBArray.length; col ++)
662
                                                rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
663
                                } catch (JNCSException exc) {
664
                                }
665
                        }
666
                        return;
667
                }
668

    
669
                if(task.getEvent() != null)
670
                        task.manageEvent(task.getEvent());
671

    
672
        }
673

    
674
        public void reProject(ICoordTrans rp) {
675
        }
676

    
677
        public int getBlockSize() {
678
                return 0;
679
        }
680

    
681
        public Object readCompleteLine(int line, int band) throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
682
                if(line < 0 || line >= file.height || band < 0 || band >= getBandCount())
683
                        throw new InvalidSetViewException("Request out of grid");
684

    
685
                Point2D begin = rasterToWorld(new Point2D.Double(0, line));
686
                Point2D end = rasterToWorld(new Point2D.Double(file.width, line + 1));
687
                int[] readBandsFromECW = new int[file.numBands];
688
                if(file.numBands <= 3) {
689
                        for(int i = 0; i < file.numBands; i++)
690
                                readBandsFromECW[i] = i;
691
                } else {
692
                        readBandsFromECW[0] = band;
693
                }
694

    
695
                Extent e = new ExtentImpl(begin.getX(), begin.getY(), end.getX(), end.getY());
696

    
697
                try {
698
                        int[] value = new int[file.width];
699
                        file.setView(file.numBands, readBandsFromECW, e.minX(), e.maxY(), e.maxX(), e.minY(), file.width, 1);
700
                        file.readLineRGBA(value);
701

    
702
                        if(file.numBands <= 3) {
703
                                switch(getDataType()[0]) {
704
                                case Buffer.TYPE_BYTE: byte[] b = new byte[file.width];
705
                                                                                switch(band) {
706
                                                                                case 0: for(int i = 0; i < file.width; i ++)
707
                                                                                                        b[i] = (byte)(((value[i] & 0x00ff0000) >> 16) & 0xff);
708
                                                                                                break;
709
                                                                                case 1: for(int i = 0; i < file.width; i ++)
710
                                                                                                        b[i] = (byte)(((value[i] & 0x0000ff00) >> 8) & 0xff);
711
                                                                                                break;
712
                                                                                case 2: for(int i = 0; i < file.width; i ++)
713
                                                                                                        b[i] = (byte)((value[i] & 0x000000ff) & 0xff);
714
                                                                                                break;
715
                                                                                }
716
                                                                                return b;
717
                                }
718
                        }else {
719
                                switch(getDataType()[0]) {
720
                                case Buffer.TYPE_BYTE: byte[] b = new byte[file.width];
721
                                                                                for(int i = 0; i < file.width; i ++)
722
                                                                                        b[i] = (byte)(((value[i] & 0x00ff0000) >> 16) & 0xff);
723
                                                                                break;
724
                                }
725
                        }
726
                        //TODO: FUNCIONALIDAD: Ecw con otro tipo de dato != Byte
727
                } catch (JNCSFileNotOpenException e1) {
728
                        throw new FileNotOpenException("Error en jecw: JNCSFileNotOpenException");
729
                } catch (JNCSInvalidSetViewException e1) {
730
                        throw new FileNotOpenException("Error en jecw: JNCSInvalidSetViewException");
731
                } catch (JNCSException e1) {
732
                        throw new RasterDriverException("Error la lectura de datos ecw");
733
                }
734

    
735
                return null;
736
        }
737

    
738
        public Object readBlock(int pos, int blockHeight, double scale) throws InvalidSetViewException, FileNotOpenException, RasterDriverException, ProcessInterruptedException {
739
                RasterTask task = RasterTaskQueue.get(Thread.currentThread().getId() + "");
740
                if(pos < 0)
741
                        throw new InvalidSetViewException("Request out of grid");
742

    
743
                if((pos + blockHeight) > file.height)
744
                        blockHeight = Math.abs(file.height - pos);
745

    
746
                Point2D begin = rasterToWorld(new Point2D.Double(0, pos));
747
                Point2D end = rasterToWorld(new Point2D.Double(file.width, pos + blockHeight));
748
                int[] readBandsFromECW = new int[file.numBands];
749

    
750
                for(int i = 0; i < file.numBands; i++)
751
                        readBandsFromECW[i] = i;
752

    
753
                byte[][][] buf = new byte[file.numBands][blockHeight][file.width];
754
                Extent e = new ExtentImpl(begin.getX(), begin.getY(), end.getX(), end.getY());
755
                e = rasterUtil.calculateAdjustedView(getExtent(), e);
756

    
757
                try {
758
                        int[] value = new int[file.width];
759
                        file.setView(file.numBands, readBandsFromECW, e.minX(), e.maxY(), e.maxX(), e.minY(), file.width, blockHeight);
760

    
761
                        if(file.numBands <= 3) {
762
                                for (int row = 0; row < blockHeight; row++) {
763
                                        file.readLineRGBA(value);
764
                                        switch(getDataType()[0]) {
765
                                        case Buffer.TYPE_BYTE:
766
                                                if(buf.length >= 3) {
767
                                                        for(int col = 0; col < file.width; col ++) {
768
                                                                buf[0][row][col] = (byte)(((value[col] & 0x00ff0000) >> 16) & 0xff);
769
                                                                buf[1][row][col] = (byte)(((value[col] & 0x0000ff00) >> 8) & 0xff);
770
                                                                buf[2][row][col] = (byte)((value[col] & 0x000000ff) & 0xff);
771
                                                        }
772
                                                } else { //Si es monobanda solo se usa cualquiera uno de los tres valores
773
                                                        for(int col = 0; col < file.width; col ++) {
774
                                                                buf[0][row][col] = (byte)(((value[col] & 0x00ff0000) >> 16) & 0xff);
775
                                                        }
776
                                                }
777
                                                break;
778
                                        }
779
                                }
780

    
781
                                if(task.getEvent() != null)
782
                                        task.manageEvent(task.getEvent());
783

    
784
                        } else {
785
                                //TODO: FUNCIONALIDAD: file.numBands > 3
786
                        }
787

    
788
                        //TODO: FUNCIONALIDAD: Ecw con otro tipo de dato != Byte
789
                } catch (JNCSFileNotOpenException e1) {
790
                        throw new FileNotOpenException("Error en jecw: JNCSFileNotOpenException");
791
                } catch (JNCSInvalidSetViewException e1) {
792
                        throw new FileNotOpenException("Error en jecw: JNCSInvalidSetViewException");
793
                } catch (JNCSException e1) {
794
                        throw new RasterDriverException("Error la lectura de datos ecw");
795
                }
796

    
797
                return buf;
798
        }
799

    
800
        public Object getData(int x, int y, int band)throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
801
                if(x < 0 || y < 0 || x >= file.width || y >= file.height)
802
                        throw new InvalidSetViewException("Request out of grid");
803

    
804
                Point2D begin = new Point2D.Double(x, y);
805
                Point2D end = new Point2D.Double(x + 1, y + 1);
806

    
807
                ownTransformation.transform(begin, begin);
808
                ownTransformation.transform(end, end);
809

    
810
                int[] readBandsFromECW = new int[file.numBands];
811
                if(file.numBands <= 3){
812
                        for(int i = 0; i < file.numBands; i++)
813
                                readBandsFromECW[i] = i;
814
                }else{
815
                        readBandsFromECW[0] = band;
816
                }
817

    
818
                Extent e = new ExtentImpl(begin.getX(), begin.getY(), end.getX(), end.getY());
819
                try {
820
                        int[] value = new int[1];
821
                        file.setView(file.numBands, readBandsFromECW, e.minX(), e.maxY(), e.maxX(), e.minY(), 1, 1);
822
                        file.readLineRGBA(value);
823
                        if(file.numBands <= 3){
824
                                switch(band){
825
                                case 0: return new Integer((((value[0] & 0x00ff0000) >> 16) & 0xffffffff));
826
                                case 1: return new Integer((((value[0] & 0x0000ff00) >> 8) & 0xffffffff));
827
                                case 2: return new Integer((((value[0] & 0x000000ff)) & 0xffffffff));
828
                                }
829
                        }
830
                        return new Integer((((value[0] & 0x00ff0000) >> 16) & 0xffffffff));
831
                } catch (JNCSFileNotOpenException e1) {
832
                        throw new FileNotOpenException("Error en jecw: JNCSFileNotOpenException");
833
                } catch (JNCSInvalidSetViewException e1) {
834
                        throw new FileNotOpenException("Error en jecw: JNCSInvalidSetViewException");
835
                } catch (JNCSException e1) {
836
                        throw new RasterDriverException("Error reading ecw data");
837
                }
838
        }
839

    
840
        public void refreshUpdate(int arg0, int arg1, double arg2, double arg3, double arg4, double arg5) {
841
        }
842

    
843
        public void refreshUpdate(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) {
844
        }
845

    
846
        public DataStoreColorInterpretation getColorInterpretation(){
847
                if(colorInterpr == null) {
848
                        colorInterpr = new DataStoreColorInterpretation();
849
                        colorInterpr.initColorInterpretation(getBandCount());
850
                        if(getBandCount() == 1)
851
                                colorInterpr.setColorInterpValue(0, DataStoreColorInterpretation.GRAY_BAND);
852
                        if(getBandCount() >= 3) {
853
                                colorInterpr.setColorInterpValue(0, DataStoreColorInterpretation.RED_BAND);
854
                                colorInterpr.setColorInterpValue(1, DataStoreColorInterpretation.GREEN_BAND);
855
                                colorInterpr.setColorInterpValue(2, DataStoreColorInterpretation.BLUE_BAND);
856
                        }
857
                }
858
                return colorInterpr;
859
        }
860

    
861
        public int getOverviewCount(int band) throws BandAccessException, RasterDriverException {
862
                if(band >= getBandCount())
863
                        throw new BandAccessException("Wrong band");
864
                return 0;
865
        }
866

    
867
        public int getOverviewWidth(int band, int overview) throws BandAccessException, RasterDriverException {
868
                if (band >= getBandCount())
869
                        throw new BandAccessException("Wrong band");
870
                return 0;
871
        }
872

    
873
        public int getOverviewHeight(int band, int overview) throws BandAccessException, RasterDriverException {
874
                if (band >= getBandCount())
875
                        throw new BandAccessException("Wrong band");
876
                return 0;
877
        }
878

    
879
        public boolean isOverviewsSupported() {
880
                return false;
881
        }
882

    
883
        
884
        public String getStringProjection() throws RasterDriverException{
885
                return file.projection;
886
        }
887

    
888
        public String getWktProjection() {
889
                return null;
890
        }
891
        
892
        public String getName() {
893
                return NAME;
894
        }
895
        
896
        public void setStatus(RasterProvider provider) {
897
                if(provider instanceof ErmapperProvider) {
898
                        //Not implemented yet
899
                }
900
        }
901
        
902
        public boolean isSupersamplingSupported() {
903
                return false;
904
        }
905
        
906
        public TileServer getTileServer() {
907
                if(tileServer == null) {
908
                        DefaultRasterStore store = new DefaultRasterStore();
909
                        store.setProvider(this);
910
                        tileServer = new FileTileServer(store);
911
                }
912
                return tileServer;
913
        }
914
}