Revision 3260

View differences:

org.gvsig.raster.ermapper/tags/org.gvsig.raster.ermapper-2.2.7/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

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

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

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

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

  
204
		int[] dt = new int[bandCount];
205
		for (int i = 0; i < bandCount; i++)
206
			dt[i] = Buffer.TYPE_BYTE;
207
		setDataType(dt);
208

  
209
		super.init();
210

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

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

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

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

  
271
	public Transparency getTransparency() {
272
		if(fileTransparency == null)
273
			fileTransparency = new DataStoreTransparency(getColorInterpretation());
274
		return fileTransparency;
275
	}
276

  
277
	public double getWidth() {
278
		return file.width;
279
	}
280

  
281
	public double getHeight() {
282
		return file.height;
283
	}
284

  
285
	public Extent getView() {
286
		return viewRequest;
287
	}
288

  
289
	public void setView(Extent e) {
290
		viewRequest = new ExtentImpl(e);
291
	}
292
	
293
	@Override
294
	public void loadBuffer(SpiRasterQuery query)
295
			throws ProcessInterruptedException, RasterDriverException {
296
		setView(transformExternalGeorefToOwnGeoref(query.getAdjustedRequestBoundingBox()));
297
		int bufWidth = query.getAdjustedBufWidth();
298
		int bufHeight = query.getAdjustedBufHeight();
299
		int[] stpBuffer = new int[]{0, 0 , bufWidth, bufHeight};
300
		loadBuffer(viewRequest, 
301
				bufWidth, 
302
				bufHeight, 
303
				query.getBufferForProviders(), 
304
				query.getBandList(), 
305
				stpBuffer, 
306
				query.getTaskStatus());
307
	}
308
	
309
	/**
310
	 * Converts coordinates from the external transformation to the own transformation.
311
	 * This is useful when the user assigns a transformation or the own raster has one
312
	 * in the rmf file. Ecw need this function because the data window are requested to 
313
	 * the library in world coordinates.
314
	 * @param ext
315
	 * @return
316
	 */
317
	private Extent transformExternalGeorefToOwnGeoref(Extent ext) {
318
		if(externalTransformation.equals(ownTransformation))
319
			return ext;
320
		
321
		Point2D ul = ext.getUL();
322
		Point2D lr = ext.getLR();
323
		
324
		Point2D p1 = new Point2D.Double();
325
		Point2D p2 = new Point2D.Double();
326
		
327
		try {
328
			externalTransformation.inverseTransform(ul, p1);
329
		} catch (NoninvertibleTransformException e) {
330
			e.printStackTrace();
331
		}
332
		ownTransformation.transform(p1, p1);
333
		
334
		try {
335
			externalTransformation.inverseTransform(lr, p2);
336
		} catch (NoninvertibleTransformException e) {
337
			e.printStackTrace();
338
		}
339
		ownTransformation.transform(p2, p2);
340
		
341
		return RasterLocator.getManager().getDataStructFactory().createExtent(p1, p2);
342
	}
343

  
344
	/**
345
	 * Carga el buffer con las bandas RGB del raster con los par?metros especificados de extensi?n
346
	 * y tama?o de buffer. El problema de ecw es que solo podemos leer 3 bandas de una vez ya que solo disponemos
347
	 * de una llamada readLineRGBA. Para leer m?s bandas tendremos que hacer multiples llamadas a setView para leer
348
	 * 3 cada vez.
349
	 *
350
	 * Si por ejemplo tenemos un ecw de 6 bandas [0, 1, 2, 3, 4, 5] y queremos cargar un buffer con el siguiente orden
351
	 * [0, -, 2, -, 4, -] La variable readBandsFromECW har? la llamada a setView con los valores [0, 2, 4, 0, 0, 0]. La
352
	 * funci?n drawRGB ser? la encargada de hacer el switch para obtener [0, -, 2, -, 4, -].
353
	 *
354
	 * Bug#1: Si se dispone de un ecw de m?s de tres bandas podemos llamar a setView con readBandsFromECW con el orden
355
	 * que queramos, por ejemplo [3, 2, 5, 1, 0] pero para ecw de 3 bandas la llamada con las bandas cambiadas no
356
	 * hace caso. El caso de readBandsFromECW = [2, 0, 1] ser? tomado siempre como [0, 1, 2].
357
	 *
358
	 * @param selectedExtent Extensi?n seleccionada
359
	 * @param bufWidth Ancho de buffer
360
	 * @param bufHeight Alto de buffer
361
	 * @param rasterBuf Buffer de datos
362
	 */
363
	private void loadBuffer(Extent selectedExtent, 
364
			int bufWidth, 
365
			int bufHeight, 
366
			Buffer rasterBuf, 
367
			BandList bandList, 
368
			int[] stpBuffer,
369
			TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
370
		try {
371
			RasterTask task = RasterTaskQueue.get(Thread.currentThread().getId() + "");
372
			
373
			int[] readBandsFromECW = new int[Math.max(file.numBands, 3)];
374
			
375
			for(int i = 0; i < readBandsFromECW.length; i ++) {
376
				readBandsFromECW[i] = i;
377
			}
378

  
379
			if(task.getEvent() != null)
380
				task.manageEvent(task.getEvent());
381
			if(status != null && status.isCancelled())
382
				return;
383

  
384
			if(bufWidth > Math.round(Math.abs(selectedExtent.width() / file.cellIncrementX)))
385
				bufWidth = (int)Math.round(Math.abs(selectedExtent.width() / file.cellIncrementX));
386
			if(bufHeight > Math.round(Math.abs(selectedExtent.height() / file.cellIncrementY)))
387
				bufHeight = (int)Math.round(Math.abs(selectedExtent.height() / file.cellIncrementY));
388
			file.setView(file.numBands, readBandsFromECW, selectedExtent.minX(), selectedExtent.maxY(), selectedExtent.maxX(), selectedExtent.minY(), bufWidth, bufHeight);
389
			
390
			//Escribimos el raster sobre un Buffer
391
			int[] pRGBArray = new int[bufWidth];
392
			drawRGB2(rasterBuf, pRGBArray, bandList, status);
393

  
394
		}catch(JNCSInvalidSetViewException exc){
395
			throw new RasterDriverException("Error setting coords");
396
		}catch (JNCSFileNotOpenException e) {
397
			throw new RasterDriverException("Error opening file");
398
		}catch (JNCSException ex) {
399
			throw new RasterDriverException("Error reading data");
400
		}
401

  
402
	}
403
	
404
	private void drawRGB2(
405
			Buffer rasterBuf, 
406
			int[] pRGBArray, 
407
			BandList bandList, 
408
			TaskStatus status) throws JNCSException, ProcessInterruptedException {
409
		RasterTask task = RasterTaskQueue.get(Thread.currentThread().getId() + "");
410
		int[] drawableBands = null;
411
		
412
		for (int line = 0; line < rasterBuf.getHeight(); line++) {
413
			try {
414
				file.readLineRGBA(pRGBArray);
415
				for(int col = 0; col < pRGBArray.length; col ++) {
416
					drawableBands = bandList.getBufferBandToDraw(getURIOfFirstProvider(), 0);
417
					if(drawableBands != null) {
418
						for (int i = 0; i < drawableBands.length; i++) {
419
							if(drawableBands[i] != -1)
420
								rasterBuf.setElem(line, col, drawableBands[i], (byte)((pRGBArray[col] & 0x00ff0000) >> 16));							
421
						}
422
					}
423
					drawableBands = bandList.getBufferBandToDraw(getURIOfFirstProvider(), 1);
424
					if(drawableBands != null) {
425
						for (int i = 0; i < drawableBands.length; i++) {
426
							if(drawableBands[i] != -1)
427
								rasterBuf.setElem(line, col, drawableBands[i], (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
428
						}
429
					}
430
					drawableBands = bandList.getBufferBandToDraw(getURIOfFirstProvider(), 2);
431
					if(drawableBands != null) {
432
						for (int i = 0; i < drawableBands.length; i++) {
433
							if(drawableBands[i] != -1)
434
								rasterBuf.setElem(line, col, drawableBands[i], (byte)(pRGBArray[col] & 0x000000ff));
435
						}
436
					}
437
				}
438
			} catch (JNCSException exc) {
439
			}
440
			if(task.getEvent() != null)
441
				task.manageEvent(task.getEvent());
442
			if(status != null && status.isCancelled())
443
				return;
444
		}
445
		return;
446
	}
447

  
448
	@SuppressWarnings("unused")
449
	private void drawRGB(Buffer rasterBuf, int[] pRGBArray, int[] readBands, BandList bandList, RasterTask task) throws JNCSException, ProcessInterruptedException {
450
		int bandR = readBands[0];
451
		int bandG = (readBands.length > 1) ? readBands[1] : -1;
452
		int bandB = (readBands.length > 2) ? readBands[2] : -1;
453

  
454
		//********* caso especial que resuelve Bug#1 **********************
455
		if(file.numBands == 3 && bandList.getDrawableBandsCount() < 3) {
456
			for(int i = 0; i < 3; i ++) {
457
				int[] b = bandList.getBand(i).getBufferBandListToDraw();
458
				if(b != null){
459
					bandG = 1; bandR = 0; bandB = 2;
460
				}
461
			}
462
		}
463
		if(file.numBands == 3 && bandR == bandG && bandG == bandB) { //caso especial que resuelve Bug#1
464
			for(int i = 0; i < 3; i ++) {
465
				int[] b = bandList.getBand(i).getBufferBandListToDraw();
466
				if(b != null) {
467
					if(i == 0) {
468
						for (int line = 0; line < rasterBuf.getHeight(); line++) {
469
							try {
470
								file.readLineRGBA(pRGBArray);
471
								for(int col = 0; col < pRGBArray.length; col ++) {
472
									rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
473
									rasterBuf.setElem(line, col, bandG, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
474
									rasterBuf.setElem(line, col, bandB, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
475
								}
476
							} catch (JNCSException exc) {
477
							}
478
						}
479
						return;
480
					}
481
					if(i == 1) {
482
						for (int line = 0; line < rasterBuf.getHeight(); line++) {
483
							try {
484
								file.readLineRGBA(pRGBArray);
485
								for(int col = 0; col < pRGBArray.length; col ++) {
486
									rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
487
									rasterBuf.setElem(line, col, bandG, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
488
									rasterBuf.setElem(line, col, bandB, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
489
								}
490
							} catch (JNCSException exc) {
491
							}
492
						}
493
						return;
494
					}
495
					if(i == 2) {
496
						for (int line = 0; line < rasterBuf.getHeight(); line++) {
497
							try {
498
								file.readLineRGBA(pRGBArray);
499
								for(int col = 0; col < pRGBArray.length; col ++) {
500
									rasterBuf.setElem(line, col, bandR, (byte)(pRGBArray[col] & 0x000000ff));
501
									rasterBuf.setElem(line, col, bandG, (byte)(pRGBArray[col] & 0x000000ff));
502
									rasterBuf.setElem(line, col, bandB, (byte)(pRGBArray[col] & 0x000000ff));
503
								}
504
							} catch (JNCSException exc) {
505
							}
506
						}
507
						return;
508
					}
509
				}
510
				if(task.getEvent() != null)
511
					task.manageEvent(task.getEvent());
512
			}
513

  
514
		}
515
		//********* END caso especial que resuelve Bug#1 **********************
516

  
517
		if(bandR >= 0 && bandG >= 0 && bandB >= 0) {
518
			for (int line = 0; line < rasterBuf.getHeight(); line++) {
519
				try {
520
					file.readLineRGBA(pRGBArray);
521
					for(int col = 0; col < pRGBArray.length; col ++) {
522
						rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
523
						rasterBuf.setElem(line, col, bandG, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
524
						rasterBuf.setElem(line, col, bandB, (byte)(pRGBArray[col] & 0x000000ff));
525
					}
526
				} catch (JNCSException exc) {
527
				}
528
			}
529
			return;
530
		}
531

  
532
		if(task.getEvent() != null)
533
			task.manageEvent(task.getEvent());
534

  
535
		if(bandR >= 0 && bandG >= 0) {
536
			for (int line = 0; line < rasterBuf.getHeight(); line++) {
537
				try {
538
					file.readLineRGBA(pRGBArray);
539
					for(int col = 0; col < pRGBArray.length; col ++) {
540
						rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
541
						rasterBuf.setElem(line, col, bandG, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
542
					}
543
				} catch (JNCSException exc) {
544
				}
545
			}
546
			return;
547
		}
548

  
549
		if(task.getEvent() != null)
550
			task.manageEvent(task.getEvent());
551

  
552
		if(bandR >= 0){
553
			for (int line = 0; line < rasterBuf.getHeight(); line++) {
554
				try {
555
					file.readLineRGBA(pRGBArray);
556
					for(int col = 0; col < pRGBArray.length; col ++)
557
						rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
558
				} catch (JNCSException exc) {
559
				}
560
			}
561
			return;
562
		}
563

  
564
		if(task.getEvent() != null)
565
			task.manageEvent(task.getEvent());
566

  
567
	}
568

  
569
	public void reProject(ICoordTrans rp) {
570
	}
571

  
572
	public int getBlockSize() {
573
		return 0;
574
	}
575

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

  
580
		Point2D begin = rasterToWorld(new Point2D.Double(0, line));
581
		Point2D end = rasterToWorld(new Point2D.Double(file.width, line + 1));
582
		int[] readBandsFromECW = new int[file.numBands];
583
		if(file.numBands <= 3) {
584
			for(int i = 0; i < file.numBands; i++)
585
				readBandsFromECW[i] = i;
586
		} else {
587
			readBandsFromECW[0] = band;
588
		}
589

  
590
		Extent e = new ExtentImpl(begin.getX(), begin.getY(), end.getX(), end.getY());
591

  
592
		try {
593
			int[] value = new int[file.width];
594
			file.setView(file.numBands, readBandsFromECW, e.minX(), e.maxY(), e.maxX(), e.minY(), file.width, 1);
595
			file.readLineRGBA(value);
596

  
597
			if(file.numBands <= 3) {
598
				switch(getDataType()[0]) {
599
				case Buffer.TYPE_BYTE: byte[] b = new byte[file.width];
600
										switch(band) {
601
										case 0: for(int i = 0; i < file.width; i ++)
602
													b[i] = (byte)(((value[i] & 0x00ff0000) >> 16) & 0xff);
603
												break;
604
										case 1: for(int i = 0; i < file.width; i ++)
605
													b[i] = (byte)(((value[i] & 0x0000ff00) >> 8) & 0xff);
606
												break;
607
										case 2: for(int i = 0; i < file.width; i ++)
608
													b[i] = (byte)((value[i] & 0x000000ff) & 0xff);
609
												break;
610
										}
611
										return b;
612
				}
613
			}else {
614
				switch(getDataType()[0]) {
615
				case Buffer.TYPE_BYTE: byte[] b = new byte[file.width];
616
										for(int i = 0; i < file.width; i ++)
617
											b[i] = (byte)(((value[i] & 0x00ff0000) >> 16) & 0xff);
618
										break;
619
				}
620
			}
621
			//TODO: FUNCIONALIDAD: Ecw con otro tipo de dato != Byte
622
		} catch (JNCSFileNotOpenException e1) {
623
			throw new FileNotOpenException("Error en jecw: JNCSFileNotOpenException");
624
		} catch (JNCSInvalidSetViewException e1) {
625
			throw new FileNotOpenException("Error en jecw: JNCSInvalidSetViewException");
626
		} catch (JNCSException e1) {
627
			throw new RasterDriverException("Error la lectura de datos ecw");
628
		}
629

  
630
		return null;
631
	}
632

  
633
	public Object readBlock(int pos, int blockHeight, double scale) throws InvalidSetViewException, FileNotOpenException, RasterDriverException, ProcessInterruptedException {
634
		RasterTask task = RasterTaskQueue.get(Thread.currentThread().getId() + "");
635
		if(pos < 0)
636
			throw new InvalidSetViewException("Request out of grid");
637

  
638
		if((pos + blockHeight) > file.height)
639
			blockHeight = Math.abs(file.height - pos);
640

  
641
		Point2D begin = rasterToWorld(new Point2D.Double(0, pos));
642
		Point2D end = rasterToWorld(new Point2D.Double(file.width, pos + blockHeight));
643
		int[] readBandsFromECW = new int[file.numBands];
644

  
645
		for(int i = 0; i < file.numBands; i++)
646
			readBandsFromECW[i] = i;
647

  
648
		byte[][][] buf = new byte[file.numBands][blockHeight][file.width];
649
		Extent e = new ExtentImpl(begin.getX(), begin.getY(), end.getX(), end.getY());
650
		e = rasterUtil.calculateAdjustedView(getExtent(), e);
651

  
652
		try {
653
			int[] value = new int[file.width];
654
			file.setView(file.numBands, readBandsFromECW, e.minX(), e.maxY(), e.maxX(), e.minY(), file.width, blockHeight);
655

  
656
			if(file.numBands <= 3) {
657
				for (int row = 0; row < blockHeight; row++) {
658
					file.readLineRGBA(value);
659
					switch(getDataType()[0]) {
660
					case Buffer.TYPE_BYTE:
661
						if(buf.length >= 3) {
662
							for(int col = 0; col < file.width; col ++) {
663
								buf[0][row][col] = (byte)(((value[col] & 0x00ff0000) >> 16) & 0xff);
664
								buf[1][row][col] = (byte)(((value[col] & 0x0000ff00) >> 8) & 0xff);
665
								buf[2][row][col] = (byte)((value[col] & 0x000000ff) & 0xff);
666
							}
667
						} else { //Si es monobanda solo se usa cualquiera uno de los tres valores
668
							for(int col = 0; col < file.width; col ++) {
669
								buf[0][row][col] = (byte)(((value[col] & 0x00ff0000) >> 16) & 0xff);
670
							}
671
						}
672
						break;
673
					}
674
				}
675

  
676
				if(task.getEvent() != null)
677
					task.manageEvent(task.getEvent());
678

  
679
			} else {
680
				//TODO: FUNCIONALIDAD: file.numBands > 3
681
			}
682

  
683
			//TODO: FUNCIONALIDAD: Ecw con otro tipo de dato != Byte
684
		} catch (JNCSFileNotOpenException e1) {
685
			throw new FileNotOpenException("Error en jecw: JNCSFileNotOpenException");
686
		} catch (JNCSInvalidSetViewException e1) {
687
			throw new FileNotOpenException("Error en jecw: JNCSInvalidSetViewException");
688
		} catch (JNCSException e1) {
689
			throw new RasterDriverException("Error la lectura de datos ecw");
690
		}
691

  
692
		return buf;
693
	}
694

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

  
699
		Point2D begin = new Point2D.Double(x, y);
700
		Point2D end = new Point2D.Double(x + 1, y + 1);
701

  
702
		ownTransformation.transform(begin, begin);
703
		ownTransformation.transform(end, end);
704

  
705
		int[] readBandsFromECW = new int[file.numBands];
706
		if(file.numBands <= 3){
707
			for(int i = 0; i < file.numBands; i++)
708
				readBandsFromECW[i] = i;
709
		}else{
710
			readBandsFromECW[0] = band;
711
		}
712

  
713
		Extent e = new ExtentImpl(begin.getX(), begin.getY(), end.getX(), end.getY());
714
		try {
715
			int[] value = new int[1];
716
			file.setView(file.numBands, readBandsFromECW, e.minX(), e.maxY(), e.maxX(), e.minY(), 1, 1);
717
			file.readLineRGBA(value);
718
			if(file.numBands <= 3){
719
				switch(band){
720
				case 0: return new Integer((((value[0] & 0x00ff0000) >> 16) & 0xffffffff));
721
				case 1: return new Integer((((value[0] & 0x0000ff00) >> 8) & 0xffffffff));
722
				case 2: return new Integer((((value[0] & 0x000000ff)) & 0xffffffff));
723
				}
724
			}
725
			return new Integer((((value[0] & 0x00ff0000) >> 16) & 0xffffffff));
726
		} catch (JNCSFileNotOpenException e1) {
727
			throw new FileNotOpenException("Error en jecw: JNCSFileNotOpenException");
728
		} catch (JNCSInvalidSetViewException e1) {
729
			throw new FileNotOpenException("Error en jecw: JNCSInvalidSetViewException");
730
		} catch (JNCSException e1) {
731
			throw new RasterDriverException("Error reading ecw data");
732
		}
733
	}
734

  
735
	public void refreshUpdate(int arg0, int arg1, double arg2, double arg3, double arg4, double arg5) {
736
	}
737

  
738
	public void refreshUpdate(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) {
739
	}
740

  
741
	public DataStoreColorInterpretation getColorInterpretation() {
742
		if(colorInterpr == null) {
743
			colorInterpr = new DataStoreColorInterpretation();
744
			colorInterpr.initColorInterpretation(getBandCount());
745
			if(getBandCount() == 1)
746
				colorInterpr = DataStoreColorInterpretation.createGrayInterpretation();
747
			if(getBandCount() == 3) {
748
				colorInterpr =  DataStoreColorInterpretation.createRGBInterpretation();
749
			}
750
			if(getBandCount() >= 4) {
751
				colorInterpr = DataStoreColorInterpretation.createRGBAInterpretation();
752
			}
753
		}
754
		return colorInterpr;
755
	}
756

  
757
	public int getOverviewCount(int band) throws BandAccessException, RasterDriverException {
758
		if(band >= getBandCount())
759
			throw new BandAccessException("Wrong band");
760
		return 0;
761
	}
762

  
763
	public int getOverviewWidth(int band, int overview) throws BandAccessException, RasterDriverException {
764
		if (band >= getBandCount())
765
			throw new BandAccessException("Wrong band");
766
		return 0;
767
	}
768

  
769
	public int getOverviewHeight(int band, int overview) throws BandAccessException, RasterDriverException {
770
		if (band >= getBandCount())
771
			throw new BandAccessException("Wrong band");
772
		return 0;
773
	}
774

  
775
	public boolean isOverviewsSupported() {
776
		return false;
777
	}
778

  
779
	
780
	public String getStringProjection() throws RasterDriverException{
781
		return file.projection;
782
	}
783

  
784
	public String getWktProjection() {
785
		return null;
786
	}
787
	
788
	public String getProviderName() {
789
		return NAME;
790
	}
791
	
792
	public void setStatus(RasterProvider provider) {
793
		if(provider instanceof ErmapperProvider) {
794
			//Not implemented yet
795
		}
796
	}
797
	
798
	public boolean isSupersamplingSupported() {
799
		return false;
800
	}
801
	
802
	public TileServer getTileServer() {
803
		if(tileServer == null) {
804
			DefaultRasterStore store = new DefaultRasterStore();
805
			store.setProvider(this);
806
			tileServer = new FileTileServer(store);
807
		}
808
		return tileServer;
809
	}
810
}
0 811

  
org.gvsig.raster.ermapper/tags/org.gvsig.raster.ermapper-2.2.7/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.7/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.7/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)
225
			compressclient = new NCSEcwCompressClient();
226

  
227
		compressclient.setOutputFilename(outFileName);
228
		compressclient.setInputFilename(inFileName);
229
		compressclient.setTargetCompress(comp);
230
		compressclient.setInOutSizeX(sizeWindowX);
231
		compressclient.setInOutSizeY(sizeWindowY);
232
		compressclient.setInputBands(nBands);
233
		compressclient.setCompressFormat(convertFormatToInt(format));
234

  
235
		/* boolean georef = new Boolean(((Param)driverParams.getParamById("georef")).defaultValue).booleanValue();
236
				if (georef) {*/
237
		compressclient.setCellIncrementX(pixelSizeX);
238
		compressclient.setCellIncrementY(pixelSizeY);
239
		compressclient.setOriginX(geoCoordOrigenX);
240
		compressclient.setOriginY(geoCoordOrigenY);
241
		//}
242

  
243
		compressclient.setCellSizeUnits(1);
244
		int blocksize = RasterLibrary.blockHeight;
245

  
246
		if (dataWriter != null)
247
			readerObj = new Reader(dataWriter, compressclient, sizeWindowX,
248
					sizeWindowY, blocksize, nBands, this, dataType);
249
	}
250

  
251
	/**
252
	 * Convierte la cadena que representa el formato en un valor n?merico
253
	 * que entiende el driver.
254
	 * @param format Cadena que representa el formato
255
	 * @return Entero que representa a la cadena
256
	 */
257
	private int convertFormatToInt(String format) {
258
		if(format.compareTo("NONE") == 0)
259
			return 0;
260
		if(format.compareTo("UINT8") == 0)
261
			return 1;
262
		if(format.compareTo("YUV") == 0)
263
			return 2;
264
		if(format.compareTo("MULTI") == 0)
265
			return 3;
266
		if(format.compareTo("RGB") == 0)
267
			return 4;
268
		return -1;
269
	}
270
	/**
271
	 * A partir de un elemento que contiene una propiedad y un valor
272
	 * lo parsea y asigna el valor a su variable.
273
	 * @param propValue        elemento con la forma propiedad=valor
274
	 */
275
	private void readProperty(String propValue) {
276
		String prop = propValue.substring(0, propValue.indexOf("="));
277

  
278
		if (propValue.startsWith(prop)) {
279
			String value = propValue.substring(propValue.indexOf("=") + 1, propValue.length());
280

  
281
			if ((value != null) && !value.equals("")) {
282
				if (prop.equals("BLOCKSIZE"))
283
					driverParams.changeParamValue("blocksize", value);
284
				if (prop.equals("FORMAT"))
285
					driverParams.changeParamValue("format", value);
286
				if (prop.equals("COMPRESSION"))
287
					driverParams.changeParamValue("compression", value);
288
			}
289
		}
290
	}
291

  
292
	/**
293
	 * Asigna propiedades al driver a partir de un vector de
294
	 * strings donde cada elemento tiene la estructura de
295
	 * propiedad=valor.
296
	 * @param props        Propiedades
297
	 */
298
	public void setProps(String[] props) {
299
		for (int iProps = 0; iProps < props.length; iProps++)
300
			readProperty(props[iProps]);
301

  
302
		loadParams();
303

  
304
		try {
305
			if (!consulta)
306
				init();
307
		} catch (EcwException e) {
308
			e.printStackTrace();
309
		}
310
	}
311

  
312
	/**
313
	 * Realiza la funci?n de compresi?n a partir de un GeoRasterFile.
314
	 * @throws IOException
315
	 */
316
	public void fileWrite() throws IOException {
317
		/* try {
318
						compressclient.NCSEcwCompressOpen(false);
319
						compressclient.NCSEcwCompress(readerObj);
320
				} catch (EcwException e) {
321
						e.printStackTrace();
322
				}*/
323
		//TODO: FUNCIONALIDAD: Compresi?n a partir de un dataset. De momento no es necesario y es posible que nunca lo sea.
324
	}
325

  
326
	/**
327
	 * Realiza la funci?n de compresi?n a partir de los datos pasados por el cliente.
328
	 * @throws IOException
329
	 */
330
	public void dataWrite() throws IOException, ProcessInterruptedException {
331
		if (dataWriter == null)
332
			throw new IOException("No se ha obtenido un objeto para la lectura valido.");
333

  
334
		try {
335
			compressclient.NCSEcwCompressOpen(false);
336
			compressclient.NCSEcwCompress(readerObj);
337
		} catch (EcwException e) {
338
			throw new IOException("Error en la compresi?n.");
339
		}
340
	}
341

  
342
	/**
343
	 * Cierra el compresor ecw.
344
	 */
345
	public void writeClose() {
346
		try {
347
			compressclient.NCSEcwCompressClose();
348
		} catch (EcwException e) {
349
			e.printStackTrace();
350
		}
351
	}
352

  
353
	/**
354
	 * Cancela el compresor ecw.
355
	 */
356
	public void writeCancel() {
357
		try {
358
			if(readerObj != null)
359
				readerObj.setWrite(false);
360
			compressclient.NCSEcwCompressCancel();
361
		} catch (EcwException e) {
362
			e.printStackTrace();
363
		}
364
	}
365

  
366
	/*
367
	 * (non-Javadoc)
368
	 * @see org.gvsig.raster.dataset.GeoRasterWriter#setWkt(java.lang.String)
369
	 */
370
	public void setWkt(String wkt) {
371
		//TODO: FUNCIONALIDAD: La asignaci?n de proyecci?n en Ecw falla haciendo petar la aplicaci?n.
372
		/*if(compressclient != null && wkt != null && wkt.compareTo("unknown") != 0) {
373
			WktUtils wktutil = new WktUtils(wkt);
374
			compressclient.setProjection("EPSG:" + wktutil.getEPSG());
375
		}*/
376
	}
377
	
378
	/*
379
	 * (non-Javadoc)
380
	 * @see org.gvsig.raster.dataset.GeoRasterWriter#setCancellableRasterDriver(org.gvsig.raster.dataset.io.IExternalCancellable)
381
	 */
382
	public void setCancellableRasterDriver(ExternalCancellable cancellable) {
383
		super.setCancellableRasterDriver(cancellable);
384
		if(readerObj != null)
385
			readerObj.setCancellableRasterDriver(cancellable);
386
	}
387

  
388
}
389

  
390

  
391
/**
392
 * Clase que se encarga de la lectura de datos que ser?n escritos. Hereda de JniObject
393
 * para asegurar  para asegurar que el interfaz de la libreria tiene acceso a variables
394
 * necesarias para la petici?n de datos cuando vacia el buffer. Implementa ReadCallBack
395
 * para obligar escribir el m?todo loadBuffer encargado de servir los datos cuando el
396
 * buffer se vacia.
397
 *
398
 */
399
class Reader extends JniObject implements ReadCallBack {
400
	private NCSEcwCompressClient	compressclient = null;
401
	private int 					width;
402
	//private int 					height;
403
	//private int 					ulX;
404
	//private int 					ulY;
405
	private DataServerWriter        dataWriter = null;
406
	//private GdalRasterBand 			rband = null;
407
	private DefaultRasterWriter			writer = null;
408
	private int 					blockSizeRead = 1; //Alto del bloque leido de la imagen origen
409
	private int 					countLine = 1; //Contador de l?neas procesadas en cada lectura de bloque
410
	byte[][] 						buf = null;
411
	byte[] 							bufband1 = null;
412
	byte[] 							bufband2 = null;
413
	byte[] 							bufband3 = null;
414
	byte[] 							bufband4 = null;
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff