Statistics
| Revision:

root / trunk / libraries / libRaster / src / org / gvsig / raster / RasterLibrary.java @ 17040

History | View | Annotate | Download (10.5 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;
20

    
21
import java.io.File;
22
import java.io.FileFilter;
23
import java.io.IOException;
24
import java.net.MalformedURLException;
25
import java.net.URL;
26
import java.util.ArrayList;
27
import java.util.Enumeration;
28
import java.util.Hashtable;
29
import java.util.jar.JarException;
30
import java.util.zip.ZipEntry;
31
import java.util.zip.ZipException;
32
import java.util.zip.ZipFile;
33

    
34
import org.apache.log4j.Logger;
35
import org.gvsig.raster.dataset.io.ErmapperDriver;
36
import org.gvsig.raster.dataset.io.ErmapperWriter;
37
import org.gvsig.raster.dataset.io.GdalDriver;
38
import org.gvsig.raster.dataset.io.GdalWriter;
39
import org.gvsig.raster.dataset.io.JpegWriter;
40
import org.gvsig.raster.dataset.io.MemoryRasterDriver;
41
import org.gvsig.raster.dataset.io.MrSidDriver;
42
import org.gvsig.raster.grid.filter.bands.ColorTableListManager;
43
import org.gvsig.raster.grid.filter.bands.HSLToRGBManager;
44
import org.gvsig.raster.grid.filter.bands.RGBToHSLManager;
45
import org.gvsig.raster.grid.filter.convolution.ConvolutionListManager;
46
import org.gvsig.raster.grid.filter.correction.MedianListManager;
47
import org.gvsig.raster.grid.filter.enhancement.BrightnessContrastListManager;
48
import org.gvsig.raster.grid.filter.enhancement.EnhancementListManager;
49
import org.gvsig.raster.grid.filter.pansharp.PanSharpeningListManager;
50
import org.gvsig.raster.grid.filter.segmentation.FirstDerivativeListManager;
51
import org.gvsig.raster.grid.filter.statistics.StatisticsListManager;
52
import org.gvsig.raster.util.extensionPoints.ExtensionPoint;
53
import org.gvsig.raster.util.extensionPoints.ExtensionPoints;
54
import org.gvsig.raster.util.extensionPoints.ExtensionPointsSingleton;
55
/**
56
 * Clase principal de la libreria. En ella se definen variables globales con informaci?n
57
 * de uso general, as? como acciones a realizar al arracar la librer?a. El m?todo que
58
 * contiene las acciones de arranque es wakeUp. Las tareas principales de este m?todo
59
 * son de registro de drivers de lectura y escritura y eliminaci?n del directorio de
60
 * temporales.
61
 *
62
 * @author Nacho Brodin (nachobrodin@gmail.com)
63
 */
64
public class RasterLibrary {
65
        public static ArrayList     writersClassList = new ArrayList();
66

    
67
        /**
68
         * En la generaci?n autom?tica de clases esta variable representa el n?mero de
69
         * clases en las que se hace la divisi?n.
70
         */
71
        public static int          defaultNumberOfClasses = 64;
72

    
73
        /**
74
         * En la genraci?n de las paletas de color, esta variable representa el n?mero
75
         * de colores en las que se hace la divisi?n para generar la paleta nueva.
76
         * Con esto conseguimos velocidad de procesamiento. Cuanto menor sea, peor
77
         * ser? la calidad representada de la imagen.
78
         */
79
        public static int          defaultNumberOfColors = 256;
80
        /**
81
         * Tama?o de bloque en los procesos que recorren un raster completo a base de ventanas con recorrido
82
         * descendente. Esta variable indica la altura de dicho bloque. Por lo tanto cada bloque ser? de
83
         * raster.width X blockHeight. Tipicamente recorridos de este tipo se usan para el calculo de estad?sticas,
84
         * histogramas, salvado a raster, etc... Es importante para el buen funcionamiento que este bloque sea
85
         * potencia de dos.
86
         */
87
        public static int          blockHeight = 512;
88

    
89
        //*************CACHE*******************
90
        /**
91
         * Tama?o aproximado de cach? en Megas. Si este valor es alto cabr?n muchas p?ginas en memoria
92
         * a la vez y si es bajo cabr?n pocas. Hay que tener en cuenta que al instanciar se convertira en bytes
93
         * para su mejor tratamiento. Al llamar al constructor esta variable contendr? el tama?o exacto
94
         * de la cache en bytes. El tama?o aqu? especificado es aproximado. Este variar? dependiendo de los
95
         * par?metros del raster a cachear ya que las p?ginas deben tener una altura potencia de 2.
96
         */
97
        public static long        cacheSize = 25;
98
        /**
99
         * Tama?o m?ximo de la p?gina en Megas. Hay que tener en cuenta que al instanciar se convertira en bytes
100
         * para su mejor tratamiento. Al llamar al constructor esta variable contendr? el tama?o exacto
101
         * de la p?gina en bytes
102
         */
103
        public static double      pageSize = 4;
104
        /**
105
         * N?mero de p?ginas que tiene cada conjunto de cach?
106
         */
107
        public static int         pagsPerGroup = 5;
108

    
109
        //*************PATHS*******************
110

    
111
        /**
112
         * Directorio temporal para la cach?. Si gastamos el mismo que andami este se ocupar? de gestionar su
113
         * destrucci?n al cerrar gvSIG.
114
         */
115
        public static String      tempCacheDirectoryPath = System.getProperty("java.io.tmpdir") + File.separator + "tmp-andami";
116
        /**
117
         * Ruta o rutas donde busca jars con clases que incorporen elementos nuevos que extiendan
118
         * otros ya existentes. Estos pueden ser drivers o filtros.
119
         */
120
        public static String[]    pathExtensions = {"." + File.separator};
121

    
122
        private static Hashtable  clasesJar = new Hashtable();
123

    
124
        /**
125
         * Establece si el valor noData esta activado o desactivado.
126
         */
127
        public static boolean     noDataEnabled = true;
128

    
129
        /**
130
         * Valor noData general para la librer?a. En caso de no tener un valor asociado
131
         * al raster se usar? este.
132
         */
133
        public static double      noDataValue = -99999;
134

    
135
        /**
136
         * Valor de transparencia para un valor noData de la libreria. En caso de no
137
         * tener un valor asociado por el usuario, se usar? este.
138
         */
139
        public static boolean     noDataTransparent = true;
140

    
141
        /**
142
         * Ejecuta las acciones necesarias para arrancar la librer?a.
143
         */
144
        public static void wakeUp() {
145
                //Punto de extensi?n para registro de drivers de lectura
146
                ExtensionPoints extensionPoints = ExtensionPointsSingleton.getInstance();
147
                if (!extensionPoints.containsKey("RasterReader"))
148
                        extensionPoints.put( new ExtensionPoint( "RasterReader", "Raster Reader Classes"));
149

    
150
                //Punto de extensi?n para registro de drivers de escritura
151
                if (!extensionPoints.containsKey("RasterWriter"))
152
                        extensionPoints.put(new ExtensionPoint("RasterWriter", "Raster Writer Classes"));
153

    
154
                //Ejecuta el c?digo static de la clase cada driver
155
                GdalDriver.register();
156
                ErmapperDriver.register();
157
                MrSidDriver.register();
158
                MemoryRasterDriver.register();
159

    
160
                GdalWriter.register();
161
                ErmapperWriter.register();
162
                JpegWriter.register();
163

    
164
                //Punto de extensi?n para registro de filtros
165
                if (!extensionPoints.containsKey("RasterFilter")) {
166
                        extensionPoints.put(new ExtensionPoint("RasterFilter", "Raster Filter Classes"));
167
                }
168

    
169
                // Invoca las llamadas est?ticas de cada clase para registrarlas en los
170
                // puntos de extensi?n
171
                BrightnessContrastListManager.register();
172
                EnhancementListManager.register();
173
                FirstDerivativeListManager.register();
174
                MedianListManager.register();
175
                ConvolutionListManager.register();
176
                ColorTableListManager.register();
177
                StatisticsListManager.register();
178
                PanSharpeningListManager.register();
179
                RGBToHSLManager.register();
180
                HSLToRGBManager.register();
181
                // Registrar los nuevos filtros del directorio
182
                //registerClasses();
183

    
184
                //Limpiamos el directorio temporal
185
                RasterLibrary.cleanUpTempFiles();
186
        }
187

    
188
        /**
189
         * Elimina los ficheros del directorio temporal. Realizamos esta acci?n al
190
         * levantar la librer?a.
191
         */
192
        public static void cleanUpTempFiles() {
193
                try {
194
                        File tempDirectory = new File(tempCacheDirectoryPath);
195

    
196
                        File[] files = tempDirectory.listFiles();
197
                        if (files != null) {
198
                                for (int i = 0; i < files.length; i++) {
199
                                        // s?lo por si en un futuro se necesitan crear directorios temporales
200
                                        if (files[i].isDirectory())
201
                                                deleteDirectory(files[i]);
202
                                        files[i].delete();
203
                                }
204
                        }
205
                        tempDirectory.delete();
206
                } catch (Exception e) {
207
                }
208
        }
209

    
210
        /**
211
         * Recursive directory delete.
212
         * @param f
213
         */
214
        private static void deleteDirectory(File f) {
215
                File[] files = f.listFiles();
216
                for (int i = 0; i < files.length; i++) {
217
                        if (files[i].isDirectory())
218
                                deleteDirectory(files[i]);
219
                        files[i].delete();
220
                }
221
        }
222

    
223
        /**
224
         * Esta funci?n buscar? todos los jars en las rutas de pathExtensions y
225
         * registrar? todos las clases registrables. En este momento hay posibilidad
226
         * de registro de drivers y filtros.
227
         */
228
        private static void registerClasses() throws Exception {
229
                RasterClassLoader loader = new RasterClassLoader();
230

    
231
                //Cargamos sobre jarList todos los File correspondientes a los jar contenidos en pathExtensions
232
                File[] jarList = null;
233
                for (int iPath = 0; iPath < pathExtensions.length; iPath++) {
234
                        File directory = new File(pathExtensions[iPath]);
235
                        if (directory.isDirectory() && directory.canRead()) {
236
                                jarList = directory.listFiles(new FileFilter() {
237
                                                                                                public boolean accept(File pathname) {
238
                                                                                                                return (pathname.getName().toUpperCase().endsWith(".JAR"));
239
                                                                                                }
240
                                                                                                });
241
                        }
242
                }
243

    
244
                //Creamos las URL
245
                URL[] urls = new URL[jarList.length];
246

    
247
                for (int j = 0; j < jarList.length; j++) {
248
                        try {
249
                                urls[j] = new URL("file:" + jarList[j]);
250
                        } catch (MalformedURLException e) {
251
                                Logger.getLogger(RasterLibrary.class.getName()).debug("Error formando la URL, jar incorrecto", e);
252
                        }
253
                }
254

    
255
                //Comprobamos que no haya clases repetidas
256
                ZipFile[] jarFiles = new ZipFile[jarList.length];
257
                for (int i = 0; i < jarList.length; i++) {
258
                        try {
259
                                jarFiles[i] = new ZipFile(jarList[i].getPath());
260

    
261
                                Enumeration entradas = jarFiles[i].entries();
262

    
263
                                while (entradas.hasMoreElements()) {
264
                                        ZipEntry file = (ZipEntry) entradas.nextElement();
265
                                        String fileName = file.getName();
266

    
267
                                        if (!fileName.toLowerCase().endsWith(".class"))
268
                                                continue;
269

    
270
                                        fileName = fileName.substring(0, fileName.length() - 6).replace('/', '.');
271

    
272
                                        if (clasesJar.get(fileName) != null) {
273
                                                throw new JarException("CLASES REPETIDAS: " + fileName + " " + " en " +
274
                                                                jarFiles[i].getName() + " y en " + ((ZipFile) clasesJar.get(fileName)).getName());
275
                                        }
276

    
277
                                        clasesJar.put(fileName, jarFiles[i]);
278
                                }
279
                        } catch (ZipException e) {
280
                                throw new IOException(" Jar: " + jarList[i].getPath() + ": " + jarFiles[i]);
281
                        } catch (IOException e) {
282
                                throw e;
283
                        }
284
                }
285

    
286
        }
287
}