Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extGraph_predes / src / com / iver / cit / gvsig / graph / GenerateNetworkExtension.java @ 8726

History | View | Annotate | Download (14.5 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package com.iver.cit.gvsig.graph;
42

    
43
import java.awt.Component;
44
import java.io.File;
45
import java.io.FileNotFoundException;
46
import java.util.HashMap;
47

    
48
import javax.swing.ImageIcon;
49
import javax.swing.JFileChooser;
50
import javax.swing.JOptionPane;
51

    
52
import com.iver.andami.PluginServices;
53
import com.iver.andami.messages.NotificationManager;
54
import com.iver.andami.plugins.Extension;
55
import com.iver.andami.preferences.IPreference;
56
import com.iver.andami.preferences.IPreferenceExtension;
57
import com.iver.andami.ui.mdiManager.IWindow;
58
import com.iver.cit.gvsig.fmap.DriverException;
59
import com.iver.cit.gvsig.fmap.MapContext;
60
import com.iver.cit.gvsig.fmap.MapControl;
61
import com.iver.cit.gvsig.fmap.core.FShape;
62
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
63
import com.iver.cit.gvsig.fmap.drivers.SHPLayerDefinition;
64
import com.iver.cit.gvsig.fmap.edition.EditionException;
65
import com.iver.cit.gvsig.fmap.edition.IWriter;
66
import com.iver.cit.gvsig.fmap.edition.ShpSchemaManager;
67
import com.iver.cit.gvsig.fmap.edition.writers.dbf.DbfWriter;
68
import com.iver.cit.gvsig.fmap.edition.writers.shp.MultiShpWriter;
69
import com.iver.cit.gvsig.fmap.edition.writers.shp.ShpWriter;
70
import com.iver.cit.gvsig.fmap.layers.FLayer;
71
import com.iver.cit.gvsig.fmap.layers.FLayers;
72
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
73
import com.iver.cit.gvsig.fmap.layers.SingleLayerIterator;
74
import com.iver.cit.gvsig.geoprocess.core.fmap.GeoprocessException;
75
import com.iver.cit.gvsig.geoprocess.core.fmap.XTypes;
76
import com.iver.cit.gvsig.graph.core.writers.NetworkFileRedWriter;
77
import com.iver.cit.gvsig.graph.core.writers.NetworkGvTableWriter;
78
import com.iver.cit.gvsig.graph.gui.wizard.NetWizard;
79
import com.iver.cit.gvsig.graph.preferences.RoutePage;
80
import com.iver.cit.gvsig.project.documents.view.IProjectView;
81
import com.iver.cit.gvsig.project.documents.view.gui.IView;
82
import com.iver.cit.gvsig.project.documents.view.gui.View;
83
import com.iver.cit.gvsig.topology.lineclean.fmap.LineCleanGeoprocess;
84
import com.iver.utiles.SimpleFileFilter;
85
import com.iver.utiles.swing.threads.AbstractMonitorableTask;
86
import com.iver.utiles.swing.threads.IMonitorableTask;
87
import com.iver.utiles.swing.threads.IPipedTask;
88
import com.iver.utiles.swing.threads.PipeTask;
89

    
90

    
91
public class GenerateNetworkExtension extends Extension implements
92
                IPreferenceExtension {
93
        private static final IPreference thePreferencePage = new RoutePage();
94
        public void initialize() {
95
        }
96

    
97
        public void execute(String actionCommand) {
98
                IView view = (View) PluginServices.getMDIManager().getActiveWindow();
99
                MapControl mapControl = view.getMapControl();
100
                MapContext map = mapControl.getMapContext();
101
                FLayers tocLyrs = map.getLayers();
102
                SingleLayerIterator lyrIterator = new SingleLayerIterator(tocLyrs);
103
                while (lyrIterator.hasNext()) {
104
                        FLayer lyr = lyrIterator.next();
105
                        if ((lyr.isActive()) && (lyr instanceof FLyrVect)) {
106
                                FLyrVect lyrVect = (FLyrVect) lyr;
107
                                int shapeType;
108
                                try {
109
                                        shapeType = lyrVect.getShapeType();
110
                                        if (shapeType == FShape.LINE) {
111
                                                if (actionCommand.equalsIgnoreCase("GENERATE_RED")) {
112
                                                        generateRedNetwork(lyrVect, tocLyrs);
113
                                                        return;
114
                                                }
115
                                        }
116
                                } catch (DriverException e) {
117
                                        e.printStackTrace();
118
                                        NotificationManager.addError(e);
119
                                }
120

    
121
                        }
122
                }
123

    
124
        }
125

    
126
        private void generateNetwork(FLyrVect lyr) {
127
                NetworkGvTableWriter netBuilder = new NetworkGvTableWriter();
128
                // Por ahora, a pelo, pero hay que sacar un cuadro
129
                // de di?logo para hecer el mapping.
130
                // Tambi?n un cuadro de di?logo para seleccionar
131
                // en qu? tablas quiere escribir, y su formato
132
                // (dbf, postgres, etc)
133
                String fieldType = "tipored";
134
                String fieldDist = "length";
135
                String fieldSense = "sen";
136
                String fieldCost = "cost";
137
                try {
138
                        netBuilder.setLayer(lyr);
139
                        netBuilder.setFieldType(fieldType);
140
                        netBuilder.setFieldDist(fieldDist);
141
                        netBuilder.setFieldSense(fieldSense);
142
                        netBuilder.setFieldCost(fieldCost);
143
                        DbfWriter nodeWriter = new DbfWriter();
144
                        nodeWriter.setFile(new File("c:/nodes.dbf"));
145

    
146
                        DbfWriter edgeWriter = new DbfWriter();
147
                        edgeWriter.setFile(new File("c:/edges.dbf"));
148

    
149
                        netBuilder.setEdgeWriter(edgeWriter);
150
                        netBuilder.setNodeWriter(nodeWriter);
151

    
152
                        netBuilder.writeNetwork();
153
                } catch (DriverException e1) {
154
                        // TODO Auto-generated catch block
155
                        e1.printStackTrace();
156
                } catch (EditionException e1) {
157
                        // TODO Auto-generated catch block
158
                        e1.printStackTrace();
159
                }
160
                JOptionPane.showMessageDialog(null, PluginServices
161
                                .getText(this, "done"));
162
        }
163
        
164
        class GenerateRedNetworkAfterCleanTask 
165
                extends AbstractMonitorableTask implements IPipedTask{
166
                
167
                File redFile;
168
                NetworkFileRedWriter netBuilder;
169
                
170
                FLyrVect inputLayer;
171
                FLyrVect pseudonodes;
172
                FLayers tocLyrs;
173
                
174
                /**
175
                 * Constructor
176
                 * @param tocLyrs
177
                 */
178
                GenerateRedNetworkAfterCleanTask(File redFile,
179
                                NetworkFileRedWriter netBuilder, FLayers tocLyrs) {
180
                        this.redFile = redFile;
181
                        this.netBuilder = netBuilder;
182
                        this.tocLyrs = tocLyrs;
183
                        setInitialStep(0);
184
                        setDeterminatedProcess(true);
185
                        setStatusMessage(PluginServices.getText(this,
186
                        "Generando_red_a_partir_de_capa_lineal"));
187
                }
188

    
189
                public void run() throws Exception {
190
                        int numShapes;
191
                        try {         
192
                                numShapes = inputLayer.getSource().getShapeCount();
193
                                setFinalStep(numShapes);
194
                                
195
                                
196
                        } catch (DriverIOException e) {
197
                                // TODO Auto-generated catch block
198
                                e.printStackTrace();
199
                        }
200
                        
201
                        
202
                        netBuilder.setLayer(inputLayer);
203
                        netBuilder.setCancellableMonitorable(this);
204
                        netBuilder.setRedFile(redFile);
205
                        netBuilder.writeNetwork();
206
                        tocLyrs.addLayer(inputLayer);
207
                        tocLyrs.addLayer(pseudonodes);
208
                        enableControls();
209
                        
210
//                        JOptionPane.showMessageDialog(null, PluginServices.getText(this,
211
//                                        "done"));
212
                }
213

    
214
                public String getNote() {
215
                        return "Procesando linea..." + " " + getCurrentStep() + " " + "de"
216
                                        + " " + getFinishStep();
217
                }
218

    
219
                public void cancel() {
220
                        setCanceled(true);
221
                }
222

    
223
                /* (non-Javadoc)
224
                 * @see com.iver.utiles.swing.threads.IPipedTask#getResult()
225
                 */
226
                public Object getResult() {
227
                        // TODO Auto-generated method stub
228
                        return null;
229
                }
230

    
231
                /**
232
                 * Implementation of PipeTask interface
233
                 * */
234
                public void setEntry(Object object) {
235
                        //The previous task of this piped task is clean geoprocess
236
                        //whose result es FLayers with two layers
237
                        //first layer has cleaned layer
238
                        //and second layer has pseudonodes layer
239
                        FLayers layers  = (FLayers) object;
240
                        this.inputLayer = (FLyrVect) layers.getLayer(0);
241
                        this.pseudonodes = (FLyrVect) layers.getLayer(1);
242
                }
243
        }
244
        
245
        public void enableControls(){
246
                PluginServices.backgroundExecution(new Runnable(){
247
                        public void run() {
248
                                PluginServices.getMainFrame().enableControls();
249
                                
250
                        }});
251
        }
252
        
253

    
254
        class GenerateRedNetworkTask extends AbstractMonitorableTask {
255
                FLyrVect layer;
256

    
257
                File redFile;
258

    
259
                NetworkFileRedWriter netBuilder;
260
                
261
                
262

    
263
                /**
264
                 * Constructor
265
                 */
266
                GenerateRedNetworkTask(FLyrVect layer, File redFile,
267
                                NetworkFileRedWriter netBuilder) {
268
                        this.layer = layer;
269
                        this.redFile = redFile;
270
                        this.netBuilder = netBuilder;
271
                        setInitialStep(0);
272
                        int numShapes;
273
                        try {
274
                                numShapes = layer.getSource().getShapeCount();
275
                                setFinalStep(numShapes);
276
                                setDeterminatedProcess(true);
277
                                setStatusMessage(PluginServices.getText(this,
278
                                                "Generando_red_a_partir_de_capa_lineal"));
279
                        } catch (DriverIOException e) {
280
                                // TODO Auto-generated catch block
281
                                e.printStackTrace();
282
                        }
283

    
284
                }
285

    
286
                public void run() throws Exception {
287
                        netBuilder.setLayer(layer);
288
                        netBuilder.setCancellableMonitorable(this);
289
                        netBuilder.setRedFile(redFile);
290
                        netBuilder.writeNetwork();
291
                        enableControls();
292
                }
293

    
294
                public String getNote() {
295
                        String processText = PluginServices.getText(this, "Procesando_linea...");
296
                        String of = PluginServices.getText(this, "de");
297
                        return processText + " " + getCurrentStep() + " " + of
298
                                        + " " + getFinishStep();
299
                }
300

    
301
                public void cancel() {
302
                        setCanceled(true);
303
                }
304
                
305
                public Object getResult(){
306
                        return null;
307
                
308
                }
309
                public void setEntry(Object object){
310
                        this.layer = (FLyrVect) object;
311
                }
312
        }
313

    
314
        /**
315
         * It returns a geoprocess to make a CLEAN of the input layer 
316
         * */
317
        private LineCleanGeoprocess createCleanGeoprocess(FLyrVect lineLyr) {
318
                 File outputFile = null;
319
                 JOptionPane.showMessageDialog(null,
320
                                PluginServices.getText(null, "Especifique_fichero_shp_resultante"),
321
                                PluginServices.getText(null, "Fichero_para_capa_corregida"),
322
                                JOptionPane.INFORMATION_MESSAGE);
323
                 JFileChooser jfc = new JFileChooser();
324
                SimpleFileFilter filterShp = new SimpleFileFilter("shp", PluginServices
325
                                .getText(this, "shp_files"));
326
                jfc.setFileFilter(filterShp);
327
                if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
328
                        File newFile = jfc.getSelectedFile();
329
                        String path = newFile.getAbsolutePath();
330
                        if (newFile.exists()) {
331
                                int resp = JOptionPane.showConfirmDialog(
332
                                                (Component) PluginServices.getMainFrame(),
333
                                                PluginServices.getText(this,
334
                                                                "fichero_ya_existe_seguro_desea_guardarlo"),
335
                                                PluginServices.getText(this, "guardar"),
336
                                                JOptionPane.YES_NO_OPTION);
337
                                if (resp != JOptionPane.YES_OPTION) {
338
                                        return null;
339
                                }
340
                        }// if
341
                        if (!(path.toLowerCase().endsWith(".shp"))) {
342
                                path = path + ".shp";
343
                        }
344
                        outputFile = new File(path);
345
                } else {
346
                        return null;
347
                }
348
                LineCleanGeoprocess geoprocess = new LineCleanGeoprocess(lineLyr);
349
                SHPLayerDefinition definition = (SHPLayerDefinition) geoprocess
350
                                .createLayerDefinition();
351
                definition.setFile(outputFile);
352
                ShpSchemaManager schemaManager = new ShpSchemaManager(outputFile
353
                                .getAbsolutePath());
354
                IWriter writer = null;
355
                try {
356
                        int shapeType = definition.getShapeType();
357
                        if (shapeType != XTypes.MULTI) {
358
                                writer = new ShpWriter();
359
                                ((ShpWriter) writer).setFile(definition.getFile());
360
                                writer.initialize(definition);
361
                        } else {
362
                                writer = new MultiShpWriter();
363
                                ((MultiShpWriter) writer).setFile(definition.getFile());
364
                                writer.initialize(definition);
365
                        }
366
                } catch (Exception e1) {
367
                        String error = PluginServices.getText(this,
368
                                        "Error_escritura_resultados");
369
                        String errorDescription = PluginServices.getText(this,
370
                                        "Error_preparar_escritura_resultados");
371
                        return null;
372
                }
373
                geoprocess.setResultLayerProperties(writer, schemaManager);
374
                HashMap params = new HashMap();
375
                params.put("layer_selection", new Boolean(false));
376
                try {
377
                        geoprocess.setParameters(params);
378
                        geoprocess.checkPreconditions();
379
                        return geoprocess;
380
                        
381
                } catch (GeoprocessException e) {
382
                        String error = PluginServices.getText(this, "Error_ejecucion");
383
                        String errorDescription = PluginServices.getText(this,
384
                                        "Error_fallo_geoproceso");
385
                        return null;
386
                }
387

    
388
        }
389

    
390
        private void generateRedNetwork(FLyrVect lyr, FLayers tocLyrs) {
391
                lyr.createSpatialIndex();
392
                NetworkFileRedWriter netBuilder = new NetworkFileRedWriter();
393
                // Por ahora, a pelo, pero hay que sacar un cuadro
394
                // de di?logo para hecer el mapping.
395
                // Tambi?n un cuadro de di?logo para seleccionar
396
                // en qu? tablas quiere escribir, y su formato
397
                // (dbf, postgres, etc)
398

    
399
                ImageIcon icon = new ImageIcon(this.getClass().getClassLoader()
400
                                .getResource("images/net-wizard-logo.jpg"));
401

    
402
                NetWizard wiz = new NetWizard(icon, lyr);
403
                PluginServices.getMDIManager().addWindow(wiz);
404
                if (!wiz.wasFinishPressed())
405
                        return;
406
                // try {
407
                String fieldType = wiz.getFieldType();
408
                String fieldLength = wiz.getFieldLength();
409
                String fieldCost = wiz.getFieldCost();
410
                String fieldSense = wiz.getFieldSense();
411
                netBuilder.setLayer(lyr);
412
                netBuilder.setFieldType(fieldType);
413
                netBuilder.setFieldDist(fieldLength);
414
                netBuilder.setFieldSense(fieldSense);
415
                netBuilder.setFieldCost(fieldCost);
416
                File redFile = NetworkUtils.getNetworkFile(lyr);
417

    
418
                boolean cleanOrigLyr = wiz.getCleanOriginalLayer();
419
                LineCleanGeoprocess clean = null;
420
                if(cleanOrigLyr)
421
                        clean = createCleanGeoprocess(lyr);
422
                boolean applySnap = wiz.getApplySnapTolerance();
423
                if(applySnap){
424
                        double snapTolerance = wiz.getSnapTolerance();
425
                        netBuilder.setSnapTolerance(snapTolerance);
426
                }        
427
                if(clean != null){
428
                        //we wont start the process of network creation
429
                        //until clean geoprocess will be finished
430
                        IPipedTask cleanTask = (IPipedTask) clean.createTask();
431
                        GenerateRedNetworkAfterCleanTask task = 
432
                                new GenerateRedNetworkAfterCleanTask(redFile, 
433
                                                                         netBuilder, tocLyrs);
434
                        
435
                        PipeTask pipe = new PipeTask(cleanTask, (IPipedTask)task);
436
                        
437
                        PluginServices.cancelableBackgroundExecution(pipe);
438
//                        PluginServices.cancelableBackgroundExecution(task);
439
                        
440
                }else{
441
                        GenerateRedNetworkTask task = new GenerateRedNetworkTask(lyr, redFile,
442
                                        netBuilder);
443
                        PluginServices.cancelableBackgroundExecution(task);
444
                }
445
        }
446

    
447
        public boolean isEnabled() {
448
                return true;
449
        }
450

    
451
        public boolean isVisible() {
452
                IWindow f = PluginServices.getMDIManager().getActiveWindow();
453

    
454
                if (f == null) {
455
                        return false;
456
                }
457

    
458
                if (f instanceof View) {
459
                        View vista = (View) f;
460
                        IProjectView model = vista.getModel();
461
                        MapContext mapa = model.getMapContext();
462
                        FLayer[] activeLayers = mapa.getLayers().getActives();
463
                        if (activeLayers.length > 0)
464
                                if (activeLayers[0] instanceof FLyrVect) {
465
                                        FLyrVect lyrVect = (FLyrVect) activeLayers[0];
466
                                        int shapeType;
467
                                        try {
468
                                                shapeType = lyrVect.getShapeType();
469
                                                if (shapeType == FShape.LINE)
470
                                                        return true;
471
                                        } catch (DriverException e) {
472
                                                // TODO Auto-generated catch block
473
                                                e.printStackTrace();
474
                                        }
475
                                }
476
                }
477
                return false;
478

    
479
        }
480

    
481
        public IPreference getPreferencesPage() {
482
                return thePreferencePage;
483
        }
484

    
485
}