Statistics
| Revision:

root / branches / v2_0_0_prep / libraries / libRaster / src / org / gvsig / raster / dataset / GeoRasterWriter.java @ 29535

History | View | Annotate | Download (14.1 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

    
31
import org.cresques.cts.IProjection;
32
import org.gvsig.raster.dataset.properties.DatasetColorInterpretation;
33
import org.gvsig.raster.dataset.serializer.RmfSerializerException;
34
import org.gvsig.raster.util.RasterUtilities;
35
import org.gvsig.tools.ToolsLocator;
36
import org.gvsig.tools.extensionpoint.ExtensionPoint;
37
import org.gvsig.tools.extensionpoint.ExtensionPointManager;
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
        protected IExternalCancellable extCancellable = null;
71

    
72
        /**
73
         * Obtiene la lista de extensiones registradas
74
         * @return Lista de extensiones registradas o null si no hay ninguna
75
         */
76
        public static String[] getDriversExtensions() {
77
                ExtensionPointManager extensionPoints = ToolsLocator.getExtensionPointManager();
78
                ExtensionPoint point = extensionPoints.get("RasterWriter");
79
                return (String[])point.getNames().toArray(new String[0]);
80
        }
81

    
82
        /**
83
         * Obtiene la lista de extensiones de ficheros sobre los que se puede salvar
84
         * en un determinado tipo de datos. Como par?metro de la funci?n se especifica
85
         * el tipo de datos sobre el que se desea consultar. Este m?todo consulta para
86
         * cada driver registrado que extensiones soportan un tipo.
87
         *
88
         * @param dataType Tipo de datos
89
         * @param bands Numero de bandas
90
         * @param reprojectable Especifica si devuelve solo los formatos reproyectables
91
         * @return Lista de extensiones registradas que soportan el tipo de datos
92
         *         pasado por par?metro.
93
         * @throws RasterDriverException
94
         */
95
        public static ArrayList getExtensionsSupported(int dataType, int bands, boolean reprojectable) throws RasterDriverException {
96
                ExtensionPointManager extensionPoints = ToolsLocator.getExtensionPointManager();
97
                ExtensionPoint point = extensionPoints.get("RasterWriter");
98
                Iterator iterator = point.iterator();
99
                ArrayList result = new ArrayList();
100
                while (iterator.hasNext()) {
101
                        ExtensionPoint.Extension extension = (ExtensionPoint.Extension) iterator
102
                                        .next();
103
                        String ext = extension.getName();
104
                        Class writerClass = extension.getExtension();
105
                        Class[] args = { String.class };
106
                        try {
107
                                Constructor hazNuevo = writerClass.getConstructor(args);
108
                                Object[] args2 = { ext };
109
                                GeoRasterWriter grw = (GeoRasterWriter) hazNuevo.newInstance(args2);
110
                                if (grw.isSupportedThisExtension(ext, dataType, bands))
111
                                        if (reprojectable) {
112
                                                if (GdalWarp.getDrivers().contains(grw.getDriverName()))
113
                                                        result.add(ext);
114
                                        } else
115
                                                result.add(ext);
116
                        } catch (SecurityException e) {
117
                                throw new RasterDriverException("Error SecurityException in open");
118
                        } catch (NoSuchMethodException e) {
119
                                throw new RasterDriverException("Error NoSuchMethodException in open");
120
                        } catch (IllegalArgumentException e) {
121
                                throw new RasterDriverException("Error IllegalArgumentException in open");
122
                        } catch (InstantiationException e) {
123
                                throw new RasterDriverException("Error InstantiationException in open");
124
                        } catch (IllegalAccessException e) {
125
                                throw new RasterDriverException("Error IllegalAccessException in open");
126
                        } catch (InvocationTargetException e) {
127
                                throw new RasterDriverException("Error in open");
128
                        }
129
                }
130
                return result;
131
        }
132

    
133
        /**
134
         * Obtiene la lista de tipos de driver
135
         * @return Lista de tipos de driver registradas o null si no hay ninguno
136
         */
137
        public static String[] getDriversType() {
138
                if (fileFeature.size() == 0)
139
                        return null;
140
                String[] list = new String[fileFeature.size()];
141
                Set values = fileFeature.entrySet();
142
                int i = 0;
143
                for (Iterator it = values.iterator(); it.hasNext();) {
144
                        list[i] = ((WriteFileFormatFeatures) ((Map.Entry) it.next()).getValue()).getDriverName();
145
                        i++;
146
                }
147

    
148
                return list;
149
        }
150

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

    
160
        /**
161
         * Devuelve el n?mero de drivers soportados
162
         * @return N?mero de drivers soportados
163
         */
164
        public static int getNDrivers() {
165
                ExtensionPointManager extensionPoints = ToolsLocator.getExtensionPointManager();
166
                ExtensionPoint point = extensionPoints.get("RasterWriter");
167
                return point.getCount();
168
        }
169

    
170
        /**
171
         * Devuelve el n?mero de tipos de driver registrados
172
         * @return N?mero de tipos de driver soportados
173
         */
174
        public static int getNTypes() {
175
                return fileFeature.size();
176
        }
177

    
178
        /**
179
         * Devuelve el identificador del driver
180
         * @return Identificador del driver
181
         */
182
        public String getIdent() {
183
                return ident;
184
        }
185

    
186
        /**
187
         * Obtiene el nombre del driver.
188
         * @return Nombre del driver
189
         */
190
        public String getDriverName() {
191
                return driver;
192
        }
193

    
194
        /**
195
         * @return
196
         */
197
        public String getDriverType() {
198
                return driver;
199
        }
200

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

    
210
        /**
211
         * Porcentaje de escritura completado.
212
         * @return Entero con el porcentaje de escritura.
213
         */
214
        public int getPercent() {
215
                return percent;
216
        }
217

    
218
        /**
219
         * Factoria para obtener escritores de los distintos tipos de raster.
220
         * @param fName Nombre del fichero.
221
         * @return GeoRasterWriter, o null si hay problemas.
222
         */
223
        public static GeoRasterWriter getWriter(String fName) throws NotSupportedExtensionException, RasterDriverException {
224
                String ext = RasterUtilities.getExtensionFromFileName(fName);
225
                GeoRasterWriter grw = null;
226
                ExtensionPointManager extensionPoints = ToolsLocator.getExtensionPointManager();
227
                ExtensionPoint point = extensionPoints.get("RasterWriter");
228
//                ExtensionPoint extensionPoint = ExtensionPoint.getExtensionPoint("RasterWriter");
229

    
230
                if (!point.has(ext))
231
                        return grw;
232

    
233
                Class clase = point.get(ext).getExtension();
234
                Class[] args = { String.class };
235
                try {
236
                        Constructor hazNuevo = clase.getConstructor(args);
237
                        Object[] args2 = { fName };
238
                        grw = (GeoRasterWriter) hazNuevo.newInstance(args2);
239
                } catch (SecurityException e) {
240
                        throw new RasterDriverException("Error SecurityException in open");
241
                } catch (NoSuchMethodException e) {
242
                        throw new RasterDriverException("Error NoSuchMethodException in open");
243
                } catch (IllegalArgumentException e) {
244
                        throw new RasterDriverException("Error IllegalArgumentException in open");
245
                } catch (InstantiationException e) {
246
                        throw new RasterDriverException("Error InstantiationException in open");
247
                } catch (IllegalAccessException e) {
248
                        throw new RasterDriverException("Error IllegalAccessException in open");
249
                } catch (InvocationTargetException e) {
250
                        throw new NotSupportedExtensionException("Error in open");
251
                }
252
                return grw;
253
        }
254

    
255
        /**
256
         * Factoria para obtener escritores de los distintos tipos de raster.
257
         *
258
         * @param fName Nombre del fichero.
259
         * @return GeoRasterWriter, o null si hay problemas.
260
         */
261
        public static GeoRasterWriter getWriter(IDataWriter dataWriter,
262
                                                                                                 String outFileName,
263
                                                                                                 int nBands,
264
                                                                                                 AffineTransform at,
265
                                                                                                 int outSizeX,
266
                                                                                                 int outSizeY,
267
                                                                                                 int dataType,
268
                                                                                                 Params params,
269
                                                                                                 IProjection proj) throws NotSupportedExtensionException, RasterDriverException {
270
                return GeoRasterWriter.getWriter(dataWriter, outFileName, nBands, at, outSizeX, outSizeY, dataType, params, proj, true);
271
        }
272

    
273
        /**
274
         * Factoria para obtener escritores de los distintos tipos de raster.
275
         *
276
         * @param fName Nombre del fichero.
277
         * @return GeoRasterWriter, o null si hay problemas.
278
         */
279
        public static GeoRasterWriter getWriter(IDataWriter dataWriter,
280
                                                                                                 String outFileName,
281
                                                                                                 int nBands,
282
                                                                                                 AffineTransform at,
283
                                                                                                 int outSizeX,
284
                                                                                                 int outSizeY,
285
                                                                                                 int dataType,
286
                                                                                                 Params params,
287
                                                                                                 IProjection proj,
288
                                                                                                 boolean geo) throws NotSupportedExtensionException, RasterDriverException {
289
                String ext = outFileName.toLowerCase().substring(outFileName.lastIndexOf('.') + 1);
290
                GeoRasterWriter grw = null;
291
                ExtensionPointManager extensionPoints =ToolsLocator.getExtensionPointManager();
292
                ExtensionPoint point=extensionPoints.get("RasterWriter");
293
//                ExtensionPoint extensionPoint = ExtensionPoint.getExtensionPoint("RasterWriter");
294

    
295
                if (!point.has(ext))
296
                        return grw;
297

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

    
322
        /**
323
         * Obtiene los par?metros del driver.
324
         * @return WriterParams
325
         */
326
        public Params getParams() {
327
                return driverParams;
328
        }
329

    
330
        /**
331
         * Asigna los par?metros del driver modificados por el cliente.
332
         * @param Params
333
         */
334
        public void setParams(Params params) {
335
                this.driverParams = params;
336
        }
337

    
338
        /**
339
         * Realiza la funci?n de compresi?n a partir de un GeoRasterFile.
340
         * @throws IOException
341
         */
342
        public abstract void fileWrite() throws IOException, InterruptedException;
343

    
344
        /**
345
         * Realiza la funci?n de compresi?n a partir de los datos pasados por el
346
         * cliente.
347
         * @throws IOException
348
         * @throws RmfSerializerException
349
         */
350
        public abstract void dataWrite() throws IOException, InterruptedException;
351

    
352
        /**
353
         * Cierra el driver
354
         */
355
        public abstract void writeClose();
356

    
357
        /**
358
         * Cancela el grabado de datos
359
         */
360
        public abstract void writeCancel();
361

    
362
        /**
363
         * A?ade la proyecci?n Wkt con la que salvar.
364
         * @param wkt
365
         * @throws GdalException
366
         */
367
        public abstract void setWkt(String wkt);
368

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

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

    
410
        /**
411
         * Assigns the object to be cancelled
412
         *
413
         * @param cancellable
414
         */
415
        public void setCancellableRasterDriver(IExternalCancellable cancellable) {
416
                this.extCancellable = cancellable;
417
        }
418
}