Statistics
| Revision:

gvsig-raster / org.gvsig.raster / trunk / org.gvsig.raster / org.gvsig.raster.lib / org.gvsig.raster.lib.impl / src / main / java / org / gvsig / raster / impl / grid / filter / RasterFilterListManagerImpl.java @ 1426

History | View | Annotate | Download (15.8 KB)

1
/* 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
import java.util.List;
29
import java.util.regex.Matcher;
30
import java.util.regex.Pattern;
31

    
32
import org.gvsig.fmap.dal.coverage.RasterLocator;
33
import org.gvsig.fmap.dal.coverage.datastruct.Params;
34
import org.gvsig.fmap.dal.coverage.exception.FilterManagerException;
35
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
import org.gvsig.fmap.dal.coverage.util.RasterUtils;
40
import org.gvsig.tools.ToolsLocator;
41
import org.gvsig.tools.extensionpoint.ExtensionPoint;
42
import org.gvsig.tools.extensionpoint.ExtensionPointManager;
43
import org.gvsig.tools.extensionpoint.ExtensionPoint.Extension;
44

    
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
public class RasterFilterListManagerImpl {
63
        protected RasterFilterList                rasterFilterList       = null;
64
        protected List<String>                        filterList             = null;
65
        private List<RasterFilterListManager>                        
66
                                            managers               = new ArrayList<RasterFilterListManager>();
67

    
68
        /**
69
         * Constructor
70
         * @param filterStack
71
         */
72
        @SuppressWarnings("unchecked")
73
        public RasterFilterListManagerImpl(RasterFilterList filterStack) {
74
                this.rasterFilterList = filterStack;
75

    
76
                // Cargamos el manager con los gestores de drivers registrados
77
                ExtensionPointManager extensionPoints = ToolsLocator.getExtensionPointManager();
78
                ExtensionPoint point = extensionPoints.get("RasterFilter");
79
                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
                                        managers.add((RasterFilterListManager)obj);
88
                        }
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
                RasterUtils util = RasterLocator.getManager().getRasterUtils();
101
                ArrayList<Exception> exceptions = new ArrayList<Exception>();
102
                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
                                        Pattern p = Pattern.compile(util.typesToString(rasterFilterList.get(i).getInRasterDataType()));
121
                                        Matcher m = p.matcher(oldClass);
122
                                        String newClass = m.replaceAll(util.typesToString(rasterFilterList.getInitDataType()));
123
                                        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
                                Pattern p = Pattern.compile(util.typesToString(rasterFilterList.get(i).getInRasterDataType()));
131
                                Matcher m = p.matcher(oldClass);
132
                                String newClass = m.replaceAll(util.typesToString(rasterFilterList.get(i - 1).getOutRasterDataType()));
133
                                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
        private void renewFilterFromControlTypes(String nameFilter, int pos, List<Exception> exceptions) {
152
                try {
153
                        RasterFilter newFilter = rasterFilterList.createEmptyFilter(nameFilter);
154
                        
155
                        newFilter.setParams(rasterFilterList.get(pos).getParams());
156
                        if (newFilter.getParams().get("filterName") != null)
157
                                newFilter.setName((String) newFilter.getParams().get("filterName"));
158
                        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
        public List<String> getStringsFromFilterList() {
188
                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
        @SuppressWarnings("unchecked")
206
        public int createStackFromStrings(List filters, String fil, int filteri) {
207
                return filteri;
208
        }
209
        
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
        public static void createFilterListFromStrings(RasterFilterList rasterFilterList, List<String> f) throws FilterTypeException {
217
                new RasterFilterListManagerImpl(rasterFilterList).createFilterListFromStrings(f, new Integer(0));
218
        }
219

    
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
        public void createFilterListFromStrings(List<String> f) throws FilterTypeException {
227
                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
        @SuppressWarnings("unchecked")
238
        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
                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
        @SuppressWarnings("unchecked")
301
        public static Object loadClass(Class clase, RasterFilterListManagerImpl stackManager) {
302
                Object obj = null;
303
                try {
304
                        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
                } 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
        
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
                        Class [] args = {RasterFilterListManagerImpl.class};
348
                        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

    
369
        /**
370
         * Obtiene el manager registrado a partir de la clase
371
         * @return
372
         */
373
        @SuppressWarnings("unchecked")
374
        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
        @SuppressWarnings("unchecked")
386
        public RasterFilterListManager getManagerByFilterClass(Class c) {
387
                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
                                if (f.isAssignableFrom(c))//(f.equals(c))
392
                                        return localMan;
393
                        }
394
                }
395
                return null;
396
        }
397

    
398
        public List<Class<?>> getRasterFilterList() {
399
                List<Class<?>> filters = new ArrayList<Class<?>>();
400
                for (int i = 0; i < managers.size(); i++) {
401
                        List<Class<?>> auxFilters = ((RasterFilterListManager) managers.get(i)).getRasterFilterList();
402
                        for (int j = 0; j < auxFilters.size(); j++)
403
                                filters.add(auxFilters.get(j));
404
                }
405
                return filters;
406
        }
407

    
408
        /*
409
         * (non-Javadoc)
410
         * @see org.gvsig.fmap.dal.coverage.grid.RasterFilterListManager#addFilter(java.lang.Class, org.gvsig.fmap.dal.coverage.datastruct.Params)
411
         */
412
        @SuppressWarnings("unchecked")
413
        public void addFilter(Class classFilter, Params params)
414
                        throws FilterTypeException {
415
                // TODO Auto-generated method stub
416
                
417
        }
418
        
419
        public void addFilter(Params params) throws FilterTypeException {
420
                throw new FilterTypeException("Method not implemented in globar manager");
421
        }
422

    
423
        public int createFilterListFromStrings(List<String> filters,
424
                        String fil, int filteri) throws FilterTypeException {
425
                // TODO Auto-generated method stub
426
                return 0;
427
        }
428

    
429
        public List<String> getStringsFromFilterList(
430
                        List<String> filterList, RasterFilter rf) {
431
                // TODO Auto-generated method stub
432
                return null;
433
        }
434
        
435
        /*
436
         * (non-Javadoc)
437
         * @see java.lang.Object#finalize()
438
         */
439
        protected void finalize() throws Throwable {
440
                rasterFilterList           = null;
441
                if(managers != null) {
442
                        managers.clear();
443
                        managers = null;
444
                }
445
                if(filterList != null) {
446
                        filterList.clear();
447
                        filterList = null;
448
                }
449
                super.finalize();
450
        }
451
}