Revision 9249

View differences:

org.gvsig.raster.ermapper/tags/org.gvsig.raster.ermapper-2.2.75/org.gvsig.raster.ermapper.io/src/test/java/org/gvsig/raster/ermapper/io/CoordTransformTest.java
1
package org.gvsig.raster.ermapper.io;
2

  
3
import java.awt.geom.AffineTransform;
4
import java.awt.geom.NoninvertibleTransformException;
5
import java.awt.geom.Point2D;
6

  
7
public class CoordTransformTest {
8
	//ul:100, 200  lr:300, 0     pxul: 0, 0  pxlr: 100, 100
9
	private AffineTransform at1 = new AffineTransform(2, 0, 0, -2, 100, 200);
10
	
11
	//ul:3000, 3400  lr:3400, 3000     pxul: 0, 0  pxlr: 100, 100
12
	private AffineTransform at2 = new AffineTransform(4, 0, 0, -4, 3000, 3400);
13
	
14
	public CoordTransformTest() {
15
		//************************************************************
16
		System.out.println("Coord Px to World AT1");
17
		Point2D p1 = new Point2D.Double(0, 0);
18
		Point2D p2 = new Point2D.Double();
19
		at1.transform(p1, p2);
20
		System.out.println("Px: " + p1.toString() + ", World: " +  p2.toString());
21
		
22
		p1 = new Point2D.Double(100, 100);
23
		p2 = new Point2D.Double();
24
		at1.transform(p1, p2);
25
		System.out.println("Px: " + p1.toString() + ", World: " +  p2.toString());
26

  
27
		System.out.println("Coord Px to World AT2");
28
		p1 = new Point2D.Double(0, 0);
29
		p2 = new Point2D.Double();
30
		at2.transform(p1, p2);
31
		System.out.println("Px: " + p1.toString() + ", World: " +  p2.toString());
32
		
33
		p1 = new Point2D.Double(100, 100);
34
		p2 = new Point2D.Double();
35
		at2.transform(p1, p2);
36
		System.out.println("Px: " + p1.toString() + ", World: " +  p2.toString());
37

  
38
		//************************************************************
39
		System.out.println("Coord World to Px AT1");
40
		p1 = new Point2D.Double(100, 200);
41
		p2 = new Point2D.Double();
42
		try {
43
			at1.inverseTransform(p1, p2);
44
		} catch (NoninvertibleTransformException e) {
45
			e.printStackTrace();
46
		}
47
		System.out.println("Px: " + p1.toString() + ", World: " +  p2.toString());
48

  
49
		p1 = new Point2D.Double(300, 0);
50
		p2 = new Point2D.Double();
51
		try {
52
			at1.inverseTransform(p1, p2);
53
		} catch (NoninvertibleTransformException e) {
54
			e.printStackTrace();
55
		}
56
		System.out.println("Px: " + p1.toString() + ", World: " +  p2.toString());
57

  
58
		System.out.println("Coord World to Px AT2");
59
		p1 = new Point2D.Double(3000, 3400);
60
		p2 = new Point2D.Double();
61
		try {
62
			at2.inverseTransform(p1, p2);
63
		} catch (NoninvertibleTransformException e) {
64
			e.printStackTrace();
65
		}
66
		System.out.println("Px: " + p1.toString() + ", World: " +  p2.toString());
67

  
68
		p1 = new Point2D.Double(3400, 3000);
69
		p2 = new Point2D.Double();
70
		try {
71
			at2.inverseTransform(p1, p2);
72
		} catch (NoninvertibleTransformException e) {
73
			e.printStackTrace();
74
		}
75
		System.out.println("Px: " + p1.toString() + ", World: " +  p2.toString());
76

  
77
		//**************************************************************
78

  
79
		System.out.println("-----Window 1 -> Window 2");
80
		//100, 200 -> 3000, 3400
81
		
82
		p1 = new Point2D.Double(100, 200);
83
		p2 = new Point2D.Double();
84
		try {
85
			at1.inverseTransform(p1, p2);
86
		} catch (NoninvertibleTransformException e) {
87
			e.printStackTrace();
88
		}
89
		at2.transform(p2, p2);
90
		System.out.println("Px:" + p1.toString() + ", To " +  p2.toString());
91
	}
92
	
93
	public static void main(String[] args) {
94
		new CoordTransformTest();
95
	}
96

  
97
}
0 98

  
org.gvsig.raster.ermapper/tags/org.gvsig.raster.ermapper-2.2.75/org.gvsig.raster.ermapper.io/src/main/java/org/gvsig/raster/ermapper/io/ErmapperProvider.java
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
        String absolutePath = new File(getURIOfFirstProvider()).getAbsolutePath();
465
        for (int line = 0; line < rasterBuf.getHeight(); line++) {
466
            try {
467
                file.readLineRGBA(pRGBArray);
468
                for (int col = 0; col < pRGBArray.length; col++) {
469
                    drawableBands = bandList.getBufferBandToDraw(absolutePath, 0);
470
                    if (drawableBands != null) {
471
                        for (int i = 0; i < drawableBands.length; i++) {
472
                            if (drawableBands[i] != -1)
473
                                rasterBuf.setElem(line, col, drawableBands[i],
474
                                    (byte) ((pRGBArray[col] & 0x00ff0000) >> 16));
475
                        }
476
                    }
477
                    drawableBands = bandList.getBufferBandToDraw(absolutePath, 1);
478
                    if (drawableBands != null) {
479
                        for (int i = 0; i < drawableBands.length; i++) {
480
                            if (drawableBands[i] != -1)
481
                                rasterBuf.setElem(line, col, drawableBands[i],
482
                                    (byte) ((pRGBArray[col] & 0x0000ff00) >> 8));
483
                        }
484
                    }
485
                    drawableBands = bandList.getBufferBandToDraw(absolutePath, 2);
486
                    if (drawableBands != null) {
487
                        for (int i = 0; i < drawableBands.length; i++) {
488
                            if (drawableBands[i] != -1)
489
                                rasterBuf.setElem(line, col, drawableBands[i], (byte) (pRGBArray[col] & 0x000000ff));
490
                        }
491
                    }
492
                }
493
            } catch (JNCSException exc) {
494
            }
495
            if (task.getEvent() != null)
496
                task.manageEvent(task.getEvent());
497
            if (status != null && status.isCancelled())
498
                return;
499
        }
500
        return;
501
    }
502

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

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

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

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

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

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

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

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

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

  
629
    }
630

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

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

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

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

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

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

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

  
698
        return null;
699
    }
700

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

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

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

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

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

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

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

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

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

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

  
763
        return buf;
764
    }
765

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  
893
}
0 894

  
org.gvsig.raster.ermapper/tags/org.gvsig.raster.ermapper-2.2.75/org.gvsig.raster.ermapper.io/src/main/java/org/gvsig/raster/ermapper/io/ErmapperNewRasterStoreParameters.java
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 org.gvsig.raster.impl.store.AbstractNewRasterStoreParameters;
25

  
26
/**
27
 * Parameters for creating a Ermapper store
28
 * @author Nacho Brodin (nachobrodin@gmail.com)
29
 */
30
public class ErmapperNewRasterStoreParameters extends AbstractNewRasterStoreParameters {
31

  
32
	public String getDataStoreName() {
33
		return ErmapperProvider.NAME;
34
	}
35

  
36
	public String getDescription() {
37
		return ErmapperProvider.DESCRIPTION;
38
	}
39

  
40
}
41

  
0 42

  
org.gvsig.raster.ermapper/tags/org.gvsig.raster.ermapper-2.2.75/org.gvsig.raster.ermapper.io/src/main/java/org/gvsig/raster/ermapper/io/ErmapperFilesystemServerExplorer.java
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

  
23
/*
24
* AUTHORS (In addition to CIT):
25
* 2009 IVER T.I   {{Task}}
26
*/
27

  
28
package org.gvsig.raster.ermapper.io;
29

  
30
import java.awt.geom.AffineTransform;
31
import java.io.File;
32
import java.io.IOException;
33

  
34
import org.gvsig.fmap.dal.DALLocator;
35
import org.gvsig.fmap.dal.DataManager;
36
import org.gvsig.fmap.dal.DataServerExplorer;
37
import org.gvsig.fmap.dal.DataStoreParameters;
38
import org.gvsig.fmap.dal.NewDataStoreParameters;
39
import org.gvsig.fmap.dal.coverage.RasterLocator;
40
import org.gvsig.fmap.dal.coverage.datastruct.Params;
41
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
42
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
43
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
44
import org.gvsig.fmap.dal.coverage.store.DataServerWriter;
45
import org.gvsig.fmap.dal.coverage.store.RasterWriter;
46
import org.gvsig.fmap.dal.coverage.store.parameter.NewRasterStoreParameters;
47
import org.gvsig.fmap.dal.exception.CreateException;
48
import org.gvsig.fmap.dal.exception.DataException;
49
import org.gvsig.fmap.dal.exception.RemoveException;
50
import org.gvsig.fmap.dal.serverexplorer.filesystem.impl.AbstractFilesystemServerExplorerProvider;
51
import org.gvsig.fmap.dal.serverexplorer.filesystem.spi.FilesystemServerExplorerProviderServices;
52
import org.gvsig.raster.impl.store.AbstractRasterFileDataParameters;
53
import org.gvsig.tools.locator.LocatorException;
54

  
55
public class ErmapperFilesystemServerExplorer extends AbstractFilesystemServerExplorerProvider {
56
	
57
	/*
58
	 * (non-Javadoc)
59
	 * @see org.gvsig.fmap.dal.serverexplorer.filesystem.spi.FilesystemServerExplorerProvider#canCreate()
60
	 */
61
	public boolean canCreate() {
62
		return false;
63
	}
64

  
65
	/*
66
	 * (non-Javadoc)
67
	 * @see org.gvsig.fmap.dal.serverexplorer.filesystem.spi.FilesystemServerExplorerProvider#canCreate(org.gvsig.fmap.dal.NewDataStoreParameters)
68
	 */
69
	public boolean canCreate(NewDataStoreParameters parameters) {
70
		return false;
71
	}
72

  
73
	/*
74
	 * (non-Javadoc)
75
	 * @see org.gvsig.fmap.dal.serverexplorer.filesystem.spi.FilesystemServerExplorerProvider#create(org.gvsig.fmap.dal.NewDataStoreParameters, boolean)
76
	 */
77
	public void create(NewDataStoreParameters parameters, boolean overwrite)
78
			throws CreateException {
79
		NewRasterStoreParameters p = null;
80
		if(parameters instanceof NewRasterStoreParameters)
81
			 p = (NewRasterStoreParameters)parameters;
82
		
83
		DataServerWriter dataWriter = p.getDataServer();
84
		if(dataWriter == null)
85
			dataWriter = RasterLocator.getManager().createDataServerWriter();
86
		dataWriter.setBuffer(p.getBuffer(), p.getBand());
87
		Params params;
88
		try {
89
			if(p.getDriverParams() != null)
90
				params = p.getDriverParams();
91
			else
92
				params = RasterLocator.getManager().createWriter(p.getFileName()).getParams();
93
			
94
			AffineTransform affineTransform = p.getAffineTransform();
95
			if(affineTransform == null) {
96
				if(p.getBuffer().getDataExtent() != null) {
97
					double x = p.getBuffer().getDataExtent().getMinX();
98
					double y = p.getBuffer().getDataExtent().getMaxY();
99
					double pixelSizeX = p.getBuffer().getDataExtent().getWidth() / p.getBuffer().getWidth();
100
					double pixelSizeY = p.getBuffer().getDataExtent().getHeight() / p.getBuffer().getHeight();
101
					affineTransform = new AffineTransform(pixelSizeX, 0, 0, pixelSizeY, x, y);
102
				} else {
103
					affineTransform = new AffineTransform();
104
				}
105
			}
106
			
107
			RasterWriter writer = RasterLocator.getManager().createWriter(
108
					dataWriter, 
109
					p.getPath() + File.separator + p.getFileName(),
110
					p.getBand() < 0 ? p.getBuffer().getBandCount() : 1,  
111
					affineTransform, 
112
					p.getBuffer().getWidth(),
113
					p.getBuffer().getHeight(), 
114
					p.getBuffer().getDataType(), 
115
					params, 
116
					null);
117
			if(p.getColorInterpretation() != null)
118
				writer.setColorBandsInterpretation(p.getColorInterpretation());
119
			writer.setWkt(p.getWktProjection());
120
			
121
			writer.dataWrite();
122
			writer.writeClose();
123
		} catch (LocatorException e) {
124
			throw new CreateException("", e);
125
		} catch (NotSupportedExtensionException e) {
126
			throw new CreateException("", e);
127
		} catch (RasterDriverException e) {
128
			throw new CreateException("", e);
129
		} catch (ProcessInterruptedException e) {
130
			//Fin del proceso
131
		} catch (IOException e) {
132
			throw new CreateException("", e);
133
		}
134
	}
135

  
136
	/*
137
	 * (non-Javadoc)
138
	 * @see org.gvsig.fmap.dal.serverexplorer.filesystem.spi.FilesystemServerExplorerProvider#getCreateParameters()
139
	 */
140
	public NewDataStoreParameters getCreateParameters() throws DataException {
141
		return new ErmapperNewRasterStoreParameters();
142
	}
143

  
144
	/*
145
	 * (non-Javadoc)
146
	 * @see org.gvsig.fmap.dal.serverexplorer.filesystem.spi.FilesystemServerExplorerProvider#initialize(org.gvsig.fmap.dal.serverexplorer.filesystem.spi.FilesystemServerExplorerProviderServices)
147
	 */
148
	public void initialize(
149
			FilesystemServerExplorerProviderServices serverExplorer) {
150
	}
151
	
152
	/*
153
	 * (non-Javadoc)
154
	 * @see org.gvsig.fmap.dal.serverexplorer.filesystem.spi.FilesystemServerExplorerProvider#remove(org.gvsig.fmap.dal.DataStoreParameters)
155
	 */
156
	public void remove(DataStoreParameters parameters) throws RemoveException {
157
		throw new UnsupportedOperationException();
158
	}
159

  
160
	/*
161
	 * (non-Javadoc)
162
	 * @see org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemFileFilter#getDataStoreProviderName()
163
	 */
164
	public String getDataStoreProviderName() {
165
		return ErmapperProvider.NAME;
166
	}
167

  
168
	/*
169
	 * (non-Javadoc)
170
	 * @see java.io.FileFilter#accept(java.io.File)
171
	 */
172
	public boolean accept(File pathname) {
173
		return RasterLocator.getManager().getProviderServices().isExtensionSupported(
174
				pathname.getAbsolutePath(), 
175
				ErmapperProvider.class);
176
	}
177

  
178
	/*
179
	 * (non-Javadoc)
180
	 * @see org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemFileFilter#getDescription()
181
	 */
182
	public String getDescription() {
183
		return ErmapperProvider.DESCRIPTION;
184
	}
185

  
186
	public DataStoreParameters getParameters(File file) throws DataException {
187
		DataManager manager = DALLocator.getDataManager();
188
		AbstractRasterFileDataParameters params = (AbstractRasterFileDataParameters) manager
189
				.createStoreParameters(this.getDataStoreProviderName());
190
		params.setFile(file);
191
		return params;
192
	}
193

  
194
	public int getMode() {
195
		return DataServerExplorer.MODE_RASTER;
196
	}
197
}
0 198

  
org.gvsig.raster.ermapper/tags/org.gvsig.raster.ermapper-2.2.75/org.gvsig.raster.ermapper.io/src/main/java/org/gvsig/raster/ermapper/io/ErmapperWriter.java
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.File;
27
import java.io.IOException;
28

  
29
import org.cresques.cts.IProjection;
30
import org.gvsig.fmap.dal.coverage.RasterLibrary;
31
import org.gvsig.fmap.dal.coverage.RasterLocator;
32
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
33
import org.gvsig.fmap.dal.coverage.datastruct.Params;
34
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
35
import org.gvsig.fmap.dal.coverage.process.CancelEvent;
36
import org.gvsig.fmap.dal.coverage.process.TaskEventManager;
37
import org.gvsig.fmap.dal.coverage.store.DataServerWriter;
38
import org.gvsig.fmap.dal.coverage.store.ExternalCancellable;
39
import org.gvsig.raster.impl.store.ParamImpl;
40
import org.gvsig.raster.impl.store.WriteFileFormatFeatures;
41
import org.gvsig.raster.impl.store.writer.DefaultRasterWriter;
42
import org.gvsig.raster.util.DefaultProviderServices;
43
import org.gvsig.tools.ToolsLocator;
44
import org.gvsig.tools.extensionpoint.ExtensionPoint;
45
import org.gvsig.tools.extensionpoint.ExtensionPointManager;
46

  
47
import es.gva.cit.jecwcompress.EcwException;
48
import es.gva.cit.jecwcompress.JniObject;
49
import es.gva.cit.jecwcompress.NCSEcwCompressClient;
50
import es.gva.cit.jecwcompress.ReadCallBack;
51
/**
52
 * Driver para la compresi?n en formato Ecw.
53
 *
54
 * Puede exportar un fichero desde un GeoRasterFile en cualquier formato soportado
55
 * por los drivers de lectura a uno en formato Ecw.
56
 *
57
 * Puede salvar a disco en formato Ecw obteniendo los datos que van siendo servidos
58
 * desde el cliente. Este cliente debe implementar un DataServerWriter o tener un objeto
59
 * que lo implemente. Inicialmente le pasar? los par?metros de la imagen de salida
60
 * y cuando el driver comience a escribir le ir? solicitando m?s a trav?s del m?todo
61
 * readData de DataServerWriter. El cliente ser? el que lleve el control de lo que va
62
 * sirviendo y lo que le queda por servir.
63
 * @author Nacho Brodin (brodin_ign@gva.es)
64
 */
65
public class ErmapperWriter extends DefaultRasterWriter {
66

  
67
	public static void register() {
68
		DefaultProviderServices pInfo = (DefaultProviderServices)RasterLocator.getManager().getProviderServices();
69
		ExtensionPointManager extensionPoints = ToolsLocator.getExtensionPointManager();
70
		ExtensionPoint point = extensionPoints.get("RasterWriter");
71
		WriteFileFormatFeatures features = null;
72

  
73
		String os = System.getProperties().getProperty("os.version");
74
		if (os.startsWith("2.4")){
75
			point.append("ecw", "", ErmapperWriter.class);
76
			features = new WriteFileFormatFeatures("Ecw", "ecw", new int[]{3}, null, ErmapperWriter.class);
77
			pInfo.getFileFeature().put("ecw", features);
78
		}
79
		point.append("jp2", "", ErmapperWriter.class);
80
		features = new WriteFileFormatFeatures("Jpeg2000", "jp2", new int[]{3}, null, ErmapperWriter.class);
81
		pInfo.getFileFeature().put("jp2", features);
82
	}
83

  
84
	public final int 				windowSizeX = 386;
85
	public final int 				windowSizeY = 220;
86
	public final int 				panelSizeX = 358;
87
	public final int 				panelSizeY = 125;
88
	public final String 			panelLayout = "BorderLayout";
89
	private NCSEcwCompressClient 	compressclient = null;
90
	private Reader 					readerObj;
91
	private double 					pixelSizeX;
92
	private double 					pixelSizeY;
93
	private double 					geoCoordOrigenX;
94
	private double 					geoCoordOrigenY;
95
	private boolean 				consulta = false;
96

  
97
	/**
98
	 * Carga los par?metros de este driver.
99
	 */
100
	public void loadParams() {
101
		WriteFileFormatFeatures wfff = new WriteFileFormatFeatures();
102
		wfff.loadParams();
103
		driverParams = wfff.getParams();
104

  
105
		driverParams.setParam(	"compression",
106
				new Integer(10),
107
				Params.SLIDER,
108
				new String[]{ "1", "20", "10", "1", "5" }); //min, max, valor defecto, intervalo peque?o, intervalo grande;
109

  
110
		driverParams.setParam(	"format",
111
				new Integer(4),
112
				Params.CHOICE,
113
				new String[]{ "NONE", "UINT8", "YUV", "MULTI", "RGB"});
114
	}
115
	
116
	/*
117
	 * (non-Javadoc)
118
	 * @see org.gvsig.fmap.dal.coverage.store.RasterWriter#getProviderName()
119
	 */
120
	public String getProviderName() {
121
		return ErmapperProvider.NAME;
122
	}
123

  
124
	/**
125
	 * Constructor para la obtenci?n de par?metros del driver.
126
	 */
127
	public ErmapperWriter(String fileName) {
128
		DefaultProviderServices pInfo = (DefaultProviderServices)RasterLocator.getManager().getProviderServices();
129
		ident = fileUtil.getExtensionFromFileName(fileName);
130
		driver = ((WriteFileFormatFeatures)pInfo.getFileFeature().get(ident)).getDriverName();
131

  
132
		loadParams();
133

  
134
		consulta = true;
135
	}
136

  
137
	/**
138
	 * Constructor para la lectura de datos desde el objeto cliente a partir de un
139
	 * viewport dado.
140
	 * @param dataWriter Objeto que sirve datos para el escritor
141
	 * @param outFileName Fichero de salida
142
	 * @param nBands N?mero de bandas
143
	 * @param at
144
	 * @param outSizeX
145
	 * @param outSizeY
146
	 * @param dataType
147
	 * @param params
148
	 * @param proj
149
	 * @param geo
150
	 * @throws EcwException
151
	 * @throws IOException
152
	 */
153
	public ErmapperWriter(	DataServerWriter dataWriter,
154
			String outFileName,
155
			Integer nBands,
156
			AffineTransform at,
157
			Integer outSizeX,
158
			Integer outSizeY,
159
			Integer dataType,
160
			Params params,
161
			IProjection proj,
162
			Boolean geo) throws EcwException, IOException {
163
		DefaultProviderServices pInfo = (DefaultProviderServices)RasterLocator.getManager().getProviderServices();
164
		//La libreria de ECW no se traga caracteres raros al escribir. Los cambiamos por X de momento y ya se apa?a el usuario
165

  
166
		String ext = fileUtil.getExtensionFromFileName(outFileName);
167
		String fname = outFileName.substring(outFileName.lastIndexOf(File.separator) + 1, outFileName.lastIndexOf(".")).replaceAll("[^a-zA-Z0-9_]", "X");
168
		outFileName = outFileName.substring(0, outFileName.lastIndexOf(File.separator) + 1) + fname + "." + ext;
169

  
170
		this.proj = proj;
171
		ident = fileUtil.getExtensionFromFileName(outFileName);
172
		driver = ((WriteFileFormatFeatures)pInfo.getFileFeature().get(ident)).getDriverName();
173
		this.dataType = dataType.intValue();
174

  
175
		if (nBands.intValue() <= 0)
176
			throw new EcwException("N?mero de bandas erroneo.");
177

  
178
		this.outFileName = outFileName;
179
		this.dataWriter = dataWriter;
180

  
181
		this.nBands = nBands.intValue();
182

  
183
		this.sizeWindowX = outSizeX.intValue();
184
		this.sizeWindowY = outSizeY.intValue();
185

  
186
		//Calculamos la georeferenciaci?n a partir del extend pasado por el cliente.
187
		geoCoordOrigenX = at.getTranslateX();
188
		geoCoordOrigenY = at.getTranslateY();
189

  
190
		pixelSizeX = (at.getScaleX() > 0) ? at.getScaleX() : -at.getScaleX();
191
		pixelSizeY = (at.getScaleY() < 0) ? at.getScaleY() : -at.getScaleY();
192

  
193
		String outRmf = fileUtil.getNameWithoutExtension(outFileName);
194
		if(geo.booleanValue())
195
			rasterUtil.saveGeoInfo(outRmf, at, new Point2D.Double(sizeWindowX, sizeWindowY));
196

  
197
		if (pixelSizeX == 0)
198
			pixelSizeX = 1.0;
199

  
200
		if (pixelSizeY == 0)
201
			pixelSizeY = 1.0;
202

  
203
		if(params == null)
204
			loadParams();
205
		else
206
			driverParams = params;
207

  
208
		init();
209
	}
210

  
211
	/**
212
	 * Inicializaci?n de los par?metros del compresor que ser?n obtenidos
213
	 * de PxRaster.
214
	 * @throws EcwException
215
	 */
216
	private void init() throws EcwException {
217
		percent = 0;
218
		int comp = ((Integer)(((ParamImpl)driverParams.getParamById("compression"))).getDefaultValue()).intValue();
219
		ParamImpl param = (ParamImpl)driverParams.getParamById("format");
220
		String format = param.getList()[((Integer)param.getDefaultValue()).intValue()];
221
		if ( comp == 0 )
222
			driverParams.changeParamValue("compression", "1");
223

  
224
		if (compressclient == null)
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff