Statistics
| Revision:

gvsig-raster / org.gvsig.raster.reproject / branches / org.gvsig.raster.reproject_dataaccess_refactoring / org.gvsig.raster.reproject.app.reprojectclient / src / main / java / org / gvsig / raster / reproject / app / PrepareLayerAskProjection.java @ 2418

History | View | Annotate | Download (11.6 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.reproject.app;
23

    
24
import java.io.File;
25
import java.util.HashMap;
26
import java.util.Map;
27

    
28
import org.cresques.cts.IProjection;
29
import org.gvsig.app.prepareAction.PrepareContext;
30
import org.gvsig.app.prepareAction.PrepareContextView;
31
import org.gvsig.app.prepareAction.PrepareDataStoreParameters;
32
import org.gvsig.app.prepareAction.PrepareLayer;
33
import org.gvsig.fmap.crs.CRSFactory;
34
import org.gvsig.fmap.dal.DALLocator;
35
import org.gvsig.fmap.dal.DataManager;
36
import org.gvsig.fmap.dal.DataStoreParameters;
37
import org.gvsig.fmap.dal.coverage.RasterLocator;
38
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
39
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
40
import org.gvsig.fmap.dal.coverage.store.parameter.RasterDataParameters;
41
import org.gvsig.fmap.dal.coverage.util.CRSUtils;
42
import org.gvsig.fmap.mapcontext.MapContextLocator;
43
import org.gvsig.fmap.mapcontext.MapContextManager;
44
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
45
import org.gvsig.fmap.mapcontext.layers.FLayer;
46
import org.gvsig.raster.algorithm.RasterBaseAlgorithmLibrary;
47
import org.gvsig.raster.algorithm.process.DataProcess;
48
import org.gvsig.raster.algorithm.process.IProcessActions;
49
import org.gvsig.raster.algorithm.process.ProcessException;
50
import org.gvsig.raster.fmap.layers.DefaultFLyrRaster;
51
import org.gvsig.raster.fmap.layers.FLyrRaster;
52
import org.gvsig.raster.mainplugin.config.Configuration;
53
import org.gvsig.raster.reproject.algorithm.ReprojectProcess;
54
import org.gvsig.raster.reproject.app.preparelayer.RasterProjectionActionsDialog;
55
import org.gvsig.raster.reproject.app.preparelayer.ReprojectionQueue;
56
import org.gvsig.raster.swing.RasterSwingLibrary;
57
import org.gvsig.tools.exception.BaseException;
58
import org.slf4j.Logger;
59
import org.slf4j.LoggerFactory;
60

    
61
public class PrepareLayerAskProjection implements PrepareDataStoreParameters, PrepareLayer, IProcessActions {
62
        protected CRSUtils              crsUtil                       = RasterLocator.getManager().getCRSUtils(); 
63
        private boolean                 changeReprojectionOption      = true;
64
        private int                     lastReprojectionOption        = RasterDataParameters.NEW_PROJETION_TO_THE_LAYER;
65
        private ReprojectionQueue       queue                         = ReprojectionQueue.getSingleton();
66
        private Logger                  log                           = LoggerFactory.getLogger(PrepareLayerAskProjection.class);
67
        
68
        @SuppressWarnings("deprecation")
69
        public DataStoreParameters prepare(DataStoreParameters storeParameters,
70
                        PrepareContext context) throws BaseException {
71
                if(!(storeParameters instanceof RasterDataParameters))
72
                        return storeParameters;
73
                
74
                DataManager dataManager = DALLocator.getDataManager();
75
                RasterDataStore dataStore = (RasterDataStore)dataManager.createStore(storeParameters);
76
                
77
                if (Configuration.getValue("general_ask_projection", Boolean.valueOf(false)).booleanValue()) {
78
                        IProjection proj = readProjection(dataStore);
79
                        if(proj != null) {
80
                                //((RasterDataParameters)storeParameters).setDynValue("CRS", proj);
81
                                compareProjections(proj, context.getViewProjection(), dataStore);
82
                        }
83
                }
84
                
85
                if(dataStore != null)
86
                        dataStore.close();
87
                
88
                if(((RasterDataParameters)storeParameters).getReprojectionOption() == RasterDataParameters.NEW_PROJETION_TO_THE_LAYER)
89
                        ((RasterDataParameters)storeParameters).setDynValue("CRS", null);
90
                        
91
                if(((RasterDataParameters)storeParameters).getReprojectionOption() == RasterDataParameters.NOT_LOAD)
92
                        return null;
93
                
94
                return storeParameters;
95
        }
96
        
97
        public void post(DataStoreParameters storeParameters, PrepareContext context) {
98
                changeReprojectionOption = true;
99
        }
100
        
101
        public void pre(DataStoreParameters storeParameters, PrepareContext context) {
102
        }
103
        
104
        /**
105
         * If this flag is true the reprojection options can be changed by the user 
106
         * @return
107
         */
108
        public boolean getChangeOption() {
109
                return changeReprojectionOption;
110
        }
111
        
112
        /**
113
         * If this flag is true the reprojection options can be changed by the user 
114
         * @param changeOption
115
         */
116
        public void setChangeOption(boolean changeOption) {
117
                this.changeReprojectionOption = changeOption;
118
        }
119
        
120
        public FLayer prepare(FLayer layer, PrepareContextView context) {
121
                if (!(layer instanceof DefaultFLyrRaster))
122
                        return layer;
123
                DefaultFLyrRaster lyrRaster = (DefaultFLyrRaster) layer;
124
                String layerName = lyrRaster.getName();
125

    
126
                RasterDataParameters params = (RasterDataParameters)lyrRaster.getDataStore().getParameters();
127
                int repOption = params.getReprojectionOption();
128
                
129
                if(repOption == RasterDataParameters.REPROJECT_DATA) {
130
                        RasterDataParameters rasterParams = reproject(lyrRaster, context.getViewProjection());
131
                        if(rasterParams != null) {
132
                                MapContextManager mcm = MapContextLocator.getMapContextManager();
133
                                try {
134
                                        return (DefaultFLyrRaster) mcm.createLayer(layerName, rasterParams);
135
                                } catch (LoadLayerException e) {
136
                                        return lyrRaster;
137
                                }
138
                                /*DefaultFLyrRaster lyr = new DefaultFLyrRaster();
139
                                DataManager dataManager = DALLocator.getDataManager();
140
                                try {
141
                                        DataStore dataStore = dataManager.createStore(rasterParams);
142
                                        lyr.setName(layerName);
143
                                        lyr.setDataStore(dataStore);
144
                                        return lyr;
145
                                } catch (ValidateDataParametersException e) {
146
                                        return lyrRaster;
147
                                } catch (InitializeException e) {
148
                                        return lyrRaster;
149
                                } catch (ProviderNotRegisteredException e) {
150
                                        return lyrRaster;
151
                                } catch (LoadLayerException e) {
152
                                        return lyrRaster;
153
                                }*/
154
                        }
155
                } else if(repOption == RasterDataParameters.REPROJECT_VIEW) {
156
                        try {
157
                                if (lyrRaster != null && lyrRaster.readProjection() != null) {
158
                                        context.getMapControl().setProjection(lyrRaster.readProjection());
159
                                        lyrRaster.setVisible(true);
160
                                }
161
                        } catch (RasterDriverException e) {
162
                                RasterSwingLibrary.messageBoxError("Error reading the projection", null, e);
163
                        }
164
                } else if(repOption == RasterDataParameters.DONT_CHANGE_PROJECTION) {
165
                        lyrRaster.setVisible(true);
166
                        return lyrRaster;
167
                } else if(repOption == RasterDataParameters.NEW_PROJETION_TO_THE_LAYER) {
168
                        IProjection proj = context.getViewProjection();
169
                        if(proj != null)
170
                                lyrRaster.setProjection(proj, false);
171
                        lyrRaster.setVisible(true);
172
                        return lyrRaster;
173
                }
174

    
175
                return lyrRaster;
176
        }
177
        
178
        private RasterDataParameters reproject(FLyrRaster lyrRaster, IProjection dstProj) {
179
                RasterDataParameters params = (RasterDataParameters)lyrRaster.getDataStore().getParameters();
180
                int repOption = params.getReprojectionOption();
181

    
182
                if(repOption == RasterDataParameters.REPROJECT_DATA) {
183
                        IProjection srcProj = readProjection(lyrRaster.getDataStore());
184
                        if(srcProj == null)
185
                                return null;
186

    
187
                        String uri = params.getURI();
188
                        uri = uri.substring(0, uri.lastIndexOf(".")) + "_" + dstProj.getAbrev() + uri.substring(uri.lastIndexOf("."));
189
                        uri = uri.replace(':', '_');
190

    
191
                        if(!new File(uri).exists()) {                                        
192
                                DataProcess process = null;
193
                                try {
194
                                        process = RasterBaseAlgorithmLibrary.getManager().createRasterTask("RasterReprojectionProcess");
195
                                } catch (ProcessException e1) {
196
                                        RasterSwingLibrary.messageBoxError("error_creating_algorithm", null, e1);
197
                                        return params;
198
                                }
199
                                process.setActions(this);
200
                                process.addParam(ReprojectProcess.RASTER_STORE, lyrRaster.getDataStore());
201
                                process.addParam(ReprojectProcess.SIZEX, 0); //Calculo autom?tico de tama?o
202
                                process.addParam(ReprojectProcess.SIZEY, 0);
203
                                process.addParam(ReprojectProcess.PATH, uri);
204
                                process.addParam(ReprojectProcess.SRC_PROJECTION, srcProj);
205
                                process.addParam(ReprojectProcess.DST_PROJECTION, dstProj);
206
                                process.addParam(ReprojectProcess.CELLSIZE, lyrRaster.getDataStore().getCellSize());
207

    
208
                                //Despierta la cola que reproyecta im?genes
209
                                synchronized (queue) {
210
                                        queue.add(process, this);        
211
                                        queue.notify();
212
                                }
213

    
214
                                //Se suspende hasta que la cola haya terminado
215
                                try {
216
                                        synchronized (this) {
217
                                                this.wait();
218
                                        }
219
                                } catch (InterruptedException e) {
220
                                }
221

    
222
                                if(process.getResult() != null) {
223
                                        HashMap<String, Object> map = (HashMap<String, Object>)process.getResult();
224
                                        String filename = (String)map.get(ReprojectProcess.FILENAME);
225
                                        params.setURI(filename);
226
                                        return params;
227
                                }
228
                        } else {
229
                                params.setURI(uri);
230
                                return params;
231
                        }
232

    
233
                } else if(repOption == RasterDataParameters.REPROJECT_VIEW) {
234
                        //Esto se cambia en el prepare que tiene acceso al mapcontrol. Este prepare es a nivel de datos
235
                } 
236
                return null;
237
        }
238

    
239
        public void end(Object param) {
240
                
241
        }
242

    
243
        /**
244
         * Compares two projections and show a dialog to the user to make a decision
245
         * @param lyrProj
246
         * @param viewProj
247
         */
248
        private void compareProjections(IProjection lyrProj, IProjection viewProj, RasterDataStore dataStore) {
249
                if(!getChangeOption() || lyrProj == null || viewProj == null) {
250
                        ((RasterDataParameters)dataStore.getParameters()).setReprojectionOption(lastReprojectionOption);
251
                        return;
252
                }
253

    
254
                /*
255
                 * Si las proyecciones de vista y raster son distintas se lanza el
256
                 * dialogo de selecci?n de opciones. Este dialogo solo se lanza en caso
257
                 * de que el checkbox de aplicar a todos los ficheros no haya sido
258
                 * marcado. En este caso para el resto de ficheros de esa selecci?n se
259
                 * har? la misma acci?n que se hizo para el primero.
260
                 */
261
                if (!viewProj.getAbrev().endsWith(lyrProj.getAbrev())) {
262
                        String layerName = dataStore.getName().substring(dataStore.getName().lastIndexOf(File.separator) + 1, dataStore.getName().length());
263
                        RasterProjectionActionsDialog dialog = new RasterProjectionActionsDialog(
264
                                        dataStore.isReproyectable(), layerName, RasterDataParameters.REPROJECT_VIEW);
265
                        if (dialog != null) {
266
                                lastReprojectionOption = dialog.getRasterProjectionActionsPanel().getSelection();
267
                                ((RasterDataParameters)dataStore.getParameters()).setReprojectionOption(lastReprojectionOption);
268
                                setChangeOption(!dialog.getChangeProjectionOption());
269
                        }
270
                }
271
        }
272
        
273
        /**
274
         * Reads the projection from a DataStore
275
         * @param dataStore
276
         * @return
277
         * @throws RasterDriverException
278
         */
279
        @SuppressWarnings("deprecation")
280
        private IProjection readProjection(RasterDataStore dataStore) {
281
                try {
282
                        crsUtil.setCRSFactory(CRSFactory.cp);
283
                        if( dataStore == null )
284
                                return null;
285
                        return crsUtil.convertWktToIProjection(dataStore.getWktProjection());
286
                } catch (Exception e) {
287
                        //Si ha habido alg?n problema con la conversi?n metemos un log y que devuelva null 
288
                        log.info("Problems converting from WKT to IProjection", e);
289
                } catch (Error e) {
290
                        log.info("Problems converting from WKT to IProjection", e);
291
                }
292
                return null;
293
        }
294

    
295
        public String getDescription() {
296
                return "Prepare projection for Raster Layer";
297
        }
298

    
299
        public String getName() {
300
                return "PrepareRasterLayerProjection";
301
        }
302

    
303
        public Object create() {
304
                return this;
305
        }
306

    
307
        public Object create(Object[] args) {
308
                return this;
309
        }
310

    
311
        @SuppressWarnings("rawtypes")
312
        public Object create(Map args) {
313
                return this;
314
        }
315

    
316
        public void interrupted() {
317
        }
318
        
319
        public void updateProgress(int current, int total) {
320
                
321
        }
322
}