Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libRaster / src / org / gvsig / raster / RasterLibrary.java @ 15948

History | View | Annotate | Download (9.74 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.convolution.ConvolutionListManager;
44
import org.gvsig.raster.grid.filter.correction.MedianListManager;
45
import org.gvsig.raster.grid.filter.enhancement.BrightnessContrastListManager;
46
import org.gvsig.raster.grid.filter.enhancement.EnhancementListManager;
47
import org.gvsig.raster.grid.filter.pansharp.PanSharpeningListManager;
48
import org.gvsig.raster.grid.filter.segmentation.FirstDerivativeListManager;
49
import org.gvsig.raster.grid.filter.statistics.StatisticsListManager;
50
import org.gvsig.raster.util.extensionPoints.ExtensionPoint;
51
import org.gvsig.raster.util.extensionPoints.ExtensionPoints;
52
import org.gvsig.raster.util.extensionPoints.ExtensionPointsSingleton;
53
/**
54
 * Clase principal de la libreria. En ella se definen variables globales con informaci?n
55
 * de uso general, as? como acciones a realizar al arracar la librer?a. El m?todo que
56
 * contiene las acciones de arranque es wakeUp. Las tareas principales de este m?todo
57
 * son de registro de drivers de lectura y escritura y eliminaci?n del directorio de
58
 * temporales.
59
 *
60
 * @author Nacho Brodin (nachobrodin@gmail.com)
61
 */
62
public class RasterLibrary {
63
        public static ArrayList writersClassList = new ArrayList();
64

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

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

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

    
107
        //*************PATHS*******************
108

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

    
120
        private static Hashtable clasesJar = new Hashtable();
121

    
122
        /**
123
         * Ejecuta las acciones necesarias para arrancar la librer?a.
124
         */
125
        public static void wakeUp() {
126
                //Punto de extensi?n para registro de drivers de lectura
127
                ExtensionPoints extensionPoints = ExtensionPointsSingleton.getInstance();
128
                if (!extensionPoints.containsKey("RasterReader"))
129
                        extensionPoints.put( new ExtensionPoint( "RasterReader", "Raster Reader Classes"));
130

    
131
                //Punto de extensi?n para registro de drivers de escritura
132
                if (!extensionPoints.containsKey("RasterWriter"))
133
                        extensionPoints.put(new ExtensionPoint("RasterWriter", "Raster Writer Classes"));
134

    
135
                //Ejecuta el c?digo static de la clase cada driver
136
                GdalDriver.register();
137
                ErmapperDriver.register();
138
                MrSidDriver.register();
139
                MemoryRasterDriver.register();
140

    
141
                GdalWriter.register();
142
                ErmapperWriter.register();
143
                JpegWriter.register();
144

    
145
                //Punto de extensi?n para registro de filtros
146
                if (!extensionPoints.containsKey("RasterFilter")) {
147
                        extensionPoints.put(new ExtensionPoint("RasterFilter", "Raster Filter Classes"));
148
                }
149

    
150
                // Invoca las llamadas est?ticas de cada clase para registrarlas en los
151
                // puntos de extensi?n
152
                BrightnessContrastListManager.register();
153
                EnhancementListManager.register();
154
                FirstDerivativeListManager.register();
155
                MedianListManager.register();
156
                ConvolutionListManager.register();
157
                ColorTableListManager.register();
158
                StatisticsListManager.register();
159
                PanSharpeningListManager.register();
160
                // Registrar los nuevos filtros del directorio
161
                //registerClasses();
162

    
163
                //Limpiamos el directorio temporal
164
                RasterLibrary.cleanUpTempFiles();
165
        }
166

    
167
        /**
168
         * Elimina los ficheros del directorio temporal. Realizamos esta acci?n al
169
         * levantar la librer?a.
170
         */
171
        public static void cleanUpTempFiles() {
172
                try {
173
                        File tempDirectory = new File(tempCacheDirectoryPath);
174

    
175
                        File[] files = tempDirectory.listFiles();
176
                        if (files != null) {
177
                                for (int i = 0; i < files.length; i++) {
178
                                        // s?lo por si en un futuro se necesitan crear directorios temporales
179
                                        if (files[i].isDirectory())
180
                                                deleteDirectory(files[i]);
181
                                        files[i].delete();
182
                                }
183
                        }
184
                        tempDirectory.delete();
185
                } catch (Exception e) {
186
                }
187
        }
188

    
189
        /**
190
         * Recursive directory delete.
191
         * @param f
192
         */
193
        private static void deleteDirectory(File f) {
194
                File[] files = f.listFiles();
195
                for (int i = 0; i < files.length; i++) {
196
                        if (files[i].isDirectory())
197
                                deleteDirectory(files[i]);
198
                        files[i].delete();
199
                }
200
        }
201

    
202
        /**
203
         * Esta funci?n buscar? todos los jars en las rutas de pathExtensions y
204
         * registrar? todos las clases registrables. En este momento hay posibilidad
205
         * de registro de drivers y filtros.
206
         */
207
        private static void registerClasses() throws Exception {
208
                RasterClassLoader loader = new RasterClassLoader();
209

    
210
                //Cargamos sobre jarList todos los File correspondientes a los jar contenidos en pathExtensions
211
                File[] jarList = null;
212
                for (int iPath = 0; iPath < pathExtensions.length; iPath++) {
213
                        File directory = new File(pathExtensions[iPath]);
214
                        if (directory.isDirectory() && directory.canRead()) {
215
                                jarList = directory.listFiles(new FileFilter() {
216
                                                                                                public boolean accept(File pathname) {
217
                                                                                                                return (pathname.getName().toUpperCase().endsWith(".JAR"));
218
                                                                                                }
219
                                                                                                });
220
                        }
221
                }
222

    
223
                //Creamos las URL
224
                URL[] urls = new URL[jarList.length];
225

    
226
                for (int j = 0; j < jarList.length; j++) {
227
                        try {
228
                                urls[j] = new URL("file:" + jarList[j]);
229
                        } catch (MalformedURLException e) {
230
                                Logger.getLogger(RasterLibrary.class.getName()).debug("Error formando la URL, jar incorrecto", e);
231
                        }
232
                }
233

    
234
                //Comprobamos que no haya clases repetidas
235
                ZipFile[] jarFiles = new ZipFile[jarList.length];
236
                for (int i = 0; i < jarList.length; i++) {
237
                        try {
238
                                jarFiles[i] = new ZipFile(jarList[i].getPath());
239

    
240
                                Enumeration entradas = jarFiles[i].entries();
241

    
242
                                while (entradas.hasMoreElements()) {
243
                                        ZipEntry file = (ZipEntry) entradas.nextElement();
244
                                        String fileName = file.getName();
245

    
246
                                        if (!fileName.toLowerCase().endsWith(".class"))
247
                                                continue;
248

    
249
                                        fileName = fileName.substring(0, fileName.length() - 6).replace('/', '.');
250

    
251
                                        if (clasesJar.get(fileName) != null) {
252
                                                throw new JarException("CLASES REPETIDAS: " + fileName + " " + " en " +
253
                                                                jarFiles[i].getName() + " y en " + ((ZipFile) clasesJar.get(fileName)).getName());
254
                                        }
255

    
256
                                        clasesJar.put(fileName, jarFiles[i]);
257
                                }
258
                        } catch (ZipException e) {
259
                                throw new IOException(" Jar: " + jarList[i].getPath() + ": " + jarFiles[i]);
260
                        } catch (IOException e) {
261
                                throw e;
262
                        }
263
                }
264

    
265
        }
266
}