Statistics
| Revision:

svn-gvsig-desktop / tags / PilotoRedes_Build_4 / extensions / extGraph_predes / src / com / iver / cit / gvsig / graph / GenerateNetworkExtension.java @ 12191

History | View | Annotate | Download (15.5 KB)

1 8646 fjp
/* 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 8659 azabala
import java.awt.Component;
44 8646 fjp
import java.io.File;
45 8659 azabala
import java.util.HashMap;
46 8646 fjp
47
import javax.swing.ImageIcon;
48 8659 azabala
import javax.swing.JFileChooser;
49 8646 fjp
import javax.swing.JOptionPane;
50
51
import com.iver.andami.PluginServices;
52
import com.iver.andami.messages.NotificationManager;
53
import com.iver.andami.plugins.Extension;
54
import com.iver.andami.preferences.IPreference;
55
import com.iver.andami.preferences.IPreferenceExtension;
56
import com.iver.andami.ui.mdiManager.IWindow;
57
import com.iver.cit.gvsig.fmap.DriverException;
58
import com.iver.cit.gvsig.fmap.MapContext;
59
import com.iver.cit.gvsig.fmap.MapControl;
60
import com.iver.cit.gvsig.fmap.core.FShape;
61
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
62 8659 azabala
import com.iver.cit.gvsig.fmap.drivers.SHPLayerDefinition;
63 8646 fjp
import com.iver.cit.gvsig.fmap.edition.EditionException;
64 8659 azabala
import com.iver.cit.gvsig.fmap.edition.IWriter;
65
import com.iver.cit.gvsig.fmap.edition.ShpSchemaManager;
66 8646 fjp
import com.iver.cit.gvsig.fmap.edition.writers.dbf.DbfWriter;
67 8659 azabala
import com.iver.cit.gvsig.fmap.edition.writers.shp.MultiShpWriter;
68
import com.iver.cit.gvsig.fmap.edition.writers.shp.ShpWriter;
69 8646 fjp
import com.iver.cit.gvsig.fmap.layers.FLayer;
70 8659 azabala
import com.iver.cit.gvsig.fmap.layers.FLayers;
71 8646 fjp
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
72
import com.iver.cit.gvsig.fmap.layers.SingleLayerIterator;
73 8659 azabala
import com.iver.cit.gvsig.geoprocess.core.fmap.GeoprocessException;
74
import com.iver.cit.gvsig.geoprocess.core.fmap.XTypes;
75 8646 fjp
import com.iver.cit.gvsig.graph.core.writers.NetworkFileRedWriter;
76
import com.iver.cit.gvsig.graph.core.writers.NetworkGvTableWriter;
77
import com.iver.cit.gvsig.graph.gui.wizard.NetWizard;
78
import com.iver.cit.gvsig.graph.preferences.RoutePage;
79
import com.iver.cit.gvsig.project.documents.view.IProjectView;
80
import com.iver.cit.gvsig.project.documents.view.gui.IView;
81
import com.iver.cit.gvsig.project.documents.view.gui.View;
82 12188 fjp
import com.iver.cit.gvsig.project.documents.view.toc.FLyrVectEditPropertiesTocMenuEntry2;
83 8659 azabala
import com.iver.cit.gvsig.topology.lineclean.fmap.LineCleanGeoprocess;
84
import com.iver.utiles.SimpleFileFilter;
85 12188 fjp
import com.iver.utiles.extensionPoints.ExtensionPoint;
86
import com.iver.utiles.extensionPoints.ExtensionPoints;
87
import com.iver.utiles.extensionPoints.ExtensionPointsSingleton;
88 8646 fjp
import com.iver.utiles.swing.threads.AbstractMonitorableTask;
89 8671 azabala
import com.iver.utiles.swing.threads.IPipedTask;
90
import com.iver.utiles.swing.threads.PipeTask;
91 8646 fjp
92 8671 azabala
93 8736 azabala
public class GenerateNetworkExtension extends Extension implements
94
                IPreferenceExtension {
95
        private static final IPreference thePreferencePage = new RoutePage();
96 8646 fjp
        public void initialize() {
97 12188 fjp
                ExtensionPoints extensionPoints = ExtensionPointsSingleton.getInstance();
98
                ((ExtensionPoint) extensionPoints.get("View_TocActions")).remove("FLyrVectEditProperties");
99
                ((ExtensionPoint) extensionPoints.get("View_TocActions")).remove("FLyrVectEditProperties2");
100
                ((ExtensionPoint) extensionPoints.get("View_TocActions")).put("FLyrVectEditProperties",new FLyrVectEditPropertiesTocMenuEntry2());
101
            //extensionPoints.add("View_TocActions","FLyrVectEditProperties2",new FLyrVectEditPropertiesTocMenuEntry2());
102
103 8646 fjp
        }
104
105
        public void execute(String actionCommand) {
106
                IView view = (View) PluginServices.getMDIManager().getActiveWindow();
107
                MapControl mapControl = view.getMapControl();
108
                MapContext map = mapControl.getMapContext();
109 8659 azabala
                FLayers tocLyrs = map.getLayers();
110
                SingleLayerIterator lyrIterator = new SingleLayerIterator(tocLyrs);
111 8646 fjp
                while (lyrIterator.hasNext()) {
112
                        FLayer lyr = lyrIterator.next();
113 8659 azabala
                        if ((lyr.isActive()) && (lyr instanceof FLyrVect)) {
114 8646 fjp
                                FLyrVect lyrVect = (FLyrVect) lyr;
115
                                int shapeType;
116
                                try {
117
                                        shapeType = lyrVect.getShapeType();
118 8659 azabala
                                        if (shapeType == FShape.LINE) {
119 8646 fjp
                                                if (actionCommand.equalsIgnoreCase("GENERATE_RED")) {
120 8659 azabala
                                                        generateRedNetwork(lyrVect, tocLyrs);
121 8646 fjp
                                                        return;
122
                                                }
123
                                        }
124
                                } catch (DriverException e) {
125
                                        e.printStackTrace();
126
                                        NotificationManager.addError(e);
127
                                }
128
129
                        }
130
                }
131
132
        }
133
134
        private void generateNetwork(FLyrVect lyr) {
135
                NetworkGvTableWriter netBuilder = new NetworkGvTableWriter();
136
                // Por ahora, a pelo, pero hay que sacar un cuadro
137
                // de di?logo para hecer el mapping.
138
                // Tambi?n un cuadro de di?logo para seleccionar
139
                // en qu? tablas quiere escribir, y su formato
140
                // (dbf, postgres, etc)
141 8659 azabala
                String fieldType = "tipored";
142
                String fieldDist = "length";
143
                String fieldSense = "sen";
144 8646 fjp
                String fieldCost = "cost";
145
                try {
146
                        netBuilder.setLayer(lyr);
147
                        netBuilder.setFieldType(fieldType);
148
                        netBuilder.setFieldDist(fieldDist);
149
                        netBuilder.setFieldSense(fieldSense);
150
                        netBuilder.setFieldCost(fieldCost);
151
                        DbfWriter nodeWriter = new DbfWriter();
152
                        nodeWriter.setFile(new File("c:/nodes.dbf"));
153
154
                        DbfWriter edgeWriter = new DbfWriter();
155
                        edgeWriter.setFile(new File("c:/edges.dbf"));
156
157
                        netBuilder.setEdgeWriter(edgeWriter);
158
                        netBuilder.setNodeWriter(nodeWriter);
159
160
                        netBuilder.writeNetwork();
161
                } catch (DriverException e1) {
162
                        // TODO Auto-generated catch block
163
                        e1.printStackTrace();
164
                } catch (EditionException e1) {
165
                        // TODO Auto-generated catch block
166
                        e1.printStackTrace();
167
                }
168 8659 azabala
                JOptionPane.showMessageDialog(null, PluginServices
169
                                .getText(this, "done"));
170 8646 fjp
        }
171 8736 azabala
172
        class GenerateRedNetworkAfterCleanTask
173 8671 azabala
                extends AbstractMonitorableTask implements IPipedTask{
174 8736 azabala
175 8659 azabala
                File redFile;
176
                NetworkFileRedWriter netBuilder;
177 8736 azabala
178 8671 azabala
                FLyrVect inputLayer;
179 8677 azabala
                FLyrVect pseudonodes;
180 8726 azabala
                FLayers tocLyrs;
181 8736 azabala
182 8659 azabala
                /**
183
                 * Constructor
184 8726 azabala
                 * @param tocLyrs
185 8659 azabala
                 */
186 8736 azabala
                GenerateRedNetworkAfterCleanTask(NetworkFileRedWriter netBuilder, FLayers tocLyrs) {
187 8659 azabala
                        this.netBuilder = netBuilder;
188 8726 azabala
                        this.tocLyrs = tocLyrs;
189 8659 azabala
                        setInitialStep(0);
190
                        setDeterminatedProcess(true);
191
                        setStatusMessage(PluginServices.getText(this,
192
                        "Generando_red_a_partir_de_capa_lineal"));
193
                }
194
195
                public void run() throws Exception {
196
                        int numShapes;
197 8736 azabala
                        try {
198 8677 azabala
                                numShapes = inputLayer.getSource().getShapeCount();
199 8775 fjp
                                // lo del 10 es para que termine despu?s de
200
                                // escribir los puntos
201
                                setFinalStep(numShapes + 10);
202 8736 azabala
203
204 8659 azabala
                        } catch (DriverIOException e) {
205
                                // TODO Auto-generated catch block
206
                                e.printStackTrace();
207
                        }
208 8677 azabala
                        netBuilder.setLayer(inputLayer);
209 8659 azabala
                        netBuilder.setCancellableMonitorable(this);
210
                        netBuilder.setRedFile(redFile);
211
                        netBuilder.writeNetwork();
212 8726 azabala
                        tocLyrs.addLayer(inputLayer);
213
                        tocLyrs.addLayer(pseudonodes);
214
                        enableControls();
215 8659 azabala
                }
216
217
                public String getNote() {
218 8758 azabala
                        String processText = PluginServices.getText(this, "Procesando_linea");
219 8736 azabala
                        String of = PluginServices.getText(this, "de");
220
                        return processText + " " + getCurrentStep() + " " + of
221 8659 azabala
                                        + " " + getFinishStep();
222
                }
223
224
                public void cancel() {
225
                        setCanceled(true);
226
                }
227 8736 azabala
228
                public boolean isFinished() {
229
                        return (getCurrentStep() >= getFinalStep());
230
                }
231 8671 azabala
232
                /* (non-Javadoc)
233
                 * @see com.iver.utiles.swing.threads.IPipedTask#getResult()
234
                 */
235
                public Object getResult() {
236
                        // TODO Auto-generated method stub
237
                        return null;
238
                }
239
240 8677 azabala
                /**
241
                 * Implementation of PipeTask interface
242
                 * */
243 8671 azabala
                public void setEntry(Object object) {
244 8677 azabala
                        //The previous task of this piped task is clean geoprocess
245
                        //whose result es FLayers with two layers
246
                        //first layer has cleaned layer
247
                        //and second layer has pseudonodes layer
248
                        FLayers layers  = (FLayers) object;
249
                        this.inputLayer = (FLyrVect) layers.getLayer(0);
250 8736 azabala
                        inputLayer.createSpatialIndex();
251
                        this.redFile = NetworkUtils.getNetworkFile(inputLayer);
252 8677 azabala
                        this.pseudonodes = (FLyrVect) layers.getLayer(1);
253 8671 azabala
                }
254 8659 azabala
        }
255 8736 azabala
256 8726 azabala
        public void enableControls(){
257
                PluginServices.backgroundExecution(new Runnable(){
258
                        public void run() {
259
                                PluginServices.getMainFrame().enableControls();
260 8736 azabala
261 8726 azabala
                        }});
262
        }
263 8736 azabala
264 8659 azabala
265
        class GenerateRedNetworkTask extends AbstractMonitorableTask {
266 8646 fjp
                FLyrVect layer;
267 8659 azabala
268 8646 fjp
                File redFile;
269 8659 azabala
270 8646 fjp
                NetworkFileRedWriter netBuilder;
271 8736 azabala
272
273 8659 azabala
274 8646 fjp
                /**
275
                 * Constructor
276 8659 azabala
                 */
277
                GenerateRedNetworkTask(FLyrVect layer, File redFile,
278
                                NetworkFileRedWriter netBuilder) {
279 8646 fjp
                        this.layer = layer;
280 8736 azabala
                        if(! layer.isSpatiallyIndexed())
281
                                layer.createSpatialIndex();
282
283 8646 fjp
                        this.redFile = redFile;
284
                        this.netBuilder = netBuilder;
285
                        setInitialStep(0);
286
                        int numShapes;
287
                        try {
288
                                numShapes = layer.getSource().getShapeCount();
289 8772 fjp
                                // lo del 10 es porque escribimos los nodos despu?s de
290
                                // los tramos.
291
                                setFinalStep(numShapes + 10);
292 8646 fjp
                                setDeterminatedProcess(true);
293 8659 azabala
                                setStatusMessage(PluginServices.getText(this,
294
                                                "Generando_red_a_partir_de_capa_lineal"));
295 8646 fjp
                        } catch (DriverIOException e) {
296
                                // TODO Auto-generated catch block
297
                                e.printStackTrace();
298
                        }
299 8659 azabala
300 8646 fjp
                }
301 8659 azabala
302 8646 fjp
                public void run() throws Exception {
303
                        netBuilder.setLayer(layer);
304
                        netBuilder.setCancellableMonitorable(this);
305
                        netBuilder.setRedFile(redFile);
306
                        netBuilder.writeNetwork();
307 8726 azabala
                        enableControls();
308 8659 azabala
                }
309
310 8646 fjp
                public String getNote() {
311 8758 azabala
                        String processText = PluginServices.getText(this, "Procesando_linea");
312 8726 azabala
                        String of = PluginServices.getText(this, "de");
313
                        return processText + " " + getCurrentStep() + " " + of
314 8659 azabala
                                        + " " + getFinishStep();
315 8646 fjp
                }
316
317
                public void cancel() {
318
                        setCanceled(true);
319
                }
320 8736 azabala
321 8671 azabala
                public Object getResult(){
322
                        return null;
323 8736 azabala
324 8671 azabala
                }
325
                public void setEntry(Object object){
326
                        this.layer = (FLyrVect) object;
327
                }
328 8646 fjp
        }
329 8659 azabala
330
        /**
331 8736 azabala
         * It returns a geoprocess to make a CLEAN of the input layer
332 8659 azabala
         * */
333
        private LineCleanGeoprocess createCleanGeoprocess(FLyrVect lineLyr) {
334
                 File outputFile = null;
335
                 JOptionPane.showMessageDialog(null,
336
                                PluginServices.getText(null, "Especifique_fichero_shp_resultante"),
337
                                PluginServices.getText(null, "Fichero_para_capa_corregida"),
338
                                JOptionPane.INFORMATION_MESSAGE);
339
                 JFileChooser jfc = new JFileChooser();
340
                SimpleFileFilter filterShp = new SimpleFileFilter("shp", PluginServices
341
                                .getText(this, "shp_files"));
342
                jfc.setFileFilter(filterShp);
343
                if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
344
                        File newFile = jfc.getSelectedFile();
345
                        String path = newFile.getAbsolutePath();
346
                        if (newFile.exists()) {
347
                                int resp = JOptionPane.showConfirmDialog(
348
                                                (Component) PluginServices.getMainFrame(),
349
                                                PluginServices.getText(this,
350
                                                                "fichero_ya_existe_seguro_desea_guardarlo"),
351
                                                PluginServices.getText(this, "guardar"),
352
                                                JOptionPane.YES_NO_OPTION);
353
                                if (resp != JOptionPane.YES_OPTION) {
354
                                        return null;
355
                                }
356
                        }// if
357
                        if (!(path.toLowerCase().endsWith(".shp"))) {
358
                                path = path + ".shp";
359
                        }
360
                        outputFile = new File(path);
361
                } else {
362
                        return null;
363
                }
364
                LineCleanGeoprocess geoprocess = new LineCleanGeoprocess(lineLyr);
365
                SHPLayerDefinition definition = (SHPLayerDefinition) geoprocess
366
                                .createLayerDefinition();
367
                definition.setFile(outputFile);
368
                ShpSchemaManager schemaManager = new ShpSchemaManager(outputFile
369
                                .getAbsolutePath());
370
                IWriter writer = null;
371
                try {
372
                        int shapeType = definition.getShapeType();
373
                        if (shapeType != XTypes.MULTI) {
374
                                writer = new ShpWriter();
375
                                ((ShpWriter) writer).setFile(definition.getFile());
376
                                writer.initialize(definition);
377
                        } else {
378
                                writer = new MultiShpWriter();
379
                                ((MultiShpWriter) writer).setFile(definition.getFile());
380
                                writer.initialize(definition);
381
                        }
382
                } catch (Exception e1) {
383
                        String error = PluginServices.getText(this,
384
                                        "Error_escritura_resultados");
385
                        String errorDescription = PluginServices.getText(this,
386
                                        "Error_preparar_escritura_resultados");
387 8712 azabala
                        return null;
388 8659 azabala
                }
389
                geoprocess.setResultLayerProperties(writer, schemaManager);
390
                HashMap params = new HashMap();
391
                params.put("layer_selection", new Boolean(false));
392
                try {
393
                        geoprocess.setParameters(params);
394
                        geoprocess.checkPreconditions();
395
                        return geoprocess;
396 8736 azabala
397 8659 azabala
                } catch (GeoprocessException e) {
398
                        String error = PluginServices.getText(this, "Error_ejecucion");
399
                        String errorDescription = PluginServices.getText(this,
400
                                        "Error_fallo_geoproceso");
401
                        return null;
402
                }
403
404
        }
405
406
        private void generateRedNetwork(FLyrVect lyr, FLayers tocLyrs) {
407 8646 fjp
                lyr.createSpatialIndex();
408
                NetworkFileRedWriter netBuilder = new NetworkFileRedWriter();
409
                // Por ahora, a pelo, pero hay que sacar un cuadro
410
                // de di?logo para hecer el mapping.
411
                // Tambi?n un cuadro de di?logo para seleccionar
412
                // en qu? tablas quiere escribir, y su formato
413
                // (dbf, postgres, etc)
414
415 8659 azabala
                ImageIcon icon = new ImageIcon(this.getClass().getClassLoader()
416
                                .getResource("images/net-wizard-logo.jpg"));
417 8646 fjp
418
                NetWizard wiz = new NetWizard(icon, lyr);
419
                PluginServices.getMDIManager().addWindow(wiz);
420 8659 azabala
                if (!wiz.wasFinishPressed())
421 8646 fjp
                        return;
422 8659 azabala
                // try {
423
                String fieldType = wiz.getFieldType();
424
                String fieldLength = wiz.getFieldLength();
425
                String fieldCost = wiz.getFieldCost();
426
                String fieldSense = wiz.getFieldSense();
427
                netBuilder.setLayer(lyr);
428
                netBuilder.setFieldType(fieldType);
429
                netBuilder.setFieldDist(fieldLength);
430
                netBuilder.setFieldSense(fieldSense);
431
                netBuilder.setFieldCost(fieldCost);
432
                File redFile = NetworkUtils.getNetworkFile(lyr);
433
434
                boolean cleanOrigLyr = wiz.getCleanOriginalLayer();
435
                LineCleanGeoprocess clean = null;
436
                if(cleanOrigLyr)
437
                        clean = createCleanGeoprocess(lyr);
438
                boolean applySnap = wiz.getApplySnapTolerance();
439
                if(applySnap){
440 8651 azabala
                        double snapTolerance = wiz.getSnapTolerance();
441 8659 azabala
                        netBuilder.setSnapTolerance(snapTolerance);
442 8736 azabala
                }
443 8659 azabala
                if(clean != null){
444
                        //we wont start the process of network creation
445
                        //until clean geoprocess will be finished
446 8671 azabala
                        IPipedTask cleanTask = (IPipedTask) clean.createTask();
447 8736 azabala
                        GenerateRedNetworkAfterCleanTask task =
448
                                new GenerateRedNetworkAfterCleanTask(netBuilder, tocLyrs);
449
450 8671 azabala
                        PipeTask pipe = new PipeTask(cleanTask, (IPipedTask)task);
451 8736 azabala
452 8671 azabala
                        PluginServices.cancelableBackgroundExecution(pipe);
453
//                        PluginServices.cancelableBackgroundExecution(task);
454 8736 azabala
455 8659 azabala
                }else{
456
                        GenerateRedNetworkTask task = new GenerateRedNetworkTask(lyr, redFile,
457
                                        netBuilder);
458 8646 fjp
                        PluginServices.cancelableBackgroundExecution(task);
459 8659 azabala
                }
460 8646 fjp
        }
461
462
        public boolean isEnabled() {
463
                return true;
464
        }
465
466
        public boolean isVisible() {
467
                IWindow f = PluginServices.getMDIManager().getActiveWindow();
468
469
                if (f == null) {
470
                        return false;
471
                }
472
473
                if (f instanceof View) {
474
                        View vista = (View) f;
475
                        IProjectView model = vista.getModel();
476
                        MapContext mapa = model.getMapContext();
477
                        FLayer[] activeLayers = mapa.getLayers().getActives();
478
                        if (activeLayers.length > 0)
479 8659 azabala
                                if (activeLayers[0] instanceof FLyrVect) {
480 8646 fjp
                                        FLyrVect lyrVect = (FLyrVect) activeLayers[0];
481 8659 azabala
                                        int shapeType;
482 8646 fjp
                                        try {
483
                                                shapeType = lyrVect.getShapeType();
484
                                                if (shapeType == FShape.LINE)
485
                                                        return true;
486
                                        } catch (DriverException e) {
487
                                                // TODO Auto-generated catch block
488
                                                e.printStackTrace();
489
                                        }
490 8659 azabala
                                }
491 8646 fjp
                }
492
                return false;
493
494
        }
495
496 8736 azabala
        public IPreference getPreferencesPage() {
497
                return thePreferencePage;
498
        }
499
500 8646 fjp
}