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 @ 2338

History | View | Annotate | Download (12.1 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
                        filterLoader.addSrcHistogram(dstoreCopy.getHistogramComputer());
158
                        addSelectedFilters(rasterFilterList, listFilterUsed);
159
                        buffer = filterLoader.applyFilters(buff);
160
                        
161
                        insertLineLog(Messages.getText("guardando_capa"));
162

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

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

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

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

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

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

    
296
                filterList.resetPercent();
297
        }
298

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

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

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

    
309
                return geoRasterWriter.getPercent();
310
        }
311

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