root / trunk / libraries / libRaster / src / org / gvsig / raster / RasterLibrary.java @ 37962
History | View | Annotate | Download (14 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.util.ArrayList; |
23 |
|
24 |
import org.gvsig.raster.dataset.io.ErmapperDriver; |
25 |
import org.gvsig.raster.dataset.io.ErmapperWriter; |
26 |
import org.gvsig.raster.dataset.io.GdalDriver; |
27 |
import org.gvsig.raster.dataset.io.GdalWriter; |
28 |
import org.gvsig.raster.dataset.io.JpegWriter; |
29 |
import org.gvsig.raster.dataset.io.MemoryRasterDriver; |
30 |
import org.gvsig.raster.dataset.io.MrSidDriver; |
31 |
import org.gvsig.raster.dataset.io.PngWriter; |
32 |
import org.gvsig.raster.dataset.serializer.ColorInterpretationRmfSerializer; |
33 |
import org.gvsig.raster.dataset.serializer.GeoInfoRmfSerializer; |
34 |
import org.gvsig.raster.dataset.serializer.GeoPointListRmfSerializer; |
35 |
import org.gvsig.raster.dataset.serializer.ProjectionRmfSerializer; |
36 |
import org.gvsig.raster.dataset.serializer.StatisticsRmfSerializer; |
37 |
import org.gvsig.raster.datastruct.serializer.ColorTableRmfSerializer; |
38 |
import org.gvsig.raster.datastruct.serializer.HistogramRmfSerializer; |
39 |
import org.gvsig.raster.datastruct.serializer.NoDataRmfSerializer; |
40 |
import org.gvsig.raster.grid.filter.bands.ColorBalanceCMYManager; |
41 |
import org.gvsig.raster.grid.filter.bands.ColorBalanceRGBManager; |
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.bands.ToLumSaManager; |
46 |
import org.gvsig.raster.grid.filter.convolution.ConvolutionListManager; |
47 |
import org.gvsig.raster.grid.filter.correction.MedianListManager; |
48 |
import org.gvsig.raster.grid.filter.correction.ModeManager; |
49 |
import org.gvsig.raster.grid.filter.enhancement.BrightnessContrastListManager; |
50 |
import org.gvsig.raster.grid.filter.enhancement.EnhancementStretchListManager; |
51 |
import org.gvsig.raster.grid.filter.enhancement.EqualizationManager; |
52 |
import org.gvsig.raster.grid.filter.pansharp.PanSharpeningListManager; |
53 |
import org.gvsig.raster.grid.filter.segmentation.FirstDerivativeListManager; |
54 |
import org.gvsig.raster.grid.filter.statistics.StatisticsListManager; |
55 |
import org.gvsig.raster.util.PropertyEvent; |
56 |
import org.gvsig.raster.util.PropertyListener; |
57 |
import org.gvsig.raster.util.extensionPoints.ExtensionPoint; |
58 |
/**
|
59 |
* Clase principal de la libreria. En ella se definen variables globales con informaci?n
|
60 |
* de uso general, as? como acciones a realizar al arracar la librer?a. El m?todo que
|
61 |
* contiene las acciones de arranque es wakeUp. Las tareas principales de este m?todo
|
62 |
* son de registro de drivers de lectura y escritura y eliminaci?n del directorio de
|
63 |
* temporales.
|
64 |
*
|
65 |
* @author Nacho Brodin (nachobrodin@gmail.com)
|
66 |
*/
|
67 |
public class RasterLibrary { |
68 |
/**
|
69 |
* Control de librer?a ya inicializada.
|
70 |
*/
|
71 |
public static boolean wakeup = false; |
72 |
public static ArrayList writersClassList = new ArrayList(); |
73 |
|
74 |
/**
|
75 |
* En la generaci?n autom?tica de clases esta variable representa el n?mero de
|
76 |
* clases en las que se hace la divisi?n.
|
77 |
*/
|
78 |
public static int defaultNumberOfClasses = 64; |
79 |
|
80 |
/**
|
81 |
* En la genraci?n de las paletas de color, esta variable representa el n?mero
|
82 |
* de colores en las que se hace la divisi?n para generar la paleta nueva.
|
83 |
* Con esto conseguimos velocidad de procesamiento. Cuanto menor sea, peor
|
84 |
* ser? la calidad representada de la imagen.
|
85 |
*/
|
86 |
public static int defaultNumberOfColors = 256; |
87 |
/**
|
88 |
* Tama?o de bloque en los procesos que recorren un raster completo a base de ventanas con recorrido
|
89 |
* descendente. Esta variable indica la altura de dicho bloque. Por lo tanto cada bloque ser? de
|
90 |
* raster.width X blockHeight. Tipicamente recorridos de este tipo se usan para el calculo de estad?sticas,
|
91 |
* histogramas, salvado a raster, etc... Es importante para el buen funcionamiento que este bloque sea
|
92 |
* potencia de dos.
|
93 |
*/
|
94 |
public static int blockHeight = 512; |
95 |
|
96 |
//*************CACHE*******************
|
97 |
/**
|
98 |
* Tama?o aproximado de cach? en Megas. Si este valor es alto cabr?n muchas p?ginas en memoria
|
99 |
* a la vez y si es bajo cabr?n pocas. 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 cache en bytes. El tama?o aqu? especificado es aproximado. Este variar? dependiendo de los
|
102 |
* par?metros del raster a cachear ya que las p?ginas deben tener una altura potencia de 2.
|
103 |
*/
|
104 |
public static long cacheSize = 64; |
105 |
/**
|
106 |
* Tama?o m?ximo de la p?gina en Megas. Hay que tener en cuenta que al instanciar se convertira en bytes
|
107 |
* para su mejor tratamiento. Al llamar al constructor esta variable contendr? el tama?o exacto
|
108 |
* de la p?gina en bytes
|
109 |
*/
|
110 |
public static double pageSize = 4; |
111 |
/**
|
112 |
* N?mero de p?ginas que tiene cada conjunto de cach?
|
113 |
*/
|
114 |
public static int pagsPerGroup = 5; |
115 |
|
116 |
//*************PATHS*******************
|
117 |
|
118 |
/**
|
119 |
* Directorio temporal para la cach?. Si gastamos el mismo que andami este se ocupar? de gestionar su
|
120 |
* destrucci?n al cerrar gvSIG.
|
121 |
*/
|
122 |
public static String tempCacheDirectoryPath = System.getProperty("java.io.tmpdir") + File.separator + "tmp-andami"; |
123 |
/**
|
124 |
* Ruta o rutas donde busca jars con clases que incorporen elementos nuevos que extiendan
|
125 |
* otros ya existentes. Estos pueden ser drivers o filtros.
|
126 |
*/
|
127 |
public static String[] pathExtensions = {"." + File.separator}; |
128 |
|
129 |
/**
|
130 |
* Valor noData por defecto para la librer?a. En caso de no tener un valor asociado
|
131 |
* al raster se usar? este.
|
132 |
*/
|
133 |
public static double defaultNoDataValue = -99999; |
134 |
/**
|
135 |
* Contador global de las capas generadas para raster
|
136 |
*/
|
137 |
private static int layerCount = 1; |
138 |
private static ArrayList propetiesListeners = new ArrayList(); |
139 |
|
140 |
public static final int NODATATYPE_DISABLED = 0; |
141 |
public static final int NODATATYPE_LAYER = 1; |
142 |
public static final int NODATATYPE_USER = 2; |
143 |
/**
|
144 |
* Ejecuta las acciones necesarias para arrancar la librer?a.
|
145 |
*/
|
146 |
public static void wakeUp() { |
147 |
if (wakeup)
|
148 |
return;
|
149 |
|
150 |
// Punto de extensi?n para registro de drivers de lectura
|
151 |
ExtensionPoint.getExtensionPoint("RasterReader").setDescription("Raster Reader Classes"); |
152 |
|
153 |
// Registro de los drivers de lectura
|
154 |
GdalDriver.register(); |
155 |
ErmapperDriver.register(); |
156 |
MrSidDriver.register(); |
157 |
MemoryRasterDriver.register(); |
158 |
|
159 |
// Punto de extensi?n para registro de drivers de escritura
|
160 |
ExtensionPoint.getExtensionPoint("RasterWriter").setDescription("Raster Writer Classes"); |
161 |
|
162 |
// Registro de los drivers de escritura
|
163 |
GdalWriter.register(); |
164 |
ErmapperWriter.register(); |
165 |
JpegWriter.register(); |
166 |
PngWriter.register(); |
167 |
|
168 |
// Punto de extensi?n de los filtros
|
169 |
ExtensionPoint.getExtensionPoint("RasterFilter").setDescription("Raster Filter Classes"); |
170 |
|
171 |
// Invoca las llamadas est?ticas de cada clase para registrarlas en los puntos de extensi?n
|
172 |
BrightnessContrastListManager.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 |
ColorBalanceCMYManager.register(); |
182 |
ColorBalanceRGBManager.register(); |
183 |
ToLumSaManager.register(); |
184 |
EnhancementStretchListManager.register(); |
185 |
EqualizationManager.register(); |
186 |
ModeManager.register(); |
187 |
// EnhancementListManager.register();
|
188 |
// RGBToCMYKManager.register();
|
189 |
// Registrar los nuevos filtros del directorio
|
190 |
// registerClasses();
|
191 |
|
192 |
// Punto de extensi?n de los serializadores
|
193 |
ExtensionPoint.getExtensionPoint("Serializer").setDescription("Raster Serializer Classes"); |
194 |
|
195 |
// Registro de serializadores
|
196 |
ColorInterpretationRmfSerializer.register(); |
197 |
GeoInfoRmfSerializer.register(); |
198 |
GeoPointListRmfSerializer.register(); |
199 |
ProjectionRmfSerializer.register(); |
200 |
StatisticsRmfSerializer.register(); |
201 |
ColorTableRmfSerializer.register(); |
202 |
HistogramRmfSerializer.register(); |
203 |
NoDataRmfSerializer.register(); |
204 |
|
205 |
// Limpiamos el directorio temporal
|
206 |
cleanUpTempFiles(); |
207 |
//Crea el directorio de temporales
|
208 |
getTemporalPath(); |
209 |
wakeup = true;
|
210 |
} |
211 |
|
212 |
/**
|
213 |
* Elimina los ficheros del directorio temporal. Realizamos esta acci?n al
|
214 |
* levantar la librer?a.
|
215 |
*/
|
216 |
public static void cleanUpTempFiles() { |
217 |
try {
|
218 |
File tempDirectory = new File(tempCacheDirectoryPath); |
219 |
|
220 |
File[] files = tempDirectory.listFiles(); |
221 |
if (files != null) { |
222 |
for (int i = 0; i < files.length; i++) { |
223 |
// s?lo por si en un futuro se necesitan crear directorios temporales
|
224 |
if (files[i].isDirectory())
|
225 |
deleteDirectory(files[i]); |
226 |
files[i].delete(); |
227 |
} |
228 |
} |
229 |
tempDirectory.delete(); |
230 |
} catch (Exception e) { |
231 |
} |
232 |
} |
233 |
|
234 |
/**
|
235 |
* Recursive directory delete.
|
236 |
* @param f
|
237 |
*/
|
238 |
private static void deleteDirectory(File f) { |
239 |
File[] files = f.listFiles(); |
240 |
for (int i = 0; i < files.length; i++) { |
241 |
if (files[i].isDirectory())
|
242 |
deleteDirectory(files[i]); |
243 |
files[i].delete(); |
244 |
} |
245 |
} |
246 |
|
247 |
//******* Servicio de nombres de capas ?nicos **************
|
248 |
|
249 |
/**
|
250 |
* La gesti?n de nombres ?nicos en la generaci?n de capas se lleva de forma
|
251 |
* autom?tica. Cuando alguien crea una capa nueva, si esta no tiene nombre especifico,
|
252 |
* obtiene su nombre mediante este m?todo. La siguiente vez que se llame dar? un nombre
|
253 |
* distinto. El nombre de la capa ser? NewLayer_ seguido de un contador de actualizaci?n
|
254 |
* autom?tica cada vez que se usa.
|
255 |
* @return Nombre ?nico para la capa.
|
256 |
*/
|
257 |
public static String usesOnlyLayerName() { |
258 |
String oldValue = getOnlyLayerName();
|
259 |
String newValue = "NewLayer_" + (++RasterLibrary.layerCount); |
260 |
for (int i = 0; i < propetiesListeners.size(); i++) { |
261 |
if(propetiesListeners.get(i) instanceof PropertyListener) |
262 |
((PropertyListener)propetiesListeners.get(i)).actionValueChanged(new PropertyEvent(oldValue, "NewLayer", newValue, oldValue)); |
263 |
} |
264 |
return newValue;
|
265 |
} |
266 |
|
267 |
/**
|
268 |
* Obtiene el nombre ?nico de la siguiente capa sin actualizar el contador. Es
|
269 |
* solo para consulta. La siguiente vez que se llama a getOnlyLayerName o usesOnlyLayerName
|
270 |
* devolver? el mismo nomnbre.
|
271 |
* @return Nombre ?nico para la capa.
|
272 |
*/
|
273 |
public static String getOnlyLayerName() { |
274 |
return "NewLayer_" + RasterLibrary.layerCount; |
275 |
} |
276 |
|
277 |
/**
|
278 |
* A?adir un listener a la lista de eventos
|
279 |
* @param listener
|
280 |
*/
|
281 |
public static void addOnlyLayerNameListener(PropertyListener listener) { |
282 |
if (!propetiesListeners.contains(listener))
|
283 |
propetiesListeners.add(listener); |
284 |
} |
285 |
|
286 |
/**
|
287 |
* Elimina un listener de la lista de eventos
|
288 |
* @param listener
|
289 |
*/
|
290 |
public static void removeOnlyLayerNameListener(PropertyListener listener) { |
291 |
for (int i = 0; i < propetiesListeners.size(); i++) |
292 |
if(propetiesListeners.get(i) == listener)
|
293 |
propetiesListeners.remove(i); |
294 |
} |
295 |
|
296 |
//******* End: Servicio de nombres de capas ?nicos **************
|
297 |
|
298 |
/**
|
299 |
* Esta funci?n crea el directorio para temporales y devuelve el manejador
|
300 |
* del directorio
|
301 |
* @return
|
302 |
*/
|
303 |
static public File getTemporalFile() { |
304 |
File tempDirectory = new File(tempCacheDirectoryPath); |
305 |
if (!tempDirectory.exists())
|
306 |
tempDirectory.mkdir(); |
307 |
return tempDirectory;
|
308 |
} |
309 |
|
310 |
/**
|
311 |
* Esta funci?n crea el directorio para temporales y devuelve la ruta de este
|
312 |
* @return
|
313 |
*/
|
314 |
static public String getTemporalPath() { |
315 |
return getTemporalFile().getAbsolutePath();
|
316 |
} |
317 |
|
318 |
/*
|
319 |
private static Hashtable clasesJar = new Hashtable();
|
320 |
|
321 |
*
|
322 |
* Esta funci?n buscar? todos los jars en las rutas de pathExtensions y
|
323 |
* registrar? todos las clases registrables. En este momento hay posibilidad
|
324 |
* de registro de drivers y filtros.
|
325 |
*
|
326 |
private static void registerClasses() throws Exception {
|
327 |
RasterClassLoader loader = new RasterClassLoader();
|
328 |
|
329 |
//Cargamos sobre jarList todos los File correspondientes a los jar contenidos en pathExtensions
|
330 |
File[] jarList = null;
|
331 |
for (int iPath = 0; iPath < pathExtensions.length; iPath++) {
|
332 |
File directory = new File(pathExtensions[iPath]);
|
333 |
if (directory.isDirectory() && directory.canRead()) {
|
334 |
jarList = directory.listFiles(new FileFilter() {
|
335 |
public boolean accept(File pathname) {
|
336 |
return (pathname.getName().toUpperCase().endsWith(".JAR"));
|
337 |
}
|
338 |
});
|
339 |
}
|
340 |
}
|
341 |
|
342 |
//Creamos las URL
|
343 |
URL[] urls = new URL[jarList.length];
|
344 |
|
345 |
for (int j = 0; j < jarList.length; j++) {
|
346 |
try {
|
347 |
urls[j] = new URL("file:" + jarList[j]);
|
348 |
} catch (MalformedURLException e) {
|
349 |
Logger.getLogger(RasterLibrary.class.getName()).debug("Error formando la URL, jar incorrecto", e);
|
350 |
}
|
351 |
}
|
352 |
|
353 |
//Comprobamos que no haya clases repetidas
|
354 |
ZipFile[] jarFiles = new ZipFile[jarList.length];
|
355 |
for (int i = 0; i < jarList.length; i++) {
|
356 |
try {
|
357 |
jarFiles[i] = new ZipFile(jarList[i].getPath());
|
358 |
|
359 |
Enumeration entradas = jarFiles[i].entries();
|
360 |
|
361 |
while (entradas.hasMoreElements()) {
|
362 |
ZipEntry file = (ZipEntry) entradas.nextElement();
|
363 |
String fileName = file.getName();
|
364 |
|
365 |
if (!fileName.toLowerCase().endsWith(".class"))
|
366 |
continue;
|
367 |
|
368 |
fileName = fileName.substring(0, fileName.length() - 6).replace('/', '.');
|
369 |
|
370 |
if (clasesJar.get(fileName) != null) {
|
371 |
throw new JarException("CLASES REPETIDAS: " + fileName + " " + " en " +
|
372 |
jarFiles[i].getName() + " y en " + ((ZipFile) clasesJar.get(fileName)).getName());
|
373 |
}
|
374 |
|
375 |
clasesJar.put(fileName, jarFiles[i]);
|
376 |
}
|
377 |
} catch (ZipException e) {
|
378 |
throw new IOException(" Jar: " + jarList[i].getPath() + ": " + jarFiles[i]);
|
379 |
} catch (IOException e) {
|
380 |
throw e;
|
381 |
}
|
382 |
}
|
383 |
}
|
384 |
*/
|
385 |
} |