Statistics
| Revision:

gvsig-raster / org.gvsig.raster.ermapper / trunk / org.gvsig.raster.ermapper / org.gvsig.raster.ermapper.io / src / main / java / org / gvsig / raster / ermapper / io / ErmapperProvider.java @ 4181

History | View | Annotate | Download (35.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.NoninvertibleTransformException;
26
import java.awt.geom.Point2D;
27
import java.io.BufferedReader;
28
import java.io.File;
29
import java.io.FileReader;
30
import java.net.URI;
31
import java.net.URISyntaxException;
32

    
33
import org.cresques.cts.ICoordTrans;
34
import org.slf4j.Logger;
35
import org.slf4j.LoggerFactory;
36

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

    
75
import com.ermapper.ecw.JNCSException;
76
import com.ermapper.ecw.JNCSFile;
77
import com.ermapper.ecw.JNCSFileNotOpenException;
78
import com.ermapper.ecw.JNCSInvalidSetViewException;
79
import com.ermapper.ecw.JNCSProgressiveUpdate;
80

    
81
/**
82
 * Driver de Ecw
83
 *
84
 * @author Nacho Brodin (nachobrodin@gmail.com)
85
 */
86
public class ErmapperProvider extends AbstractRasterProvider implements JNCSProgressiveUpdate {
87

    
88
    private static final Logger logger = LoggerFactory.getLogger(ErmapperProvider.class);
89
    public static String NAME = "Ermapper Store";
90
    public static String DESCRIPTION = "Ermapper Raster file";
91
    public static final String METADATA_DEFINITION_NAME = "ErmapperStore";
92
    private JNCSFile file = null;
93
    protected Transparency fileTransparency = null;
94
    private Extent viewRequest = null;
95
    private DataStoreColorInterpretation colorInterpr = null;
96
    private boolean open = false;
97
    protected static String[] formatList = null;
98

    
99
    public static void register() {
100
        RasterLocator.getManager().getProviderServices().registerFileProvidersTiled(ErmapperProvider.class);
101
        registerFormats();
102

    
103
        DataManagerProviderServices dataman = (DataManagerProviderServices) DALLocator.getDataManager();
104
        if (dataman != null && !dataman.getStoreProviders().contains(NAME)) {
105
            dataman.registerStoreProvider(NAME, ErmapperProvider.class, ErmapperDataParameters.class);
106
        }
107

    
108
        if (DALFileLocator.getFilesystemServerExplorerManager() != null)
109
            DALFileLocator.getFilesystemServerExplorerManager().registerProvider(NAME, DESCRIPTION,
110
                ErmapperFilesystemServerExplorer.class);
111

    
112
        dataman.registerStoreFactory(NAME, DefaultStoreFactory.class);
113
    }
114

    
115
    private static void registerFormats() {
116
        formatList = new String[] { "ecw", "jp2" };
117
        for (int i = 0; i < formatList.length; i++)
118
            RasterLocator.getManager().getProviderServices().addFormat(formatList[i], ErmapperProvider.class);
119
    }
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
     *
128
     * @param ext
129
     * @return
130
     */
131
    public boolean isExtensionSupported(String ext) {
132
        if (ext.indexOf(".") != -1)
133
            ext = ext.substring(ext.lastIndexOf(".") + 1, ext.length());
134
        for (int i = 0; i < formatList.length; i++) {
135
            if (formatList[i].compareTo(ext) == 0)
136
                return true;
137
        }
138
        return false;
139
    }
140

    
141
    /**
142
     * Mandatory constructor to instantiate an empty provider
143
     */
144
    public ErmapperProvider() {
145
    }
146

    
147
    /**
148
     * Constructor. Abre el dataset.
149
     *
150
     * @param proj
151
     *            Proyecci?n
152
     * @param fName
153
     *            Nombre del fichero ecw
154
     * @throws NotSupportedExtensionException
155
     * @throws OpenException
156
     * @deprecated use {@link #ErmapperProvider(URI)}, this constructor will be removed in gvSIG 2.5
157
     */
158
    public ErmapperProvider(String params) throws NotSupportedExtensionException, OpenException {
159
        super(params);
160
        logger.info("Deprecated use of ErmapperProvider constructor");
161
        if (params instanceof String) {
162
            ErmapperDataParameters p = new ErmapperDataParameters();
163
            try {
164
                p.setURI(new URI((String) params));
165
            } catch (URISyntaxException e) {
166
                throw new OpenException("Can't create URI from" + (String) params, e);
167
            }
168
            super.init(
169
                p,
170
                null,
171
                ToolsLocator.getDynObjectManager().createDynObject(
172
                    MetadataLocator.getMetadataManager().getDefinition(DataStore.METADATA_DEFINITION_NAME)));
173
            init(p, null);
174
        }
175
    }
176

    
177
    /**
178
     * Constructor. Abre el dataset.
179
     *
180
     * @param proj
181
     *            Proyecci?n
182
     * @param uri
183
     *            uri del fichero ecw
184
     * @throws NotSupportedExtensionException
185
     */
186
    public ErmapperProvider(URI uri) throws NotSupportedExtensionException {
187
        super(uri);
188
        ErmapperDataParameters p = new ErmapperDataParameters();
189
        p.setURI(uri);
190
        super.init(
191
            p,
192
            null,
193
            ToolsLocator.getDynObjectManager().createDynObject(
194
                MetadataLocator.getMetadataManager().getDefinition(DataStore.METADATA_DEFINITION_NAME)));
195
        init(p, null);
196
    }
197

    
198
    public ErmapperProvider(ErmapperDataParameters params, DataStoreProviderServices storeServices)
199
        throws NotSupportedExtensionException {
200
        super(params, storeServices, ToolsLocator.getDynObjectManager().createDynObject(
201
            MetadataLocator.getMetadataManager().getDefinition(DataStore.METADATA_DEFINITION_NAME)));
202
        init(params, storeServices);
203
    }
204

    
205
    /**
206
     * Abre el dataset.
207
     *
208
     * @param proj
209
     *            Proyecci?n
210
     * @param fName
211
     *            Nombre del fichero ecw
212
     * @throws NotSupportedExtensionException
213
     */
214
    public void init(AbstractRasterDataParameters params, DataStoreProviderServices storeServices)
215
        throws NotSupportedExtensionException {
216
        setParam(storeServices, params);
217
        if (!((RasterFileStoreParameters) param).getFile().exists()
218
            && !("ecwp".equalsIgnoreCase(((RasterDataParameters) param).getURI().getScheme()))) {
219
            throw new NotSupportedExtensionException("Extension not supported");
220
        }
221

    
222
        try {
223
            String stringPath = ((RasterFileStoreParameters) param).getFile().getPath();
224
            file = new JNCSFile(stringPath, false);
225
        } catch (JNCSException e1) {
226
            throw new NotSupportedExtensionException("Error loading the ecw file", e1);
227
        }
228

    
229
        /*
230
         * TODO: Leer proyecciones ECW
231
         *
232
         * wktProjection = null;//getWKTFromEcw_csFile(file.projection);
233
         * if(wktProjection != null && wktProjection != "") {
234
         * try {
235
         * proj =
236
         * RasterLocator.getManager().getCRSUtils().convertWktToIProjection
237
         * (wktProjection);
238
         * } catch (Exception e) {
239
         * logger.info("Error reading WKT from the raster provider", e);
240
         * }
241
         * }
242
         */
243

    
244
        load();
245
        bandCount = file.numBands;
246

    
247
        int[] dt = new int[bandCount];
248
        for (int i = 0; i < bandCount; i++)
249
            dt[i] = Buffer.TYPE_BYTE;
250
        setDataType(dt);
251

    
252
        super.init();
253

    
254
        try {
255
            loadFromRmf(getRmfBlocksManager());
256
        } catch (ParsingException e) {
257
            // No lee desde rmf
258
        }
259
        open = true;
260
    }
261

    
262
    @SuppressWarnings("unused")
263
    private String getWKTFromEcw_csFile(String identifier) {
264
        File file = new File("./");
265
        file =
266
            new File(file.getAbsoluteFile() + File.separator + "data" + File.separator + "gdal" + File.separator
267
                + "ecw_cs.wkt");
268
        if (file.exists()) {
269
            FileReader fr = null;
270
            BufferedReader br = null;
271
            try {
272
                fr = new FileReader(file);
273
                br = new BufferedReader(fr);
274

    
275
                String line;
276
                while ((line = br.readLine()) != null) {
277
                    if (line.startsWith(identifier + ",")) {
278
                        int index = line.indexOf(",") + 1;
279
                        return line.substring(index);
280
                    }
281
                }
282
            } catch (Exception e) {
283
                return null;
284
            } finally {
285
                try {
286
                    if (fr != null)
287
                        fr.close();
288
                } catch (Exception e2) {
289
                    e2.printStackTrace();
290
                }
291
            }
292
        }
293
        return null;
294
    }
295

    
296
    public RasterProvider load() {
297
        ownTransformation =
298
            new AffineTransform(file.cellIncrementX, 0, 0, file.cellIncrementY, file.originX, file.originY);
299
        externalTransformation = (AffineTransform) ownTransformation.clone();
300
        return this;
301
    }
302

    
303
    public boolean isOpen() {
304
        return open;
305
    }
306

    
307
    public void close() {
308
        if (file != null) {
309
            open = false;
310
            // Cuando se abren varios datastores del mismo fichero y se cierra
311
            // uno de ellos se cierra la aplicaci?n en el siguiente dibujado
312
            // Se deber?a buscar una soluci?n ya que en los PrepareLayer se abre
313
            // y cierra para hacer comprobaciones.
314
            // file.close(false);
315
            file = null;
316
        }
317
    }
318

    
319
    public Transparency getTransparency() {
320
        if (fileTransparency == null)
321
            fileTransparency = new DataStoreTransparency(getColorInterpretation());
322
        return fileTransparency;
323
    }
324

    
325
    public double getWidth() {
326
        return file.width;
327
    }
328

    
329
    public double getHeight() {
330
        return file.height;
331
    }
332

    
333
    public Extent getView() {
334
        return viewRequest;
335
    }
336

    
337
    public void setView(Extent e) {
338
        viewRequest = new ExtentImpl(e);
339
    }
340

    
341
    @Override
342
    public void loadBuffer(SpiRasterQuery query) throws ProcessInterruptedException, RasterDriverException {
343
        setView(transformExternalGeorefToOwnGeoref(query.getAdjustedRequestBoundingBox()));
344
        int bufWidth = query.getAdjustedBufWidth();
345
        int bufHeight = query.getAdjustedBufHeight();
346
        int[] stpBuffer = new int[] { 0, 0, bufWidth, bufHeight };
347
        loadBuffer(viewRequest, bufWidth, bufHeight, query.getBufferForProviders(), query.getBandList(), stpBuffer,
348
            query.getTaskStatus());
349
    }
350

    
351
    /**
352
     * Converts coordinates from the external transformation to the own
353
     * transformation.
354
     * This is useful when the user assigns a transformation or the own raster
355
     * has one
356
     * in the rmf file. Ecw need this function because the data window are
357
     * requested to
358
     * the library in world coordinates.
359
     *
360
     * @param ext
361
     * @return
362
     */
363
    private Extent transformExternalGeorefToOwnGeoref(Extent ext) {
364
        if (externalTransformation.equals(ownTransformation))
365
            return ext;
366

    
367
        Point2D ul = ext.getUL();
368
        Point2D lr = ext.getLR();
369

    
370
        Point2D p1 = new Point2D.Double();
371
        Point2D p2 = new Point2D.Double();
372

    
373
        try {
374
            externalTransformation.inverseTransform(ul, p1);
375
        } catch (NoninvertibleTransformException e) {
376
            e.printStackTrace();
377
        }
378
        ownTransformation.transform(p1, p1);
379

    
380
        try {
381
            externalTransformation.inverseTransform(lr, p2);
382
        } catch (NoninvertibleTransformException e) {
383
            e.printStackTrace();
384
        }
385
        ownTransformation.transform(p2, p2);
386

    
387
        return RasterLocator.getManager().getDataStructFactory().createExtent(p1, p2);
388
    }
389

    
390
    /**
391
     * Carga el buffer con las bandas RGB del raster con los par?metros
392
     * especificados de extensi?n
393
     * y tama?o de buffer. El problema de ecw es que solo podemos leer 3 bandas
394
     * de una vez ya que solo disponemos
395
     * de una llamada readLineRGBA. Para leer m?s bandas tendremos que hacer
396
     * multiples llamadas a setView para leer
397
     * 3 cada vez.
398
     *
399
     * Si por ejemplo tenemos un ecw de 6 bandas [0, 1, 2, 3, 4, 5] y queremos
400
     * cargar un buffer con el siguiente orden
401
     * [0, -, 2, -, 4, -] La variable readBandsFromECW har? la llamada a setView
402
     * con los valores [0, 2, 4, 0, 0, 0]. La
403
     * funci?n drawRGB ser? la encargada de hacer el switch para obtener [0, -,
404
     * 2, -, 4, -].
405
     *
406
     * Bug#1: Si se dispone de un ecw de m?s de tres bandas podemos llamar a
407
     * setView con readBandsFromECW con el orden
408
     * que queramos, por ejemplo [3, 2, 5, 1, 0] pero para ecw de 3 bandas la
409
     * llamada con las bandas cambiadas no
410
     * hace caso. El caso de readBandsFromECW = [2, 0, 1] ser? tomado siempre
411
     * como [0, 1, 2].
412
     *
413
     * @param selectedExtent
414
     *            Extensi?n seleccionada
415
     * @param bufWidth
416
     *            Ancho de buffer
417
     * @param bufHeight
418
     *            Alto de buffer
419
     * @param rasterBuf
420
     *            Buffer de datos
421
     */
422
    private void loadBuffer(Extent selectedExtent, int bufWidth, int bufHeight, Buffer rasterBuf, BandList bandList,
423
        int[] stpBuffer, TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
424
        try {
425
            RasterTask task = RasterTaskQueue.get(Thread.currentThread().getId() + "");
426

    
427
            int[] readBandsFromECW = new int[Math.max(file.numBands, 3)];
428

    
429
            for (int i = 0; i < readBandsFromECW.length; i++) {
430
                readBandsFromECW[i] = i;
431
            }
432

    
433
            if (task.getEvent() != null)
434
                task.manageEvent(task.getEvent());
435
            if (status != null && status.isCancelled())
436
                return;
437

    
438
            if (bufWidth > Math.round(Math.abs(selectedExtent.width() / file.cellIncrementX)))
439
                bufWidth = (int) Math.round(Math.abs(selectedExtent.width() / file.cellIncrementX));
440
            if (bufHeight > Math.round(Math.abs(selectedExtent.height() / file.cellIncrementY)))
441
                bufHeight = (int) Math.round(Math.abs(selectedExtent.height() / file.cellIncrementY));
442
            file.setView(file.numBands, readBandsFromECW, selectedExtent.minX(), selectedExtent.maxY(),
443
                selectedExtent.maxX(), selectedExtent.minY(), bufWidth, bufHeight);
444

    
445
            // Escribimos el raster sobre un Buffer
446
            int[] pRGBArray = new int[bufWidth];
447
            drawRGB2(rasterBuf, pRGBArray, bandList, status);
448

    
449
        } catch (JNCSInvalidSetViewException exc) {
450
            throw new RasterDriverException("Error setting coords");
451
        } catch (JNCSFileNotOpenException e) {
452
            throw new RasterDriverException("Error opening file");
453
        } catch (JNCSException ex) {
454
            throw new RasterDriverException("Error reading data");
455
        }
456

    
457
    }
458

    
459
    private void drawRGB2(Buffer rasterBuf, int[] pRGBArray, BandList bandList, TaskStatus status)
460
        throws JNCSException, ProcessInterruptedException {
461
        RasterTask task = RasterTaskQueue.get(Thread.currentThread().getId() + "");
462
        int[] drawableBands = null;
463

    
464
        for (int line = 0; line < rasterBuf.getHeight(); line++) {
465
            try {
466
                file.readLineRGBA(pRGBArray);
467
                for (int col = 0; col < pRGBArray.length; col++) {
468
                    drawableBands = bandList.getBufferBandToDraw(getURIOfFirstProvider().getPath(), 0);
469
                    if (drawableBands != null) {
470
                        for (int i = 0; i < drawableBands.length; i++) {
471
                            if (drawableBands[i] != -1)
472
                                rasterBuf.setElem(line, col, drawableBands[i],
473
                                    (byte) ((pRGBArray[col] & 0x00ff0000) >> 16));
474
                        }
475
                    }
476
                    drawableBands = bandList.getBufferBandToDraw(getURIOfFirstProvider().getPath(), 1);
477
                    if (drawableBands != null) {
478
                        for (int i = 0; i < drawableBands.length; i++) {
479
                            if (drawableBands[i] != -1)
480
                                rasterBuf.setElem(line, col, drawableBands[i],
481
                                    (byte) ((pRGBArray[col] & 0x0000ff00) >> 8));
482
                        }
483
                    }
484
                    drawableBands = bandList.getBufferBandToDraw(getURIOfFirstProvider().getPath(), 2);
485
                    if (drawableBands != null) {
486
                        for (int i = 0; i < drawableBands.length; i++) {
487
                            if (drawableBands[i] != -1)
488
                                rasterBuf.setElem(line, col, drawableBands[i], (byte) (pRGBArray[col] & 0x000000ff));
489
                        }
490
                    }
491
                }
492
            } catch (JNCSException exc) {
493
            }
494
            if (task.getEvent() != null)
495
                task.manageEvent(task.getEvent());
496
            if (status != null && status.isCancelled())
497
                return;
498
        }
499
        return;
500
    }
501

    
502
    @SuppressWarnings("unused")
503
    private void drawRGB(Buffer rasterBuf, int[] pRGBArray, int[] readBands, BandList bandList, RasterTask task)
504
        throws JNCSException, ProcessInterruptedException {
505
        int bandR = readBands[0];
506
        int bandG = (readBands.length > 1) ? readBands[1] : -1;
507
        int bandB = (readBands.length > 2) ? readBands[2] : -1;
508

    
509
        // ********* caso especial que resuelve Bug#1 **********************
510
        if (file.numBands == 3 && bandList.getDrawableBandsCount() < 3) {
511
            for (int i = 0; i < 3; i++) {
512
                int[] b = bandList.getBand(i).getBufferBandListToDraw();
513
                if (b != null) {
514
                    bandG = 1;
515
                    bandR = 0;
516
                    bandB = 2;
517
                }
518
            }
519
        }
520
        if (file.numBands == 3 && bandR == bandG && bandG == bandB) { // caso
521
                                                                      // especial
522
                                                                      // que
523
                                                                      // resuelve
524
                                                                      // Bug#1
525
            for (int i = 0; i < 3; i++) {
526
                int[] b = bandList.getBand(i).getBufferBandListToDraw();
527
                if (b != null) {
528
                    if (i == 0) {
529
                        for (int line = 0; line < rasterBuf.getHeight(); line++) {
530
                            try {
531
                                file.readLineRGBA(pRGBArray);
532
                                for (int col = 0; col < pRGBArray.length; col++) {
533
                                    rasterBuf.setElem(line, col, bandR, (byte) ((pRGBArray[col] & 0x00ff0000) >> 16));
534
                                    rasterBuf.setElem(line, col, bandG, (byte) ((pRGBArray[col] & 0x00ff0000) >> 16));
535
                                    rasterBuf.setElem(line, col, bandB, (byte) ((pRGBArray[col] & 0x00ff0000) >> 16));
536
                                }
537
                            } catch (JNCSException exc) {
538
                            }
539
                        }
540
                        return;
541
                    }
542
                    if (i == 1) {
543
                        for (int line = 0; line < rasterBuf.getHeight(); line++) {
544
                            try {
545
                                file.readLineRGBA(pRGBArray);
546
                                for (int col = 0; col < pRGBArray.length; col++) {
547
                                    rasterBuf.setElem(line, col, bandR, (byte) ((pRGBArray[col] & 0x0000ff00) >> 8));
548
                                    rasterBuf.setElem(line, col, bandG, (byte) ((pRGBArray[col] & 0x0000ff00) >> 8));
549
                                    rasterBuf.setElem(line, col, bandB, (byte) ((pRGBArray[col] & 0x0000ff00) >> 8));
550
                                }
551
                            } catch (JNCSException exc) {
552
                            }
553
                        }
554
                        return;
555
                    }
556
                    if (i == 2) {
557
                        for (int line = 0; line < rasterBuf.getHeight(); line++) {
558
                            try {
559
                                file.readLineRGBA(pRGBArray);
560
                                for (int col = 0; col < pRGBArray.length; col++) {
561
                                    rasterBuf.setElem(line, col, bandR, (byte) (pRGBArray[col] & 0x000000ff));
562
                                    rasterBuf.setElem(line, col, bandG, (byte) (pRGBArray[col] & 0x000000ff));
563
                                    rasterBuf.setElem(line, col, bandB, (byte) (pRGBArray[col] & 0x000000ff));
564
                                }
565
                            } catch (JNCSException exc) {
566
                            }
567
                        }
568
                        return;
569
                    }
570
                }
571
                if (task.getEvent() != null)
572
                    task.manageEvent(task.getEvent());
573
            }
574

    
575
        }
576
        // ********* END caso especial que resuelve Bug#1 **********************
577

    
578
        if (bandR >= 0 && bandG >= 0 && bandB >= 0) {
579
            for (int line = 0; line < rasterBuf.getHeight(); line++) {
580
                try {
581
                    file.readLineRGBA(pRGBArray);
582
                    for (int col = 0; col < pRGBArray.length; col++) {
583
                        rasterBuf.setElem(line, col, bandR, (byte) ((pRGBArray[col] & 0x00ff0000) >> 16));
584
                        rasterBuf.setElem(line, col, bandG, (byte) ((pRGBArray[col] & 0x0000ff00) >> 8));
585
                        rasterBuf.setElem(line, col, bandB, (byte) (pRGBArray[col] & 0x000000ff));
586
                    }
587
                } catch (JNCSException exc) {
588
                }
589
            }
590
            return;
591
        }
592

    
593
        if (task.getEvent() != null)
594
            task.manageEvent(task.getEvent());
595

    
596
        if (bandR >= 0 && bandG >= 0) {
597
            for (int line = 0; line < rasterBuf.getHeight(); line++) {
598
                try {
599
                    file.readLineRGBA(pRGBArray);
600
                    for (int col = 0; col < pRGBArray.length; col++) {
601
                        rasterBuf.setElem(line, col, bandR, (byte) ((pRGBArray[col] & 0x00ff0000) >> 16));
602
                        rasterBuf.setElem(line, col, bandG, (byte) ((pRGBArray[col] & 0x0000ff00) >> 8));
603
                    }
604
                } catch (JNCSException exc) {
605
                }
606
            }
607
            return;
608
        }
609

    
610
        if (task.getEvent() != null)
611
            task.manageEvent(task.getEvent());
612

    
613
        if (bandR >= 0) {
614
            for (int line = 0; line < rasterBuf.getHeight(); line++) {
615
                try {
616
                    file.readLineRGBA(pRGBArray);
617
                    for (int col = 0; col < pRGBArray.length; col++)
618
                        rasterBuf.setElem(line, col, bandR, (byte) ((pRGBArray[col] & 0x00ff0000) >> 16));
619
                } catch (JNCSException exc) {
620
                }
621
            }
622
            return;
623
        }
624

    
625
        if (task.getEvent() != null)
626
            task.manageEvent(task.getEvent());
627

    
628
    }
629

    
630
    public void reProject(ICoordTrans rp) {
631
    }
632

    
633
    public int getBlockSize() {
634
        return 0;
635
    }
636

    
637
    public Object readCompleteLine(int line, int band) throws InvalidSetViewException, FileNotOpenException,
638
        RasterDriverException {
639
        if (line < 0 || line >= file.height || band < 0 || band >= getBandCount())
640
            throw new InvalidSetViewException("Request out of grid");
641

    
642
        Point2D begin = rasterToWorld(new Point2D.Double(0, line));
643
        Point2D end = rasterToWorld(new Point2D.Double(file.width, line + 1));
644
        int[] readBandsFromECW = new int[file.numBands];
645
        if (file.numBands <= 3) {
646
            for (int i = 0; i < file.numBands; i++)
647
                readBandsFromECW[i] = i;
648
        } else {
649
            readBandsFromECW[0] = band;
650
        }
651

    
652
        Extent e = new ExtentImpl(begin.getX(), begin.getY(), end.getX(), end.getY());
653

    
654
        try {
655
            int[] value = new int[file.width];
656
            file.setView(file.numBands, readBandsFromECW, e.minX(), e.maxY(), e.maxX(), e.minY(), file.width, 1);
657
            file.readLineRGBA(value);
658

    
659
            if (file.numBands <= 3) {
660
                switch (getDataType()[0]) {
661
                case Buffer.TYPE_BYTE:
662
                    byte[] b = new byte[file.width];
663
                    switch (band) {
664
                    case 0:
665
                        for (int i = 0; i < file.width; i++)
666
                            b[i] = (byte) (((value[i] & 0x00ff0000) >> 16) & 0xff);
667
                        break;
668
                    case 1:
669
                        for (int i = 0; i < file.width; i++)
670
                            b[i] = (byte) (((value[i] & 0x0000ff00) >> 8) & 0xff);
671
                        break;
672
                    case 2:
673
                        for (int i = 0; i < file.width; i++)
674
                            b[i] = (byte) ((value[i] & 0x000000ff) & 0xff);
675
                        break;
676
                    }
677
                    return b;
678
                }
679
            } else {
680
                switch (getDataType()[0]) {
681
                case Buffer.TYPE_BYTE:
682
                    byte[] b = new byte[file.width];
683
                    for (int i = 0; i < file.width; i++)
684
                        b[i] = (byte) (((value[i] & 0x00ff0000) >> 16) & 0xff);
685
                    break;
686
                }
687
            }
688
            // TODO: FUNCIONALIDAD: Ecw con otro tipo de dato != Byte
689
        } catch (JNCSFileNotOpenException e1) {
690
            throw new FileNotOpenException("Error en jecw: JNCSFileNotOpenException");
691
        } catch (JNCSInvalidSetViewException e1) {
692
            throw new FileNotOpenException("Error en jecw: JNCSInvalidSetViewException");
693
        } catch (JNCSException e1) {
694
            throw new RasterDriverException("Error la lectura de datos ecw");
695
        }
696

    
697
        return null;
698
    }
699

    
700
    public Object readBlock(int pos, int blockHeight, double scale) throws InvalidSetViewException,
701
        FileNotOpenException, RasterDriverException, ProcessInterruptedException {
702
        RasterTask task = RasterTaskQueue.get(Thread.currentThread().getId() + "");
703
        if (pos < 0)
704
            throw new InvalidSetViewException("Request out of grid");
705

    
706
        if ((pos + blockHeight) > file.height)
707
            blockHeight = Math.abs(file.height - pos);
708

    
709
        Point2D begin = rasterToWorld(new Point2D.Double(0, pos));
710
        Point2D end = rasterToWorld(new Point2D.Double(file.width, pos + blockHeight));
711
        int[] readBandsFromECW = new int[file.numBands];
712

    
713
        for (int i = 0; i < file.numBands; i++)
714
            readBandsFromECW[i] = i;
715

    
716
        byte[][][] buf = new byte[file.numBands][blockHeight][file.width];
717
        Extent e = new ExtentImpl(begin.getX(), begin.getY(), end.getX(), end.getY());
718
        e = rasterUtil.calculateAdjustedView(getExtent(), e);
719

    
720
        try {
721
            int[] value = new int[file.width];
722
            file.setView(file.numBands, readBandsFromECW, e.minX(), e.maxY(), e.maxX(), e.minY(), file.width,
723
                blockHeight);
724

    
725
            if (file.numBands <= 3) {
726
                for (int row = 0; row < blockHeight; row++) {
727
                    file.readLineRGBA(value);
728
                    switch (getDataType()[0]) {
729
                    case Buffer.TYPE_BYTE:
730
                        if (buf.length >= 3) {
731
                            for (int col = 0; col < file.width; col++) {
732
                                buf[0][row][col] = (byte) (((value[col] & 0x00ff0000) >> 16) & 0xff);
733
                                buf[1][row][col] = (byte) (((value[col] & 0x0000ff00) >> 8) & 0xff);
734
                                buf[2][row][col] = (byte) ((value[col] & 0x000000ff) & 0xff);
735
                            }
736
                        } else { // Si es monobanda solo se usa cualquiera uno
737
                                 // de los tres valores
738
                            for (int col = 0; col < file.width; col++) {
739
                                buf[0][row][col] = (byte) (((value[col] & 0x00ff0000) >> 16) & 0xff);
740
                            }
741
                        }
742
                        break;
743
                    }
744
                }
745

    
746
                if (task.getEvent() != null)
747
                    task.manageEvent(task.getEvent());
748

    
749
            } else {
750
                // TODO: FUNCIONALIDAD: file.numBands > 3
751
            }
752

    
753
            // TODO: FUNCIONALIDAD: Ecw con otro tipo de dato != Byte
754
        } catch (JNCSFileNotOpenException e1) {
755
            throw new FileNotOpenException("Error en jecw: JNCSFileNotOpenException");
756
        } catch (JNCSInvalidSetViewException e1) {
757
            throw new FileNotOpenException("Error en jecw: JNCSInvalidSetViewException");
758
        } catch (JNCSException e1) {
759
            throw new RasterDriverException("Error la lectura de datos ecw");
760
        }
761

    
762
        return buf;
763
    }
764

    
765
    public Object getData(int x, int y, int band) throws InvalidSetViewException, FileNotOpenException,
766
        RasterDriverException {
767
        if (x < 0 || y < 0 || x >= file.width || y >= file.height)
768
            throw new InvalidSetViewException("Request out of grid");
769

    
770
        Point2D begin = new Point2D.Double(x, y);
771
        Point2D end = new Point2D.Double(x + 1, y + 1);
772

    
773
        ownTransformation.transform(begin, begin);
774
        ownTransformation.transform(end, end);
775

    
776
        int[] readBandsFromECW = new int[file.numBands];
777
        if (file.numBands <= 3) {
778
            for (int i = 0; i < file.numBands; i++)
779
                readBandsFromECW[i] = i;
780
        } else {
781
            readBandsFromECW[0] = band;
782
        }
783

    
784
        Extent e = new ExtentImpl(begin.getX(), begin.getY(), end.getX(), end.getY());
785
        try {
786
            int[] value = new int[1];
787
            file.setView(file.numBands, readBandsFromECW, e.minX(), e.maxY(), e.maxX(), e.minY(), 1, 1);
788
            file.readLineRGBA(value);
789
            if (file.numBands <= 3) {
790
                switch (band) {
791
                case 0:
792
                    return new Integer((((value[0] & 0x00ff0000) >> 16) & 0xffffffff));
793
                case 1:
794
                    return new Integer((((value[0] & 0x0000ff00) >> 8) & 0xffffffff));
795
                case 2:
796
                    return new Integer((((value[0] & 0x000000ff)) & 0xffffffff));
797
                }
798
            }
799
            return new Integer((((value[0] & 0x00ff0000) >> 16) & 0xffffffff));
800
        } catch (JNCSFileNotOpenException e1) {
801
            throw new FileNotOpenException("Error en jecw: JNCSFileNotOpenException");
802
        } catch (JNCSInvalidSetViewException e1) {
803
            throw new FileNotOpenException("Error en jecw: JNCSInvalidSetViewException");
804
        } catch (JNCSException e1) {
805
            throw new RasterDriverException("Error reading ecw data");
806
        }
807
    }
808

    
809
    public void refreshUpdate(int arg0, int arg1, double arg2, double arg3, double arg4, double arg5) {
810
    }
811

    
812
    public void refreshUpdate(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) {
813
    }
814

    
815
    public DataStoreColorInterpretation getColorInterpretation() {
816
        if (colorInterpr == null) {
817
            colorInterpr = new DataStoreColorInterpretation();
818
            colorInterpr.initColorInterpretation(getBandCount());
819
            if (getBandCount() == 1)
820
                colorInterpr = DataStoreColorInterpretation.createGrayInterpretation();
821
            if (getBandCount() == 3) {
822
                colorInterpr = DataStoreColorInterpretation.createRGBInterpretation();
823
            }
824
            if (getBandCount() >= 4) {
825
                colorInterpr = DataStoreColorInterpretation.createRGBAInterpretation();
826
            }
827
        }
828
        return colorInterpr;
829
    }
830

    
831
    public int getOverviewCount(int band) throws BandAccessException, RasterDriverException {
832
        if (band >= getBandCount())
833
            throw new BandAccessException("Wrong band");
834
        return 0;
835
    }
836

    
837
    public int getOverviewWidth(int band, int overview) throws BandAccessException, RasterDriverException {
838
        if (band >= getBandCount())
839
            throw new BandAccessException("Wrong band");
840
        return 0;
841
    }
842

    
843
    public int getOverviewHeight(int band, int overview) throws BandAccessException, RasterDriverException {
844
        if (band >= getBandCount())
845
            throw new BandAccessException("Wrong band");
846
        return 0;
847
    }
848

    
849
    public boolean isOverviewsSupported() {
850
        return false;
851
    }
852

    
853
    public String getStringProjection() throws RasterDriverException {
854
        return file.projection;
855
    }
856

    
857
    public String getWktProjection() {
858
        return null;
859
    }
860

    
861
    public String getProviderName() {
862
        return NAME;
863
    }
864

    
865
    public void setStatus(RasterProvider provider) {
866
        if (provider instanceof ErmapperProvider) {
867
            // Not implemented yet
868
        }
869
    }
870

    
871
    public boolean isSupersamplingSupported() {
872
        return false;
873
    }
874

    
875
    public TileServer getTileServer() {
876
        if (tileServer == null) {
877
            DefaultRasterStore store = new DefaultRasterStore();
878
            store.setProvider(this);
879
            tileServer = new FileTileServer(store);
880
        }
881
        return tileServer;
882
    }
883

    
884
    public void addFile(File file) throws InvalidSourceException {
885
        // Do nothing
886
    }
887

    
888
    public void removeFile(File file) {
889
        // Do nothing
890
    }
891

    
892
}