Statistics
| Revision:

gvsig-raster / org.gvsig.raster / tags / 2.0.0 / org.gvsig.raster.lib / org.gvsig.raster.lib.impl / src / main / java / org / gvsig / raster / impl / grid / filter / RasterFilterListManagerImpl.java @ 1708

History | View | Annotate | Download (16.2 KB)

1 21 nbrodin
/* gvSIG. Geographic Information System of the Valencian Government
2
 *
3
 * Copyright (C) 2007-2008 Infrastructures and Transports Department
4
 * of the Valencian Government (CIT)
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 2
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 */
22
package org.gvsig.raster.impl.grid.filter;
23
24
import java.lang.reflect.Constructor;
25
import java.lang.reflect.InvocationTargetException;
26
import java.util.ArrayList;
27
import java.util.Iterator;
28 1426 nbrodin
import java.util.List;
29 21 nbrodin
import java.util.regex.Matcher;
30
import java.util.regex.Pattern;
31
32 132 nbrodin
import org.gvsig.fmap.dal.coverage.RasterLocator;
33 21 nbrodin
import org.gvsig.fmap.dal.coverage.datastruct.Params;
34 125 nbrodin
import org.gvsig.fmap.dal.coverage.exception.FilterManagerException;
35 21 nbrodin
import org.gvsig.fmap.dal.coverage.exception.FilterTypeException;
36
import org.gvsig.fmap.dal.coverage.grid.RasterFilter;
37
import org.gvsig.fmap.dal.coverage.grid.RasterFilterList;
38
import org.gvsig.fmap.dal.coverage.grid.RasterFilterListManager;
39 130 nbrodin
import org.gvsig.fmap.dal.coverage.util.RasterUtils;
40 21 nbrodin
import org.gvsig.tools.ToolsLocator;
41
import org.gvsig.tools.extensionpoint.ExtensionPoint;
42
import org.gvsig.tools.extensionpoint.ExtensionPointManager;
43 125 nbrodin
import org.gvsig.tools.extensionpoint.ExtensionPoint.Extension;
44 21 nbrodin
45
/*
46
 * TODO: FUNCIONALIDAD: Anulada las estad?sticas. Hay que incluirlas de nuevo.
47
 */
48
/**
49
 * Esta clase es de la parte cliente y es la encargada de la gesti?n de la pila
50
 * de filtros. Cada tipo de filtro o conjunto de tipos de filtro deben tener un
51
 * gestor que implementa IRasterFilterManager. Esos gestores deben registrarse
52
 * en esta clase con la funci?n addClassListManager. Este registro puede hacerse
53
 * desde esta misma clase o desde una extensi?n. Un cliente que desee aplicar un
54
 * filtro deber? introducirlo en la lista usando para ello las funciones que su
55
 * manager de filtros le ofrece. Adem?s se encarga de otras funciones como la
56
 * conversi?n de un filtro a cadena de Strings y la recuperaci?n desde cadena de
57
 * Strings y el control de tipos de la salida de un raster de la lista con la
58
 * entrada del siguiente filtro.
59
 *
60
 * @author Nacho Brodin (nachobrodin@gmail.com)
61
 */
62 125 nbrodin
public class RasterFilterListManagerImpl {
63 755 nbrodin
        protected RasterFilterList                rasterFilterList       = null;
64 1426 nbrodin
        protected List<String>                        filterList             = null;
65
        private List<RasterFilterListManager>
66 755 nbrodin
                                            managers               = new ArrayList<RasterFilterListManager>();
67 21 nbrodin
68
        /**
69
         * Constructor
70
         * @param filterStack
71
         */
72 30 nbrodin
        @SuppressWarnings("unchecked")
73 21 nbrodin
        public RasterFilterListManagerImpl(RasterFilterList filterStack) {
74
                this.rasterFilterList = filterStack;
75
76
                // Cargamos el manager con los gestores de drivers registrados
77 30 nbrodin
                ExtensionPointManager extensionPoints = ToolsLocator.getExtensionPointManager();
78
                ExtensionPoint point = extensionPoints.get("RasterFilter");
79 21 nbrodin
                Iterator iterator = point.iterator();
80
                while (iterator.hasNext()) {
81
                        ExtensionPoint.Extension entry = (ExtensionPoint.Extension) iterator
82
                                        .next();
83
                        if (entry != null) {
84
                                Class RasterClass = entry.getExtension();
85
                                Object obj = RasterFilterListManagerImpl.loadClass(RasterClass, this);
86
                                if (obj != null)
87 755 nbrodin
                                        managers.add((RasterFilterListManager)obj);
88 21 nbrodin
                        }
89
                }
90
        }
91
92
        /**
93
         * Controla que los tipos de los filtros de la pila sean correctos, es decir,
94
         * que el tipo de salida de un filtro de salida coincida con el tipo de la
95
         * entrada del siguiente. En caso de no ser as? crea el filtro de tipo
96
         * adecuado y lo sustituye en el no coincidente. Esto es necesario ya que en
97
         * la eliminaci?n de filtros puede quedarse en inconsistencia de tipos.
98
         */
99
        public void controlTypes() throws FilterTypeException {
100 132 nbrodin
                RasterUtils util = RasterLocator.getManager().getRasterUtils();
101 30 nbrodin
                ArrayList<Exception> exceptions = new ArrayList<Exception>();
102 21 nbrodin
                for (int i = 0; i < rasterFilterList.lenght(); i++) {
103
                        String classFilter = null, packageFilter = null, oldClass = null;
104
                        try {
105
                                RasterFilter rf = rasterFilterList.get(i);
106
                                if (rf == null)
107
                                        return;
108
                                classFilter = rf.getClass().toString();
109
                                packageFilter = classFilter.substring(classFilter.indexOf(" ") + 1, classFilter.lastIndexOf("."));
110
                                oldClass = classFilter.substring(classFilter.lastIndexOf(".") + 1, classFilter.length());
111
                        } catch (ArrayIndexOutOfBoundsException ex) {
112
                                return;
113
                        } catch (NullPointerException ex) {
114
                                return;
115
                        }
116
117
                        // Para el primer filtro comprobamos con el tipo de dato de entrada a la pila
118
                        if (i == 0) {
119
                                if (rasterFilterList.getInitDataType() != rasterFilterList.get(i).getInRasterDataType()) {
120 132 nbrodin
                                        Pattern p = Pattern.compile(util.typesToString(rasterFilterList.get(i).getInRasterDataType()));
121 21 nbrodin
                                        Matcher m = p.matcher(oldClass);
122 132 nbrodin
                                        String newClass = m.replaceAll(util.typesToString(rasterFilterList.getInitDataType()));
123 21 nbrodin
                                        String strPackage = packageFilter + "." + newClass;
124
125
                                        renewFilterFromControlTypes(strPackage, i, exceptions);
126
                                }
127
128
                                // Desde el filtro 2 en adelante se compara la salida de uno con la entrada del siguiente
129
                        } else if (rasterFilterList.get(i - 1).getOutRasterDataType() != rasterFilterList.get(i).getInRasterDataType()) {
130 132 nbrodin
                                Pattern p = Pattern.compile(util.typesToString(rasterFilterList.get(i).getInRasterDataType()));
131 21 nbrodin
                                Matcher m = p.matcher(oldClass);
132 132 nbrodin
                                String newClass = m.replaceAll(util.typesToString(rasterFilterList.get(i - 1).getOutRasterDataType()));
133 21 nbrodin
                                String strPackage = packageFilter + "." + newClass;
134
135
                                renewFilterFromControlTypes(strPackage.trim(), i, exceptions);
136
                        }
137
                }
138
139
                if (exceptions.size() > 0)
140
                        throw new FilterTypeException("");
141
142
        }
143
144
        /**
145
         * Reemplaza un filtro segun su nombre a la lista de filtros, util para cambiar
146
         * el tipo de datos de un filtro en la pila de filtros.
147
         * @param nameFilter
148
         * @param pos
149
         * @param exceptions
150
         */
151 1426 nbrodin
        private void renewFilterFromControlTypes(String nameFilter, int pos, List<Exception> exceptions) {
152 21 nbrodin
                try {
153 169 nbrodin
                        RasterFilter newFilter = rasterFilterList.createEmptyFilter(nameFilter);
154
155 151 nbrodin
                        newFilter.setParams(rasterFilterList.get(pos).getParams());
156
                        if (newFilter.getParams().get("filterName") != null)
157
                                newFilter.setName((String) newFilter.getParams().get("filterName"));
158 21 nbrodin
                        else
159
                                newFilter.setName(rasterFilterList.get(pos).getName());
160
                        rasterFilterList.replace(newFilter, pos);
161
                } catch (FilterTypeException e) {
162
                        exceptions.add(e);
163
                }
164
        }
165
166
        /**
167
         * M?todo que devuelve true si el tipo de filtro pasado por par?metro est? en
168
         * la pila y false si no lo est?.
169
         * @param filter Tipo de filtro a comprobar
170
         * @return true si est? en la pila y false si no lo est?
171
         */
172
        public boolean isActive(String name) {
173
                return rasterFilterList.isActive(name);
174
        }
175
176
        /**
177
         * Elimina los filtros de la pila de un determinado tipo
178
         *
179
         * @param type Tipo de filtro a eliminar
180
         * @throws FilterTypeException
181
         */
182
        public void removeFilter(String name) throws FilterTypeException {
183
                rasterFilterList.remove(name);
184
                this.controlTypes();
185
        }
186
187 1426 nbrodin
        public List<String> getStringsFromFilterList() {
188 21 nbrodin
                filterList = new ArrayList<String>();
189
                for (int i = 0; i < rasterFilterList.lenght(); i++) {
190
                        RasterFilter rf = rasterFilterList.get(i);
191
192
                        // Se recorren todos los managers registrados comprobando si corresponde a
193
                        // la clase del filtro
194
                        for (int j = 0; j < managers.size(); j++)
195
                                filterList = ((RasterFilterListManager) managers.get(j)).getStringsFromFilterList(filterList, rf);
196
                }
197
198
                return filterList;
199
        }
200
201
        /*
202
         * (non-Javadoc)
203
         * @see org.gvsig.raster.grid.filter.IRasterFilterListManager#createStackFromStrings(java.util.ArrayList, java.lang.String, int)
204
         */
205 30 nbrodin
        @SuppressWarnings("unchecked")
206 1426 nbrodin
        public int createStackFromStrings(List filters, String fil, int filteri) {
207 21 nbrodin
                return filteri;
208
        }
209 128 nbrodin
210
        /**
211
         * Crea una pila de filtros a partir de un Array de Strings. Cada elemento del array debe
212
         * tener la forma elemento=valor.
213
         * @param filters
214
         * @throws FilterTypeException
215
         */
216 1426 nbrodin
        public static void createFilterListFromStrings(RasterFilterList rasterFilterList, List<String> f) throws FilterTypeException {
217 128 nbrodin
                new RasterFilterListManagerImpl(rasterFilterList).createFilterListFromStrings(f, new Integer(0));
218
        }
219 21 nbrodin
220
        /**
221
         * Crea una pila de filtros a partir de un Array de Strings. Cada elemento del array debe
222
         * tener la forma elemento=valor.
223
         * @param filters
224
         * @throws FilterTypeException
225
         */
226 1426 nbrodin
        public void createFilterListFromStrings(List<String> f) throws FilterTypeException {
227 21 nbrodin
                createFilterListFromStrings(f, new Integer(0));
228
        }
229
230
        /**
231
         * Crea una pila de filtros a partir de un Array de Strings. Cada elemento del array debe
232
         * tener la forma elemento=valor.
233
         * @param pos Posici?n desde la cual se empieza a analizar.
234
         * @param filters
235
         * @throws FilterTypeException
236
         */
237 132 nbrodin
        @SuppressWarnings("unchecked")
238 1426 nbrodin
        private void createFilterListFromStrings(List<String> f, Integer pos) throws FilterTypeException {
239
                List<String> filters = null;
240
                if(f instanceof ArrayList) {
241
                        filters = (List<String>)((ArrayList<String>) f).clone();
242
                } else {
243
                        filters = new ArrayList<String>();
244
                        for (int i = 0; i < f.size(); i++) {
245
                                filters.add(f.get(i));
246
                        }
247
                }
248 21 nbrodin
                rasterFilterList.clear();
249
250
                int filteri = pos.intValue();
251
252
                // Busca un filtro activo y despu?s todas las propiedades que necesita ese
253
                // filtro para ser creado. Una vez las tiene a?ade en la pila el tipo de
254
                // filtro.
255
                while ((filters.size() > 0) && (filteri < filters.size())) {
256
                        String fil = (String) filters.get(filteri);
257
258
                        for (int j = 0; j < managers.size(); j++)
259
                                try {
260
                                        filteri = ((RasterFilterListManager) managers.get(j)).createFilterListFromStrings(filters, fil, filteri);
261
                                } catch (NullPointerException e) {
262
                                }
263
264
                        filteri++;
265
                }
266
        }
267
268
        /**
269
         * Obtiene el elemento de una cadena de la forma elemento=valor
270
         * @param cadena
271
         * @return
272
         */
273
        public static String getElem(String cadena) {
274
                if (cadena != null)
275
                        return cadena.substring(0, cadena.indexOf("="));
276
                else
277
                        return null;
278
        }
279
280
        /**
281
         * Obtiene el valor de una cadena de la forma elemento=valor
282
         * @param cadena
283
         * @return
284
         */
285
        public static String getValue(String cadena) {
286
                if (cadena != null)
287
                        return cadena.substring(cadena.indexOf("=") + 1, cadena.length());
288
                else
289
                        return null;
290
        }
291
292
        /**
293
         * Carga una clase pasada por par?metro. Como argumento del constructor de la
294
         * clase se pasar? un RasterFilterStackManager. Esto es usado para instanciar
295
         * los gestores de filtros registrados
296
         * @param clase Clase a instanciar
297
         * @param stackManager Par?metro del constructor de la clase a instanciar
298
         * @return Objeto que corresponde a la instancia de la clase pasada.
299
         */
300 30 nbrodin
        @SuppressWarnings("unchecked")
301 125 nbrodin
        public static Object loadClass(Class clase, RasterFilterListManagerImpl stackManager) {
302 21 nbrodin
                Object obj = null;
303
                try {
304 152 nbrodin
                        try {
305
                                Constructor hazNuevo = clase.getConstructor(new Class[]{ RasterFilterList.class });
306
                                obj = hazNuevo.newInstance(new Object[]{stackManager.getFilterList()});
307
                        } catch (NoSuchMethodException e) {
308
                                Constructor hazNuevo = clase.getConstructor(new Class[]{ RasterFilterListManagerImpl.class });
309
                                obj = hazNuevo.newInstance(new Object[]{stackManager});
310
                        }
311 21 nbrodin
                } catch (SecurityException e) {
312
                        e.printStackTrace();
313
                } catch (NoSuchMethodException e) {
314
                        e.printStackTrace();
315
                } catch (IllegalArgumentException e) {
316
                        e.printStackTrace();
317
                } catch (InstantiationException e) {
318
                        e.printStackTrace();
319
                } catch (IllegalAccessException e) {
320
                        e.printStackTrace();
321
                } catch (InvocationTargetException e) {
322
                        e.printStackTrace();
323
                }
324
                return obj;
325
        }
326
327
        /*
328
         * (non-Javadoc)
329
         * @see org.gvsig.fmap.dal.coverage.grid.RasterFilterListManager#getFilterList()
330
         */
331
        public RasterFilterList getFilterList() {
332
                return rasterFilterList;
333
        }
334 125 nbrodin
335
        /*
336
         * (non-Javadoc)
337
         * @see org.gvsig.fmap.dal.coverage.grid.RasterFilterListManager#getManagerByID(java.lang.String)
338
         */
339
        @SuppressWarnings("unchecked")
340
        public RasterFilterListManager getManagerByID(String id) throws FilterManagerException {
341
                // Cargamos el manager con los gestores de drivers registrados
342
                ExtensionPointManager extensionPoints = ToolsLocator.getExtensionPointManager();
343
                ExtensionPoint point = extensionPoints.get("RasterFilter");
344
                Extension ext = point.get(id);
345
                if (ext != null) {
346
                        Class clase = ext.getExtension();
347 142 nbrodin
                        Class [] args = {RasterFilterListManagerImpl.class};
348 125 nbrodin
                        try {
349
                                Constructor hazNuevo = clase.getConstructor(args);
350
                                Object [] args2 = {this};
351
                                return (RasterFilterListManager) hazNuevo.newInstance(args2);
352
                        } catch (SecurityException e) {
353
                                throw new FilterManagerException("Error SecurityException in open", e);
354
                        } catch (NoSuchMethodException e) {
355
                                throw new FilterManagerException("Error NoSuchMethodException in open", e);
356
                        } catch (IllegalArgumentException e) {
357
                                throw new FilterManagerException("Error IllegalArgumentException in open", e);
358
                        } catch (InstantiationException e) {
359
                                throw new FilterManagerException("Error InstantiationException in open", e);
360
                        } catch (IllegalAccessException e) {
361
                                throw new FilterManagerException("Error IllegalAccessException in open", e);
362
                        } catch (InvocationTargetException e) {
363
                                throw new FilterManagerException("Error opening this image with " + clase, e);
364
                        }
365
                }
366
                return null;
367
        }
368 21 nbrodin
369
        /**
370
         * Obtiene el manager registrado a partir de la clase
371
         * @return
372
         */
373 30 nbrodin
        @SuppressWarnings("unchecked")
374 21 nbrodin
        public RasterFilterListManager getManagerByClass(Class c) {
375
                for (int j = 0; j < managers.size(); j++)
376
                        if (managers.get(j).getClass().equals(c))
377
                                return (RasterFilterListManager) managers.get(j);
378
                return null;
379
        }
380
381
        /**
382
         * Obtiene el manager registrado a partir de la clase de un filtro
383
         * @return
384
         */
385 30 nbrodin
        @SuppressWarnings("unchecked")
386 21 nbrodin
        public RasterFilterListManager getManagerByFilterClass(Class c) {
387 149 nbrodin
                for (int i = 0; i < managers.size(); i++) {
388
                        RasterFilterListManager localMan = ((RasterFilterListManager) managers.get(i));
389
                        for (int j = 0; j < localMan.getRasterFilterList().size(); j++) {
390
                                Class f = (Class)localMan.getRasterFilterList().get(j);
391 761 nbrodin
                                if (f.isAssignableFrom(c))//(f.equals(c))
392 149 nbrodin
                                        return localMan;
393
                        }
394
                }
395 21 nbrodin
                return null;
396
        }
397
398 1426 nbrodin
        public List<Class<?>> getRasterFilterList() {
399
                List<Class<?>> filters = new ArrayList<Class<?>>();
400 21 nbrodin
                for (int i = 0; i < managers.size(); i++) {
401 1427 nbrodin
                        List<Class<?>> auxFilters = managers.get(i).getRasterFilterList();
402 21 nbrodin
                        for (int j = 0; j < auxFilters.size(); j++)
403
                                filters.add(auxFilters.get(j));
404
                }
405
                return filters;
406
        }
407 1427 nbrodin
408
        public List<Class<?>> getRasterFilterListByDataType(int dataType) {
409
                List<Class<?>> filters = new ArrayList<Class<?>>();
410
                for (int i = 0; i < managers.size(); i++) {
411
                        RasterFilterListManager man = managers.get(i);
412
                        if(man.isDataTypeSupported(dataType)) {
413
                                List<Class<?>> auxFilters = man.getRasterFilterList();
414
                                for (int j = 0; j < auxFilters.size(); j++)
415
                                        filters.add(auxFilters.get(j));
416
                        }
417
                }
418
                return filters;
419
        }
420 21 nbrodin
421 30 nbrodin
        /*
422
         * (non-Javadoc)
423
         * @see org.gvsig.fmap.dal.coverage.grid.RasterFilterListManager#addFilter(java.lang.Class, org.gvsig.fmap.dal.coverage.datastruct.Params)
424
         */
425
        @SuppressWarnings("unchecked")
426 21 nbrodin
        public void addFilter(Class classFilter, Params params)
427
                        throws FilterTypeException {
428
                // TODO Auto-generated method stub
429
430
        }
431 125 nbrodin
432
        public void addFilter(Params params) throws FilterTypeException {
433
                throw new FilterTypeException("Method not implemented in globar manager");
434
        }
435 21 nbrodin
436 1426 nbrodin
        public int createFilterListFromStrings(List<String> filters,
437 21 nbrodin
                        String fil, int filteri) throws FilterTypeException {
438
                // TODO Auto-generated method stub
439
                return 0;
440
        }
441
442 1426 nbrodin
        public List<String> getStringsFromFilterList(
443
                        List<String> filterList, RasterFilter rf) {
444 21 nbrodin
                // TODO Auto-generated method stub
445
                return null;
446
        }
447 1055 nbrodin
448
        /*
449
         * (non-Javadoc)
450
         * @see java.lang.Object#finalize()
451
         */
452
        protected void finalize() throws Throwable {
453
                rasterFilterList           = null;
454
                if(managers != null) {
455
                        managers.clear();
456
                        managers = null;
457
                }
458
                if(filterList != null) {
459
                        filterList.clear();
460
                        filterList = null;
461
                }
462
                super.finalize();
463
        }
464 21 nbrodin
}