Revision 5468 org.gvsig.raster.reproject/branches/org.gvsig.raster.reproject_proyeccion_al_vuelo/org.gvsig.raster.reproject.app.reprojectclient/src/main/java/org/gvsig/raster/reproject/app/PrepareLayerAskProjection.java

View differences:

PrepareLayerAskProjection.java
21 21
*/
22 22
package org.gvsig.raster.reproject.app;
23 23

  
24
import java.io.File;
25
import java.util.HashMap;
26 24
import java.util.Map;
27
import org.apache.commons.io.FilenameUtils;
28 25

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

  
62
public class PrepareLayerAskProjection implements PrepareDataStoreParameters, PrepareLayer, IProcessActions {
63
	protected CRSUtils              crsUtil                       = RasterLocator.getManager().getCRSUtils();
64
	private boolean                 changeReprojectionOption      = true;
65
	private int                     lastReprojectionOption        = RasterDataParameters.NEW_PROJETION_TO_THE_LAYER;
66
	private ReprojectionQueue       queue                         = ReprojectionQueue.getSingleton();
67
	private Logger                  log                           = LoggerFactory.getLogger(PrepareLayerAskProjection.class);
45
import es.unex.sextante.gui.cmd.bshcommands.data;
68 46

  
69
	@SuppressWarnings("deprecation")
70
	public DataStoreParameters prepare(DataStoreParameters storeParameters,
71
			PrepareContext context) throws BaseException {
72
		if(!(storeParameters instanceof RasterDataParameters))
73
			return storeParameters;
47
/**
48
 * Entity to configure data store parameters when raster is projected on the fly
49
 * before open store.
50
 * 
51
 * @author <a href="mailto:lmarques@disid.com">Lluis Marques</a>
52
 *
53
 */
54
public class PrepareLayerAskProjection implements PrepareDataStoreParameters {
74 55

  
75
		DataManager dataManager = DALLocator.getDataManager();
76
		RasterDataStore dataStore = (RasterDataStore)dataManager.createStore(storeParameters);
56
    public DataStoreParameters prepare(DataStoreParameters storeParameters, PrepareContext context)
57
        throws BaseException {
77 58

  
78
		if (Configuration.getValue("general_ask_projection", Boolean.valueOf(false)).booleanValue()) {
79
			IProjection proj = readProjection(dataStore);
80
			if(proj != null) {
81
				//((RasterDataParameters)storeParameters).setDynValue("CRS", proj);
82
				compareProjections(proj, context.getViewProjection(), dataStore);
83
			}
84
		}
59
        if (storeParameters instanceof RasterDataParameters) {
60
            RasterDataParameters rasterParameters = (RasterDataParameters) storeParameters;
61
            
62
            DataManager dataManager = DALLocator.getDataManager();
63
            RasterDataStore store =
64
                (RasterDataStore) dataManager.openStore(rasterParameters.getDataStoreName(),
65
                    rasterParameters);
66
            IProjection projection = store.getProjection();
67
            store.dispose();
68
            
69
            if(projection != null){
70
                rasterParameters.setSRS(projection);
71
            }
72
        }
85 73

  
86
		if(dataStore != null)
87
			dataStore.close();
74
        return storeParameters;
75
    }
76
    
77
    public void pre(DataStoreParameters storeParameters, PrepareContext context) {
78
    }
88 79

  
89
		if(((RasterDataParameters)storeParameters).getReprojectionOption() == RasterDataParameters.NEW_PROJETION_TO_THE_LAYER) {
90
			IProjection viewProjection = context.getViewProjection();
91
			if(viewProjection != null) {
92
				((RasterDataParameters)storeParameters).setSRS(viewProjection);
93
				((RasterDataParameters)storeParameters).setSRSID(viewProjection.getAbrev());
94
			} else {
95
				((RasterDataParameters)storeParameters).setSRS(null);
96
				((RasterDataParameters)storeParameters).setSRSID(null);
97
			}
98
		}
80
    public void post(DataStoreParameters storeParameters, PrepareContext context) {
81
    }
99 82

  
100
		if(((RasterDataParameters)storeParameters).getReprojectionOption() == RasterDataParameters.NOT_LOAD)
101
			return null;
83
    public String getDescription() {
84
        return "Prepare projection for Raster Layer";
85
    }
102 86

  
103
		return storeParameters;
104
	}
87
    public String getName() {
88
        return "PrepareRasterLayerProjection";
89
    }
105 90

  
106
	public void post(DataStoreParameters storeParameters, PrepareContext context) {
107
		changeReprojectionOption = true;
108
	}
91
    public Object create() {
92
        return this;
93
    }
109 94

  
110
	public void pre(DataStoreParameters storeParameters, PrepareContext context) {
111
	}
95
    public Object create(Object[] args) {
96
        return this;
97
    }
112 98

  
113
	/**
114
	 * If this flag is true the reprojection options can be changed by the user
115
	 * @return
116
	 */
117
	public boolean getChangeOption() {
118
		return changeReprojectionOption;
119
	}
120

  
121
	/**
122
	 * If this flag is true the reprojection options can be changed by the user
123
	 * @param changeOption
124
	 */
125
	public void setChangeOption(boolean changeOption) {
126
		this.changeReprojectionOption = changeOption;
127
	}
128

  
129
	public FLayer prepare(FLayer layer, PrepareContextView context) {
130
		if (!(layer instanceof DefaultFLyrRaster))
131
			return layer;
132
		DefaultFLyrRaster lyrRaster = (DefaultFLyrRaster) layer;
133
		String layerName = lyrRaster.getName();
134

  
135
		RasterDataParameters params = (RasterDataParameters)lyrRaster.getDataStore().getParameters();
136
		int repOption = params.getReprojectionOption();
137

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

  
184
		return lyrRaster;
185
	}
186

  
187
	private RasterDataParameters reproject(FLyrRaster lyrRaster, IProjection dstProj) {
188
		RasterDataParameters params = (RasterDataParameters)lyrRaster.getDataStore().getParameters();
189
		int repOption = params.getReprojectionOption();
190

  
191
		if(repOption == RasterDataParameters.REPROJECT_DATA) {
192
			IProjection srcProj = readProjection(lyrRaster.getDataStore());
193
			if(srcProj == null)
194
				return null;
195

  
196
			File f = new File(params.getURI());
197
            File fdst =
198
                new File(FilenameUtils.removeExtension(f.getAbsolutePath()) + "_"
199
                    + dstProj.getAbrev().replace(":", "_")+ "." + FilenameUtils.getExtension(f.getName()));
200

  
201
			if(!fdst.exists()) {
202
				DataProcess process = null;
203
				try {
204
					process = RasterBaseAlgorithmLibrary.getManager().createRasterTask("RasterReprojectionProcess");
205
				} catch (ProcessException e1) {
206
					RasterSwingLibrary.messageBoxError("error_creating_algorithm", null, e1);
207
					return params;
208
				}
209
				process.setActions(this);
210
				process.addParam(ReprojectProcess.RASTER_STORE, lyrRaster.getDataStore());
211
				process.addParam(ReprojectProcess.SIZEX, 0); //Calculo autom?tico de tama?o
212
				process.addParam(ReprojectProcess.SIZEY, 0);
213
				process.addParam(ReprojectProcess.PATH, fdst.getAbsolutePath());
214
				process.addParam(ReprojectProcess.SRC_PROJECTION, srcProj);
215
				process.addParam(ReprojectProcess.DST_PROJECTION, dstProj);
216
				process.addParam(ReprojectProcess.CELLSIZE, lyrRaster.getDataStore().getCellSize());
217

  
218
				//Despierta la cola que reproyecta im?genes
219
				synchronized (queue) {
220
					queue.add(process, this);
221
					queue.notify();
222
				}
223

  
224
				//Se suspende hasta que la cola haya terminado
225
				try {
226
					synchronized (this) {
227
						this.wait();
228
					}
229
				} catch (InterruptedException e) {
230
				}
231

  
232
				if(process.getResult() != null) {
233
					HashMap<String, Object> map = (HashMap<String, Object>)process.getResult();
234
					String filename = (String)map.get(ReprojectProcess.FILENAME);
235
					params.setURI(new File(filename).toURI());
236
					return params;
237
				}
238
			} else {
239
				params.setURI(fdst.toURI());
240
				return params;
241
			}
242

  
243
		} else if(repOption == RasterDataParameters.REPROJECT_VIEW) {
244
			//Esto se cambia en el prepare que tiene acceso al mapcontrol. Este prepare es a nivel de datos
245
		}
246
		return null;
247
	}
248

  
249
	public void end(Object param) {
250

  
251
	}
252

  
253
	/**
254
	 * Compares two projections and show a dialog to the user to make a decision
255
	 * @param lyrProj
256
	 * @param viewProj
257
	 */
258
	private void compareProjections(IProjection lyrProj, IProjection viewProj, RasterDataStore dataStore) {
259
		if(!getChangeOption() || lyrProj == null || viewProj == null) {
260
			((RasterDataParameters)dataStore.getParameters()).setReprojectionOption(lastReprojectionOption);
261
			return;
262
		}
263

  
264
		/*
265
		 * Si las proyecciones de vista y raster son distintas se lanza el
266
		 * dialogo de selecci?n de opciones. Este dialogo solo se lanza en caso
267
		 * de que el checkbox de aplicar a todos los ficheros no haya sido
268
		 * marcado. En este caso para el resto de ficheros de esa selecci?n se
269
		 * har? la misma acci?n que se hizo para el primero.
270
		 */
271
		if (!viewProj.getAbrev().endsWith(lyrProj.getAbrev())) {
272
			String layerName = dataStore.getName().substring(dataStore.getName().lastIndexOf(File.separator) + 1, dataStore.getName().length());
273
			RasterProjectionActionsDialog dialog = new RasterProjectionActionsDialog(
274
					dataStore.isReproyectable(), layerName, RasterDataParameters.REPROJECT_VIEW, viewProj, lyrProj);
275
			if (dialog != null) {
276
				lastReprojectionOption = dialog.getRasterProjectionActionsPanel().getSelection();
277
				((RasterDataParameters)dataStore.getParameters()).setReprojectionOption(lastReprojectionOption);
278
				setChangeOption(!dialog.getChangeProjectionOption());
279
			}
280
		}
281
	}
282

  
283
	/**
284
	 * Reads the projection from a DataStore
285
	 * @param dataStore
286
	 * @return
287
	 * @throws RasterDriverException
288
	 */
289
	@SuppressWarnings("deprecation")
290
	private IProjection readProjection(RasterDataStore dataStore) {
291
		try {
292
			crsUtil.setCRSFactory(CRSFactory.cp);
293
			if( dataStore == null )
294
				return null;
295
			return crsUtil.convertWktToIProjection(dataStore.getWktProjection());
296
		} catch (Exception e) {
297
			//Si ha habido alg?n problema con la conversi?n metemos un log y que devuelva null
298
			log.info("Problems converting from WKT to IProjection", e);
299
		} catch (Error e) {
300
			log.info("Problems converting from WKT to IProjection", e);
301
		}
302
		return null;
303
	}
304

  
305
	public String getDescription() {
306
		return "Prepare projection for Raster Layer";
307
	}
308

  
309
	public String getName() {
310
		return "PrepareRasterLayerProjection";
311
	}
312

  
313
	public Object create() {
314
		return this;
315
	}
316

  
317
	public Object create(Object[] args) {
318
		return this;
319
	}
320

  
321
	@SuppressWarnings("rawtypes")
322
	public Object create(Map args) {
323
		return this;
324
	}
325

  
326
	public void interrupted() {
327
	}
328

  
329
	public void updateProgress(int current, int total) {
330

  
331
	}
99
    @SuppressWarnings("rawtypes")
100
    public Object create(Map args) {
101
        return this;
102
    }
332 103
}

Also available in: Unified diff