Statistics
| Revision:

gvsig-raster / org.gvsig.raster.tools / branches / org.gvsig.raster.tools_dataaccess_refactoring / org.gvsig.raster.tools.app.basic / src / main / java / org / gvsig / raster / tools / app / basic / raster / process / FilterProcess.java @ 2331

History | View | Annotate | Download (12 KB)

1
package org.gvsig.raster.tools.app.basic.raster.process;
2

    
3
import java.io.IOException;
4
import java.util.ArrayList;
5
import java.util.List;
6

    
7
import javax.swing.SwingUtilities;
8

    
9
import org.cresques.cts.IProjection;
10
import org.gvsig.fmap.dal.coverage.RasterLocator;
11
import org.gvsig.fmap.dal.coverage.RasterManager;
12
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
13
import org.gvsig.fmap.dal.coverage.datastruct.NoData;
14
import org.gvsig.fmap.dal.coverage.exception.FilterManagerException;
15
import org.gvsig.fmap.dal.coverage.exception.FilterTypeException;
16
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
17
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
18
import org.gvsig.fmap.dal.coverage.exception.QueryException;
19
import org.gvsig.fmap.dal.coverage.exception.ROIException;
20
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
21
import org.gvsig.fmap.dal.coverage.filter.FilterLoader;
22
import org.gvsig.fmap.dal.coverage.grid.RasterFilterList;
23
import org.gvsig.fmap.dal.coverage.grid.RasterFilterListManager;
24
import org.gvsig.fmap.dal.coverage.store.DataServerWriter;
25
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
26
import org.gvsig.fmap.dal.coverage.store.RasterQuery;
27
import org.gvsig.fmap.dal.coverage.store.RasterWriter;
28
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
29
import org.gvsig.fmap.dal.coverage.store.props.Transparency;
30
import org.gvsig.fmap.dal.exception.CloseException;
31
import org.gvsig.i18n.Messages;
32
import org.gvsig.raster.fmap.layers.FLyrRaster;
33
import org.gvsig.raster.roi.ROI;
34
import org.gvsig.raster.tools.app.basic.raster.bean.previewbase.ParamStruct;
35

    
36
/**
37
 * Clase donde se hara todo el proceso de aplicar una lista de filtros a una
38
 * capa. Muestra una ventana de dialogo de incremento informativa.
39
 *
40
 * @author BorSanZa - Borja S?nchez Zamorano 
41
 */
42
public class FilterProcess extends RasterProcess {
43
        private String                   filename         = "";
44
        private RasterDataStore          rasterDataSource = null;
45
        private ArrayList<ParamStruct>   listFilterUsed   = null;
46

    
47
        private RasterFilterList         rasterFilterList = null;
48
        private RasterWriter             geoRasterWriter  = null;
49
        private FLyrRaster               lyr              = null;
50
        private RasterManager            rManager         = RasterLocator.getManager();
51

    
52
        public void init() {
53
                filename = getStringParam("filename");
54
                listFilterUsed = (ArrayList) getParam("listfilterused");
55
                lyr = (FLyrRaster)getParam("layer");
56
                rasterDataSource = lyr.getDataStore();
57
        }
58

    
59
        /**
60
         * Devuelve una interpretacion de color. Es usado cuando no conseguimos un
61
         * rendering y no podemos saber que interpretacion l?gica ten?a antes.
62
         * @param geoRasterWriter
63
         */
64
        private ColorInterpretation getColorIntepretation(Buffer buffer, RasterFilterList filterList) {
65
                ColorInterpretation colorInterpretation = null;
66

    
67
                do {
68
                        // Si tiene una tabla de color asignamos las tres bandas
69
                        if (filterList.isActive("colortable")) {
70
                                colorInterpretation = rManager.getDataStructFactory().createColorInterpretation(
71
                                                new String[] { 
72
                                                                ColorInterpretation.RED_BAND, 
73
                                                                ColorInterpretation.GREEN_BAND, 
74
                                                                ColorInterpretation.BLUE_BAND,
75
                                                                ColorInterpretation.ALPHA_BAND 
76
                                                                });
77
                                break;
78
                        }
79

    
80
                        // Si el numero de bandas coincide asignamos la misma interpretacion que tenia antes
81
                        if (buffer.getBandCount() == rasterDataSource.getBandCount()) {
82
                                colorInterpretation = rasterDataSource.getColorInterpretation();
83
                                break;
84
                        }
85

    
86
                        String[] colorInterp = new String[rasterDataSource.getColorInterpretation().getValues().length];
87

    
88
                        for (int i = 0; i < rasterDataSource.getColorInterpretation().getValues().length; i++) {
89
                                if (rasterDataSource.getColorInterpretation().getValues()[i].equals(ColorInterpretation.UNDEF_BAND)) {
90
                                        colorInterp[i] = ColorInterpretation.GRAY_BAND;
91
                                        continue;
92
                                }
93
                                colorInterp[i] = rasterDataSource.getColorInterpretation().getValues()[i];
94
                        }
95
                        colorInterpretation = rManager.getDataStructFactory().createColorInterpretation(colorInterp);
96
                } while (false);
97

    
98
                return colorInterpretation;
99
        }
100
        
101
        public void process() throws ProcessInterruptedException, ProcessException {
102
                DataServerWriter writerBufferServer = null;
103
                if(lyr != null)
104
                        lyr.setReadingData(Thread.currentThread().getId() + "");
105

    
106
                RasterDataStore dstoreCopy = null;
107
                RasterQuery query          = null;
108
                Buffer buffer              = null;
109
                Buffer buff                = null;
110
                Buffer alpha               = null;
111
                try {
112
                        insertLineLog(Messages.getText("leyendo_raster"));
113
                        
114
                        //Creaci?n del BufferFactory
115
                        dstoreCopy = rasterDataSource.newNotTiledDataStore();
116
                        query = rManager.createQuery();
117
                        //if (!RasterBuffer.loadInMemory(dsetCopy))
118
                        query.setReadOnly(true);
119

    
120
                        //Asignaci?n de bandas
121
                        int[] renderBands = lyr.getRender().getRenderColorInterpretation().buildRenderBands();
122
                        if (renderBands != null) {
123
                                // Si es gris, se reduce a una sola banda
124
                                if ((renderBands.length == 3) && (renderBands[0] == renderBands[1]) && (renderBands[1] == renderBands[2])) 
125
                                        renderBands = new int[] { renderBands[0] };
126
                                query.setDrawableBands(renderBands);
127
                        } else
128
                                query.setAllDrawableBands();
129

    
130
                        query.setAreaOfInterest();
131
                        
132
                        buff = dstoreCopy.query(query);
133
                        if(buff.isReadOnlyBuffer()) 
134
                                buff.addDrawableBands(renderBands);
135
                        
136
                        insertLineLog(Messages.getText("aplicando_filtros"));
137

    
138
                        Transparency processTransparency = dstoreCopy.getTransparency().cloneTransparency();
139
                        processTransparency.setColorInterpretation(lyr.getRender().getRenderColorInterpretation().cloneColorInterpretation());
140
                        
141
                        List<ROI> roi = null;
142
                        try {
143
                                IProjection proj = dstoreCopy.getProjection();
144
                                if(proj == null)
145
                                        proj = lyr.getMapContext().getProjection();
146
                                roi = (List<ROI>)dstoreCopy.getRois(proj);
147
                        } catch (ROIException e) {
148
                        }
149
                        
150
                        rasterFilterList = rManager.createEmptyFilterList(dstoreCopy.getDataType()[0]);
151
                        FilterLoader filterLoader = RasterLocator.getManager().createFilterLoader(rasterFilterList);
152
                        filterLoader.addSrcBandCount(dstoreCopy.getBandCount());
153
                        filterLoader.addSrcDataType(dstoreCopy.getDataType()[0]);
154
                        filterLoader.addSrcStatistics(dstoreCopy.getStatistics());
155
                        filterLoader.addSrcROI(roi);
156
                        filterLoader.addTransparency(processTransparency);
157
                        addSelectedFilters(rasterFilterList, listFilterUsed);
158
                        buffer = filterLoader.applyFilters(buff);
159
                        
160
                        insertLineLog(Messages.getText("guardando_capa"));
161

    
162
                        writerBufferServer = rManager.createDataServerWriter();
163
                        writerBufferServer.setBuffer(buffer, -1);
164
                        // TODO: FUNCIONALIDAD: Poner los getWriter con la proyecci?n del fichero fuente
165

    
166
                        ColorInterpretation colorInterpretation = getColorInterpretation(buffer.getBandCount(), buffer.getDataType());
167
                        
168
                        geoRasterWriter = rManager.createWriter(writerBufferServer, 
169
                                        filename,
170
                                        buffer.getBandCount(), 
171
                                        rasterDataSource.getAffineTransform(), 
172
                                        buffer.getWidth(), 
173
                                        buffer.getHeight(), 
174
                                        buffer.getDataType(), 
175
                                        rManager.createWriter(filename).getParams(), 
176
                                        null);
177
                        
178
                        if (lyr.getRender() == null)
179
                                colorInterpretation = getColorIntepretation(buffer, rasterFilterList);
180

    
181
                        geoRasterWriter.setColorBandsInterpretation(colorInterpretation.getValues());
182

    
183
                        geoRasterWriter.dataWrite();
184
                        geoRasterWriter.writeClose();
185
                        geoRasterWriter = null;
186
                        
187
                        // Guardamos en el RMF el valor NoData
188
                        //Si el del buffer tiene valor es porque alg?n filtro le ha salvado valor nodata por lo que se pone ese
189
                        //sino se pone el de la imagen original
190
                        NoData nodataOrigin = (NoData)rasterDataSource.getNoDataValue();
191
                        NoData nodataBuffer =  (NoData)buffer.getNoDataValue();
192
                        if(nodataBuffer != null && nodataBuffer.isDefined()) {
193
                                nodataBuffer.setFileName(filename);
194
                                nodataBuffer.save();
195
                        } else if(nodataOrigin != null && nodataOrigin.isDefined()) {
196
                                nodataOrigin.setFileName(filename);
197
                                nodataOrigin.save();
198
                        }
199
                        
200
                        SwingUtilities.invokeLater(new Runnable() {
201
                                public void run() {
202
                                        if (externalActions != null)
203
                                                externalActions.end(filename);
204
                                }
205
                        });
206
                } catch (NotSupportedExtensionException e) {
207
                        throw new ProcessException("error_writer_notsupportedextension", e);
208
                } catch (RasterDriverException e) {
209
                        throw new ProcessException("error_writer", e);
210
                } catch (IOException e) {
211
                        throw new ProcessException("error_writer", e);
212
                } catch (FilterTypeException e) {
213
                        throw new ProcessException("error_adding_filters", e);
214
                } catch (QueryException e) {
215
                        throw new ProcessException("error_loading_data", e);
216
                } catch (FilterManagerException e) {
217
                        throw new ProcessException("error_adding_filters", e);
218
                } finally {
219
                        if(writerBufferServer != null)
220
                                writerBufferServer.dispose();
221
                        if(buff != null)
222
                                buff.dispose();
223
                        if(rasterFilterList != null)
224
                                rasterFilterList.dispose();
225
                        if(alpha != null)
226
                                alpha.dispose();
227
                        if(dstoreCopy != null)
228
                                try {
229
                                        dstoreCopy.close();
230
                                } catch (CloseException e) {
231
                                }
232
                        if(lyr != null)
233
                                lyr.setReadingData(null);
234
                        dispose();
235
                }
236
        }
237
        
238
        private ColorInterpretation getColorInterpretation(int nBands, int dataType) {
239
                //Si la fuente es con paleta, al aplicarle un filtro se genera un ARGB
240
                if(lyr.existColorTable()) 
241
                        return rManager.getDataStructFactory().createColorInterpretation(
242
                                        new String[] { ColorInterpretation.RED_BAND, ColorInterpretation.GREEN_BAND, ColorInterpretation.BLUE_BAND, ColorInterpretation.ALPHA_BAND });
243

    
244
                if(dataType == Buffer.TYPE_BYTE) {
245
                        if(nBands == 3)
246
                                return rManager.getDataStructFactory().createColorInterpretation(
247
                                                new String[] { ColorInterpretation.RED_BAND, ColorInterpretation.GREEN_BAND, ColorInterpretation.BLUE_BAND });
248
                        if(nBands == 4)
249
                                return rManager.getDataStructFactory().createColorInterpretation(
250
                                                new String[] { ColorInterpretation.RED_BAND, ColorInterpretation.GREEN_BAND, ColorInterpretation.BLUE_BAND, ColorInterpretation.ALPHA_BAND });
251
                        if(nBands == 2 || nBands > 4) {
252
                                return lyr.getRender().getRenderColorInterpretation();
253
                                /*int[] renderBands = lyr.getRender().getRenderBands();
254
                                String[] ci = new String[renderBands.length];
255
                                for (int i = 0; i < renderBands.length; i++) {
256
                                        switch (renderBands[i]) {
257
                                        case 0:ci[i] = ColorInterpretation.RED_BAND; break;
258
                                        case 1:ci[i] = ColorInterpretation.GREEN_BAND; break;
259
                                        case 2:ci[i] = ColorInterpretation.BLUE_BAND; break;
260
                                        default: ci[i] = ColorInterpretation.UNDEF_BAND; 
261
                                        }
262
                                }
263
                                return rManager.getDataStructFactory().createColorInterpretation(ci);*/
264
                        }
265
                }
266
                if(nBands == 1)
267
                        return rManager.getDataStructFactory().createColorInterpretation(
268
                                new String[] { ColorInterpretation.GRAY_BAND });
269
                else {
270
                        String[] ci = new String[nBands];
271
                        for (int i = 0; i < ci.length; i++) {
272
                                ci[i] = ColorInterpretation.UNDEF_BAND;
273
                        }
274
                        return rManager.getDataStructFactory().createColorInterpretation(ci);
275
                }
276
        }
277

    
278
        /**
279
         * Sustituye la lista de filtros de filterList por la que le pasamos en forma
280
         * de ArrayList
281
         * @param filterList
282
         * @param listFilterUsed
283
         * @throws FilterTypeException 
284
         * @throws FilterTypeException 
285
         */
286
        public void addSelectedFilters(RasterFilterList filterList, ArrayList<ParamStruct> listFilterUsed) throws FilterManagerException, FilterTypeException {
287
                filterList.clear();
288
                
289
                for (int i = 0; i < listFilterUsed.size(); i++) {
290
                        ParamStruct aux = (ParamStruct) listFilterUsed.get(i);
291
                        RasterFilterListManager filterManager = filterList.getManagerByFilterClass(aux.getFilterClass());
292
                        filterManager.addFilter(aux.getFilterClass(), aux.getFilterParam());
293
                }
294

    
295
                filterList.resetPercent();
296
        }
297

    
298
        public int getPercent() {
299
                if (rasterFilterList == null)
300
                        return 0;
301

    
302
                if (rasterFilterList.getPercent() < 100)
303
                        return rasterFilterList.getPercent();
304

    
305
                if (geoRasterWriter == null)
306
                        return 0;
307

    
308
                return geoRasterWriter.getPercent();
309
        }
310

    
311
        public String getTitle() {
312
                return Messages.getText("aplicando_filtros");
313
        }
314
        
315
        public void dispose() {
316
                rasterDataSource = null;
317
                if(listFilterUsed != null) {
318
                        listFilterUsed.clear();
319
                        listFilterUsed = null;
320
                }
321
                rasterFilterList = null;
322
                geoRasterWriter  = null;
323
                lyr              = null;
324
        }
325
        
326
        @Override
327
        protected void finalize() throws Throwable {
328
                dispose();
329
                super.finalize();
330
        }
331
}