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

View differences:

ErmapperProvider.java
27 27
import java.io.BufferedReader;
28 28
import java.io.File;
29 29
import java.io.FileReader;
30
import java.net.URI;
31
import java.net.URISyntaxException;
30 32

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

  
32 37
import org.gvsig.fmap.dal.DALFileLocator;
33 38
import org.gvsig.fmap.dal.DALLocator;
34 39
import org.gvsig.fmap.dal.DataStore;
......
39 44
import org.gvsig.fmap.dal.coverage.exception.BandAccessException;
40 45
import org.gvsig.fmap.dal.coverage.exception.FileNotOpenException;
41 46
import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
47
import org.gvsig.fmap.dal.coverage.exception.InvalidSourceException;
42 48
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
43 49
import org.gvsig.fmap.dal.coverage.exception.ParsingException;
44 50
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
......
46 52
import org.gvsig.fmap.dal.coverage.store.parameter.RasterDataParameters;
47 53
import org.gvsig.fmap.dal.coverage.store.parameter.RasterFileStoreParameters;
48 54
import org.gvsig.fmap.dal.coverage.store.props.Transparency;
55
import org.gvsig.fmap.dal.exception.OpenException;
49 56
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
50 57
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
51 58
import org.gvsig.metadata.MetadataLocator;
......
70 77
import com.ermapper.ecw.JNCSFileNotOpenException;
71 78
import com.ermapper.ecw.JNCSInvalidSetViewException;
72 79
import com.ermapper.ecw.JNCSProgressiveUpdate;
80

  
73 81
/**
74 82
 * Driver de Ecw
75 83
 *
76 84
 * @author Nacho Brodin (nachobrodin@gmail.com)
77 85
 */
78 86
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 87

  
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");
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;
182 98

  
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;
99
    public static void register() {
100
        RasterLocator.getManager().getProviderServices().registerFileProvidersTiled(ErmapperProvider.class);
101
        registerFormats();
203 102

  
204
		int[] dt = new int[bandCount];
205
		for (int i = 0; i < bandCount; i++)
206
			dt[i] = Buffer.TYPE_BYTE;
207
		setDataType(dt);
103
        DataManagerProviderServices dataman = (DataManagerProviderServices) DALLocator.getDataManager();
104
        if (dataman != null && !dataman.getStoreProviders().contains(NAME)) {
105
            dataman.registerStoreProvider(NAME, ErmapperProvider.class, ErmapperDataParameters.class);
106
        }
208 107

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

  
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);
112
        dataman.registerStoreFactory(NAME, DefaultStoreFactory.class);
113
    }
229 114

  
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
	}
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
    }
250 120

  
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
	}
121
    public String[] getFormatList() {
122
        return formatList;
123
    }
260 124

  
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
	}
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
    }
270 140

  
271
	public Transparency getTransparency() {
272
		if(fileTransparency == null)
273
			fileTransparency = new DataStoreTransparency(getColorInterpretation());
274
		return fileTransparency;
275
	}
141
    /**
142
     * Mandatory constructor to instantiate an empty provider
143
     */
144
    public ErmapperProvider() {
145
    }
276 146

  
277
	public double getWidth() {
278
		return file.width;
279
	}
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
    }
280 176

  
281
	public double getHeight() {
282
		return file.height;
283
	}
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
    }
284 197

  
285
	public Extent getView() {
286
		return viewRequest;
287
	}
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
    }
288 204

  
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
	}
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
        }
343 221

  
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
			}
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
        }
378 228

  
379
			if(task.getEvent() != null)
380
				task.manageEvent(task.getEvent());
381
			if(status != null && status.isCancelled())
382
				return;
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
         */
383 243

  
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);
244
        load();
245
        bandCount = file.numBands;
393 246

  
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
		}
247
        int[] dt = new int[bandCount];
248
        for (int i = 0; i < bandCount; i++)
249
            dt[i] = Buffer.TYPE_BYTE;
250
        setDataType(dt);
401 251

  
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
	}
252
        super.init();
447 253

  
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;
254
        try {
255
            loadFromRmf(getRmfBlocksManager());
256
        } catch (ParsingException e) {
257
            // No lee desde rmf
258
        }
259
        open = true;
260
    }
453 261

  
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
			}
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);
513 274

  
514
		}
515
		//********* END caso especial que resuelve Bug#1 **********************
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
    }
516 295

  
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
		}
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
    }
531 302

  
532
		if(task.getEvent() != null)
533
			task.manageEvent(task.getEvent());
303
    public boolean isOpen() {
304
        return open;
305
    }
534 306

  
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
		}
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
    }
548 318

  
549
		if(task.getEvent() != null)
550
			task.manageEvent(task.getEvent());
319
    public Transparency getTransparency() {
320
        if (fileTransparency == null)
321
            fileTransparency = new DataStoreTransparency(getColorInterpretation());
322
        return fileTransparency;
323
    }
551 324

  
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
		}
325
    public double getWidth() {
326
        return file.width;
327
    }
563 328

  
564
		if(task.getEvent() != null)
565
			task.manageEvent(task.getEvent());
329
    public double getHeight() {
330
        return file.height;
331
    }
566 332

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

  
569
	public void reProject(ICoordTrans rp) {
570
	}
337
    public void setView(Extent e) {
338
        viewRequest = new ExtentImpl(e);
339
    }
571 340

  
572
	public int getBlockSize() {
573
		return 0;
574
	}
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
    }
575 350

  
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");
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;
579 366

  
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
		}
367
        Point2D ul = ext.getUL();
368
        Point2D lr = ext.getLR();
589 369

  
590
		Extent e = new ExtentImpl(begin.getX(), begin.getY(), end.getX(), end.getY());
370
        Point2D p1 = new Point2D.Double();
371
        Point2D p2 = new Point2D.Double();
591 372

  
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);
373
        try {
374
            externalTransformation.inverseTransform(ul, p1);
375
        } catch (NoninvertibleTransformException e) {
376
            e.printStackTrace();
377
        }
378
        ownTransformation.transform(p1, p1);
596 379

  
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
		}
380
        try {
381
            externalTransformation.inverseTransform(lr, p2);
382
        } catch (NoninvertibleTransformException e) {
383
            e.printStackTrace();
384
        }
385
        ownTransformation.transform(p2, p2);
629 386

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

  
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");
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() + "");
637 426

  
638
		if((pos + blockHeight) > file.height)
639
			blockHeight = Math.abs(file.height - pos);
427
            int[] readBandsFromECW = new int[Math.max(file.numBands, 3)];
640 428

  
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];
429
            for (int i = 0; i < readBandsFromECW.length; i++) {
430
                readBandsFromECW[i] = i;
431
            }
644 432

  
645
		for(int i = 0; i < file.numBands; i++)
646
			readBandsFromECW[i] = i;
433
            if (task.getEvent() != null)
434
                task.manageEvent(task.getEvent());
435
            if (status != null && status.isCancelled())
436
                return;
647 437

  
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);
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);
651 444

  
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);
445
            // Escribimos el raster sobre un Buffer
446
            int[] pRGBArray = new int[bufWidth];
447
            drawRGB2(rasterBuf, pRGBArray, bandList, status);
655 448

  
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
				}
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
        }
675 456

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

  
679
			} else {
680
				//TODO: FUNCIONALIDAD: file.numBands > 3
681
			}
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;
682 463

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

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

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

  
699
		Point2D begin = new Point2D.Double(x, y);
700
		Point2D end = new Point2D.Double(x + 1, y + 1);
575
        }
576
        // ********* END caso especial que resuelve Bug#1 **********************
701 577

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

  
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
		}
593
        if (task.getEvent() != null)
594
            task.manageEvent(task.getEvent());
712 595

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

  
735
	public void refreshUpdate(int arg0, int arg1, double arg2, double arg3, double arg4, double arg5) {
736
	}
610
        if (task.getEvent() != null)
611
            task.manageEvent(task.getEvent());
737 612

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

  
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
	}
625
        if (task.getEvent() != null)
626
            task.manageEvent(task.getEvent());
756 627

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

  
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
	}
630
    public void reProject(ICoordTrans rp) {
631
    }
768 632

  
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
	}
633
    public int getBlockSize() {
634
        return 0;
635
    }
774 636

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

  
779
	
780
	public String getStringProjection() throws RasterDriverException{
781
		return file.projection;
782
	}
642
        Point2D begin = rasterToWorld(new Point2D.Double(0, line));
643
        Point2D end = rasterToWorld(new Point2D.Double(file.width, line + 1));
644
        int[] readBandsFromECW = new int[file.numBands];
645
        if (file.numBands <= 3) {
646
            for (int i = 0; i < file.numBands; i++)
647
                readBandsFromECW[i] = i;
648
        } else {
649
            readBandsFromECW[0] = band;
650
        }
783 651

  
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
}
652
        Extent e = new ExtentImpl(begin.getX(), begin.getY(), end.getX(), end.getY());
653

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

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

  
697
        return null;
698
    }
699

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

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

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

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

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

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

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

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

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

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

  
762
        return buf;
763
    }
764

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff