Statistics
| Revision:

root / trunk / libraries / libRaster / src / org / gvsig / raster / dataset / GeoRasterWriter.java @ 22422

History | View | Annotate | Download (13.4 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2006 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 */
19
package org.gvsig.raster.dataset;
20

    
21
import java.awt.geom.AffineTransform;
22
import java.io.IOException;
23
import java.lang.reflect.Constructor;
24
import java.lang.reflect.InvocationTargetException;
25
import java.util.ArrayList;
26
import java.util.Iterator;
27
import java.util.Map;
28
import java.util.Set;
29
import java.util.TreeMap;
30
import java.util.Map.Entry;
31

    
32
import org.cresques.cts.IProjection;
33
import org.gvsig.raster.dataset.io.RasterDriverException;
34
import org.gvsig.raster.dataset.io.features.WriteFileFormatFeatures;
35
import org.gvsig.raster.dataset.properties.DatasetColorInterpretation;
36
import org.gvsig.raster.util.RasterUtilities;
37
import org.gvsig.raster.util.extensionPoints.ExtensionPoint;
38

    
39
import es.gva.cit.jgdal.GdalException;
40
import es.gva.cit.jgdal.GdalWarp;
41

    
42
/**
43
 * Clase abstracta de la que heredan los drivers de escritura. Tiene los m?todos
44
 * abstractos que debe implementar cualquier driver de escritura y las
45
 * funcionalidades y opciones soportadas comunes a todos ellos.
46
 * 
47
 * @author Nacho Brodin (nachobrodin@gmail.com)
48
 */
49
public abstract class GeoRasterWriter {
50
        public static final int   MODE_FILEWRITE = 1;
51
        public static final int   MODE_DATAWRITE = 2;
52

    
53
        public static TreeMap     fileFeature    = new TreeMap();
54
        protected String          outFileName    = null;
55
        protected String          inFileName     = null;
56
        protected int             sizeWindowX    = 0;
57
        protected int             sizeWindowY    = 0;
58
        protected int             ulX            = 0;
59
        protected int             ulY            = 0;
60
        protected IDataWriter     dataWriter     = null;
61
        protected int             nBands         = 0;
62
        protected String          ident          = null;
63
        protected String          driver         = null;
64
        protected Params          driverParams   = null;
65
        protected AffineTransform at             = null;
66
        protected int             percent        = 0;
67
        protected int             dataType       = IBuffer.TYPE_BYTE;
68
        protected IProjection     proj           = null;
69
        protected DatasetColorInterpretation colorInterp = null;
70
                
71
        /**
72
         * Obtiene la lista de extensiones registradas
73
         * @return Lista de extensiones registradas o null si no hay ninguna
74
         */
75
        public static String[] getDriversExtensions() {
76
                ExtensionPoint extensionPoint = ExtensionPoint.getExtensionPoint("RasterWriter");
77
                return extensionPoint.getKeys();
78
        }
79

    
80
        /**
81
         * Obtiene la lista de extensiones de ficheros sobre los que se puede salvar
82
         * en un determinado tipo de datos. Como par?metro de la funci?n se especifica
83
         * el tipo de datos sobre el que se desea consultar. Este m?todo consulta para
84
         * cada driver registrado que extensiones soportan un tipo.
85
         * 
86
         * @param dataType Tipo de datos
87
         * @param bands Numero de bandas
88
         * @param reprojectable Especifica si devuelve solo los formatos reproyectables
89
         * @return Lista de extensiones registradas que soportan el tipo de datos
90
         *         pasado por par?metro.
91
         * @throws RasterDriverException
92
         */
93
        public static ArrayList getExtensionsSupported(int dataType, int bands, boolean reprojectable) throws RasterDriverException {
94
                ExtensionPoint extensionPoint = ExtensionPoint.getExtensionPoint("RasterWriter");
95
                Iterator iterator = extensionPoint.getIterator();
96
                ArrayList result = new ArrayList();
97
                while (iterator.hasNext()) {
98
                        Entry entry = (Entry) iterator.next();
99
                        String ext = (String) entry.getKey();
100
                        Class writerClass = (Class) entry.getValue();
101
                        Class[] args = { String.class };
102
                        try {
103
                                Constructor hazNuevo = writerClass.getConstructor(args);
104
                                Object[] args2 = { ext };
105
                                GeoRasterWriter grw = (GeoRasterWriter) hazNuevo.newInstance(args2);
106
                                if (grw.isSupportedThisExtension(ext, dataType, bands)) {
107
                                        if (reprojectable) {
108
                                                if (GdalWarp.getDrivers().contains(grw.getDriverName()))
109
                                                        result.add(ext);
110
                                        } else {
111
                                                result.add(ext);
112
                                        }
113
                                }
114
                        } catch (SecurityException e) {
115
                                throw new RasterDriverException("Error SecurityException in open");
116
                        } catch (NoSuchMethodException e) {
117
                                throw new RasterDriverException("Error NoSuchMethodException in open");
118
                        } catch (IllegalArgumentException e) {
119
                                throw new RasterDriverException("Error IllegalArgumentException in open");
120
                        } catch (InstantiationException e) {
121
                                throw new RasterDriverException("Error InstantiationException in open");
122
                        } catch (IllegalAccessException e) {
123
                                throw new RasterDriverException("Error IllegalAccessException in open");
124
                        } catch (InvocationTargetException e) {
125
                                throw new RasterDriverException("Error in open");
126
                        }
127
                }
128
                return result;
129
        }
130
                
131
        /**
132
         * Obtiene la lista de tipos de driver
133
         * @return Lista de tipos de driver registradas o null si no hay ninguno
134
         */
135
        public static String[] getDriversType() {
136
                if (fileFeature.size() == 0)
137
                        return null;
138
                String[] list = new String[fileFeature.size()];
139
                Set values = fileFeature.entrySet();
140
                int i = 0;
141
                for (Iterator it = values.iterator(); it.hasNext();) {
142
                        list[i] = ((WriteFileFormatFeatures) ((Map.Entry) it.next()).getValue()).getDriverName();
143
                        i++;
144
                }
145

    
146
                return list;
147
        }
148

    
149
        /**
150
         * Obtiene el tipo de driver a partir de la extensi?n
151
         * @param ext Extensi?n
152
         * @return Tipo
153
         */
154
        public static String getDriverType(String ext) {
155
                return ((WriteFileFormatFeatures) fileFeature.get(ext)).getDriverName();
156
        }
157

    
158
        /**
159
         * Devuelve el n?mero de drivers soportados
160
         * @return N?mero de drivers soportados
161
         */
162
        public static int getNDrivers() {
163
                return ExtensionPoint.getExtensionPoint("RasterWriter").size();
164
        }
165

    
166
        /**
167
         * Devuelve el n?mero de tipos de driver registrados
168
         * @return N?mero de tipos de driver soportados
169
         */
170
        public static int getNTypes() {
171
                return fileFeature.size();
172
        }
173

    
174
        /**
175
         * Devuelve el identificador del driver
176
         * @return Identificador del driver
177
         */
178
        public String getIdent() {
179
                return ident;
180
        }
181

    
182
        /**
183
         * Obtiene el nombre del driver.
184
         * @return Nombre del driver
185
         */
186
        public String getDriverName() {
187
                return driver;
188
        }
189

    
190
        /**
191
         * @return
192
         */
193
        public String getDriverType() {
194
                return driver;
195
        }
196

    
197
        /**
198
         * Asigna el porcentaje de incremento. Esto es usado por el driver para
199
         * actualizar la variable percent
200
         * @param percent
201
         */
202
        public void setPercent(int percent) {
203
                this.percent = percent;
204
        }
205

    
206
        /**
207
         * Porcentaje de escritura completado.
208
         * @return Entero con el porcentaje de escritura.
209
         */
210
        public int getPercent() {
211
                return percent;
212
        }
213

    
214
        /**
215
         * Factoria para obtener escritores de los distintos tipos de raster.
216
         * @param fName Nombre del fichero.
217
         * @return GeoRasterWriter, o null si hay problemas.
218
         */
219
        public static GeoRasterWriter getWriter(String fName) throws NotSupportedExtensionException, RasterDriverException {
220
                String ext = RasterUtilities.getExtensionFromFileName(fName);
221
                GeoRasterWriter grw = null;
222

    
223
                ExtensionPoint extensionPoint = ExtensionPoint.getExtensionPoint("RasterWriter");
224

    
225
                if (!extensionPoint.existKey(ext))
226
                        return grw;
227

    
228
                Class clase = (Class) extensionPoint.getValue(ext);
229
                Class[] args = { String.class };
230
                try {
231
                        Constructor hazNuevo = clase.getConstructor(args);
232
                        Object[] args2 = { fName };
233
                        grw = (GeoRasterWriter) hazNuevo.newInstance(args2);
234
                } catch (SecurityException e) {
235
                        throw new RasterDriverException("Error SecurityException in open");
236
                } catch (NoSuchMethodException e) {
237
                        throw new RasterDriverException("Error NoSuchMethodException in open");
238
                } catch (IllegalArgumentException e) {
239
                        throw new RasterDriverException("Error IllegalArgumentException in open");
240
                } catch (InstantiationException e) {
241
                        throw new RasterDriverException("Error InstantiationException in open");
242
                } catch (IllegalAccessException e) {
243
                        throw new RasterDriverException("Error IllegalAccessException in open");
244
                } catch (InvocationTargetException e) {
245
                        throw new NotSupportedExtensionException("Error in open");
246
                }
247
                return grw;
248
        }
249
        
250
        /**
251
         * Factoria para obtener escritores de los distintos tipos de raster.
252
         * 
253
         * @param fName Nombre del fichero.
254
         * @return GeoRasterWriter, o null si hay problemas.
255
         */
256
        public static GeoRasterWriter getWriter(IDataWriter dataWriter, 
257
                                                                                                 String outFileName, 
258
                                                                                                 int nBands,
259
                                                                                                 AffineTransform at,
260
                                                                                                 int outSizeX,
261
                                                                                                 int outSizeY,
262
                                                                                                 int dataType,
263
                                                                                                 Params params,
264
                                                                                                 IProjection proj) throws NotSupportedExtensionException, RasterDriverException {
265
                return GeoRasterWriter.getWriter(dataWriter, outFileName, nBands, at, outSizeX, outSizeY, dataType, params, proj, true);
266
        }
267
        
268
        /**
269
         * Factoria para obtener escritores de los distintos tipos de raster.
270
         * 
271
         * @param fName Nombre del fichero.
272
         * @return GeoRasterWriter, o null si hay problemas.
273
         */
274
        public static GeoRasterWriter getWriter(IDataWriter dataWriter, 
275
                                                                                                 String outFileName, 
276
                                                                                                 int nBands,
277
                                                                                                 AffineTransform at,
278
                                                                                                 int outSizeX,
279
                                                                                                 int outSizeY,
280
                                                                                                 int dataType,
281
                                                                                                 Params params,
282
                                                                                                 IProjection proj,
283
                                                                                                 boolean geo) throws NotSupportedExtensionException, RasterDriverException {
284
                String ext = outFileName.toLowerCase().substring(outFileName.lastIndexOf('.') + 1);
285
                GeoRasterWriter grw = null;
286

    
287
                ExtensionPoint extensionPoint = ExtensionPoint.getExtensionPoint("RasterWriter");
288

    
289
                if (!extensionPoint.existKey(ext))
290
                        return grw;
291

    
292
                Class clase = (Class) extensionPoint.getValue(ext);
293
                Class[] args = { IDataWriter.class, String.class, Integer.class, AffineTransform.class, Integer.class, Integer.class, Integer.class, Params.class, IProjection.class, Boolean.class };
294
                try {
295
                        Constructor hazNuevo = clase.getConstructor(args);
296
                        Object [] args2 = {dataWriter, outFileName, new Integer(nBands), at, 
297
                                                                new Integer(outSizeX), new Integer(outSizeY), new Integer(dataType), 
298
                                                                params, proj, new Boolean(geo)};
299
                        grw = (GeoRasterWriter) hazNuevo.newInstance(args2);
300
                } catch (SecurityException e) {
301
                        throw new RasterDriverException("Error SecurityException in open");
302
                } catch (NoSuchMethodException e) {
303
                        throw new RasterDriverException("Error NoSuchMethodException in open");
304
                } catch (IllegalArgumentException e) {
305
                        throw new RasterDriverException("Error IllegalArgumentException in open");
306
                } catch (InstantiationException e) {
307
                        throw new RasterDriverException("Error InstantiationException in open");
308
                } catch (IllegalAccessException e) {
309
                        throw new RasterDriverException("Error IllegalAccessException in open");
310
                } catch (InvocationTargetException e) {
311
                        throw new NotSupportedExtensionException("Error in open. Problemas con las librer?as nativas.");
312
                }
313
                return grw;
314
        }
315

    
316
        /**
317
         * Obtiene los par?metros del driver.
318
         * @return WriterParams
319
         */
320
        public Params getParams() {
321
                return driverParams;
322
        }
323

    
324
        /**
325
         * Asigna los par?metros del driver modificados por el cliente.
326
         * @param Params
327
         */
328
        public void setParams(Params params) {
329
                this.driverParams = params;
330
        }
331

    
332
        /**
333
         * Realiza la funci?n de compresi?n a partir de un GeoRasterFile.
334
         * @throws IOException
335
         */
336
        public abstract void fileWrite() throws IOException, InterruptedException;
337

    
338
        /**
339
         * Realiza la funci?n de compresi?n a partir de los datos pasados por el
340
         * cliente.
341
         * @throws IOException
342
         */
343
        public abstract void dataWrite() throws IOException, InterruptedException;
344

    
345
        /**
346
         * Cierra el driver
347
         */
348
        public abstract void writeClose();
349

    
350
        /**
351
         * Cancela el grabado de datos
352
         */
353
        public abstract void writeCancel();
354

    
355
        /**
356
         * A?ade la proyecci?n Wkt con la que salvar.
357
         * @param wkt
358
         * @throws GdalException
359
         */
360
        public abstract void setWkt(String wkt);
361

    
362
        /**
363
         * Asigna la interpretaci?n de color para el fichero de salida.
364
         * @param colorInterp Interpretaci?n de color
365
         */
366
        public void setColorBandsInterpretation(String[] colorInterp) {
367
                if (colorInterp != null) {
368
                        this.colorInterp = new DatasetColorInterpretation();
369
                        this.colorInterp.initColorInterpretation(colorInterp.length);
370
                        for (int i = 0; i < colorInterp.length; i++) {
371
                                this.colorInterp.setColorInterpValue(i, colorInterp[i]);
372
                        }
373
                }
374
        }
375

    
376
        /**
377
         * M?todo que pregunta si la extensi?n pasada por par?metro est? soportada con
378
         * el tipo y n?mero de bandas indicadas.
379
         * 
380
         * @param dataType Tipo de dato
381
         * @param bands N?mero de bandas
382
         * @param extensi?n
383
         * @return true si est? soportada y false si no lo est?
384
         */
385
        public boolean isSupportedThisExtension(String ext, int dataType, int bands) {
386
                WriteFileFormatFeatures features = (WriteFileFormatFeatures) fileFeature.get(ext);
387
                if (features == null)
388
                        return false;
389
                int[] bandsSupported = features.getNBandsSupported();
390
                for (int i = 0; i < bandsSupported.length; i++) {
391
                        if (bandsSupported[i] == -1)
392
                                break;
393
                        if (bandsSupported[i] >= bands)
394
                                break;
395
                        return false;
396
                }
397
                int[] dt = features.getDataTypesSupported();
398
                for (int i = 0; i < dt.length; i++)
399
                        if (dataType == dt[i])
400
                                return true;
401
                return false;
402
        }
403
}