Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extGraph / src / org / gvsig / graph / GenerateNetworkExtension.java @ 26861

History | View | Annotate | Download (15.4 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 org.gvsig.graph;
42

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

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

    
51
import org.gvsig.exceptions.BaseException;
52
import org.gvsig.graph.core.NetworkUtils;
53
import org.gvsig.graph.core.writers.NetworkFileRedWriter;
54
import org.gvsig.graph.core.writers.NetworkGvTableWriter;
55
import org.gvsig.graph.gui.wizard.NetWizard;
56
import org.gvsig.graph.preferences.RoutePage;
57

    
58
import com.iver.andami.PluginServices;
59
import com.iver.andami.messages.NotificationManager;
60
import com.iver.andami.plugins.Extension;
61
import com.iver.andami.preferences.IPreference;
62
import com.iver.andami.preferences.IPreferenceExtension;
63
import com.iver.andami.ui.mdiManager.IWindow;
64
import com.iver.cit.gvsig.fmap.MapContext;
65
import com.iver.cit.gvsig.fmap.MapControl;
66
import com.iver.cit.gvsig.fmap.core.FShape;
67
import com.iver.cit.gvsig.fmap.drivers.SHPLayerDefinition;
68
import com.iver.cit.gvsig.fmap.edition.IWriter;
69
import com.iver.cit.gvsig.fmap.edition.ShpSchemaManager;
70
import com.iver.cit.gvsig.fmap.edition.writers.dbf.DbfWriter;
71
import com.iver.cit.gvsig.fmap.edition.writers.shp.MultiShpWriter;
72
import com.iver.cit.gvsig.fmap.edition.writers.shp.ShpWriter;
73
import com.iver.cit.gvsig.fmap.layers.FLayer;
74
import com.iver.cit.gvsig.fmap.layers.FLayers;
75
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
76
import com.iver.cit.gvsig.fmap.layers.SingleLayerIterator;
77
import com.iver.cit.gvsig.geoprocess.core.fmap.GeoprocessException;
78
import com.iver.cit.gvsig.geoprocess.core.fmap.XTypes;
79
import com.iver.cit.gvsig.geoprocess.impl.topology.lineclean.fmap.LineCleanGeoprocess;
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.utiles.SimpleFileFilter;
84
import com.iver.utiles.swing.threads.AbstractMonitorableTask;
85
import com.iver.utiles.swing.threads.IPipedTask;
86
import com.iver.utiles.swing.threads.PipeTask;
87

    
88

    
89
public class GenerateNetworkExtension extends Extension implements
90
                IPreferenceExtension {
91
        private static final IPreference[] thePreferencePages = new IPreference[] {
92
                new RoutePage()
93
                };
94
        public void initialize() {
95
                PluginServices.getIconTheme().registerDefault(
96
                                "build_graph",
97
                                this.getClass().getClassLoader().getResource("images/build_graph.png")
98
                        );                
99
                
100
//                ExtensionPoints extensionPoints = ExtensionPointsSingleton.getInstance();
101
//                ((ExtensionPoint) extensionPoints.get("View_TocActions")).remove("FLyrVectEditProperties");
102
//                ((ExtensionPoint) extensionPoints.get("View_TocActions")).remove("FLyrVectEditProperties2");
103
//                ((ExtensionPoint) extensionPoints.get("View_TocActions")).put("FLyrVectEditProperties",new FLyrVectEditPropertiesTocMenuEntry2());
104
            //extensionPoints.add("View_TocActions","FLyrVectEditProperties2",new FLyrVectEditPropertiesTocMenuEntry2());
105
                
106
        }
107

    
108
        public void execute(String actionCommand) {
109
                IView view = (View) PluginServices.getMDIManager().getActiveWindow();
110
                MapControl mapControl = view.getMapControl();
111
                MapContext map = mapControl.getMapContext();
112
                FLayers tocLyrs = map.getLayers();
113
                SingleLayerIterator lyrIterator = new SingleLayerIterator(tocLyrs);
114
                while (lyrIterator.hasNext()) {
115
                        FLayer lyr = lyrIterator.next();
116
                        if ((lyr.isActive()) && (lyr instanceof FLyrVect)) {
117
                                FLyrVect lyrVect = (FLyrVect) lyr;
118
                                int shapeType;
119
                                try {
120
                                        shapeType = lyrVect.getShapeType();
121
                                        if ((shapeType & FShape.LINE) == FShape.LINE) {
122
                                                if (actionCommand.equalsIgnoreCase("GENERATE_RED")) {
123
                                                        generateRedNetwork(lyrVect, tocLyrs);
124
                                                        return;
125
                                                }
126
                                        }
127
                                } catch (BaseException e) {
128
                                        e.printStackTrace();
129
                                        NotificationManager.addError(e);
130
                                }
131

    
132
                        }
133
                }
134

    
135
        }
136

    
137
        private void generateNetwork(FLyrVect lyr) {
138
                NetworkGvTableWriter netBuilder = new NetworkGvTableWriter();
139
                // Por ahora, a pelo, pero hay que sacar un cuadro
140
                // de di?logo para hecer el mapping.
141
                // Tambi?n un cuadro de di?logo para seleccionar
142
                // en qu? tablas quiere escribir, y su formato
143
                // (dbf, postgres, etc)
144
                String fieldType = "tipored";
145
                String fieldDist = "length";
146
                String fieldSense = "sen";
147
                String fieldCost = "cost";
148
                try {
149
                        netBuilder.setLayer(lyr);
150
                        netBuilder.setFieldType(fieldType);
151
                        netBuilder.setFieldDist(fieldDist);
152
                        netBuilder.setFieldSense(fieldSense);
153
                        netBuilder.setFieldCost(fieldCost);
154
                        DbfWriter nodeWriter = new DbfWriter();
155
                        nodeWriter.setFile(new File("c:/nodes.dbf"));
156

    
157
                        DbfWriter edgeWriter = new DbfWriter();
158
                        edgeWriter.setFile(new File("c:/edges.dbf"));
159

    
160
                        netBuilder.setEdgeWriter(edgeWriter);
161
                        netBuilder.setNodeWriter(nodeWriter);
162

    
163
                        netBuilder.writeNetwork();
164
                } catch (BaseException e1) {
165
                        // TODO Auto-generated catch block
166
                        e1.printStackTrace();
167
                }
168
                JOptionPane.showMessageDialog(null, PluginServices
169
                                .getText(this, "done"));
170
        }
171

    
172
        class GenerateRedNetworkAfterCleanTask
173
                extends AbstractMonitorableTask implements IPipedTask{
174

    
175
                File redFile;
176
                NetworkFileRedWriter netBuilder;
177

    
178
                FLyrVect inputLayer;
179
                FLyrVect pseudonodes;
180
                FLayers tocLyrs;
181

    
182
                /**
183
                 * Constructor
184
                 * @param tocLyrs
185
                 */
186
                GenerateRedNetworkAfterCleanTask(NetworkFileRedWriter netBuilder, FLayers tocLyrs) {
187
                        this.netBuilder = netBuilder;
188
                        this.tocLyrs = tocLyrs;
189
                        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
                        try {
198
                                numShapes = inputLayer.getSource().getShapeCount();
199
                                // lo del 10 es para que termine despu?s de
200
                                // escribir los puntos
201
                                setFinalStep(numShapes + 10);
202

    
203

    
204
                        } catch (BaseException e) {
205
                                // TODO Auto-generated catch block
206
                                e.printStackTrace();
207
                        }
208
                        netBuilder.setLayer(inputLayer);
209
                        netBuilder.setCancellableMonitorable(this);
210
                        netBuilder.setRedFile(redFile);
211
                        netBuilder.writeNetwork();
212
                        tocLyrs.addLayer(inputLayer);
213
                        tocLyrs.addLayer(pseudonodes);
214
                        enableControls();
215
                }
216

    
217
                public String getNote() {
218
                        String processText = PluginServices.getText(this, "Procesando_linea");
219
                        String of = PluginServices.getText(this, "de");
220
                        return processText + " " + getCurrentStep() + " " + of
221
                                        + " " + getFinishStep();
222
                }
223

    
224
                public void cancel() {
225
                        setCanceled(true);
226
                }
227

    
228
                public boolean isFinished() {
229
                        return (getCurrentStep() >= getFinalStep());
230
                }
231

    
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
                /**
241
                 * Implementation of PipeTask interface
242
                 * */
243
                public void setEntry(Object object) {
244
                        //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
                        inputLayer.createSpatialIndex();
251
                        this.redFile = NetworkUtils.getNetworkFile(inputLayer);
252
                        this.pseudonodes = (FLyrVect) layers.getLayer(1);
253
                }
254
        }
255

    
256
        public void enableControls(){
257
                PluginServices.backgroundExecution(new Runnable(){
258
                        public void run() {
259
                                PluginServices.getMainFrame().enableControls();
260

    
261
                        }});
262
        }
263

    
264

    
265
        public class GenerateRedNetworkTask extends AbstractMonitorableTask {
266
                FLyrVect layer;
267

    
268
                File redFile;
269

    
270
                NetworkFileRedWriter netBuilder;
271

    
272

    
273

    
274
                /**
275
                 * Constructor
276
                 */
277
                GenerateRedNetworkTask(FLyrVect layer, File redFile,
278
                                NetworkFileRedWriter netBuilder) {
279
                        this.layer = layer;
280
                        if(! layer.isSpatiallyIndexed())
281
                                layer.createSpatialIndex();
282

    
283
                        this.redFile = redFile;
284
                        this.netBuilder = netBuilder;
285
                        setInitialStep(0);
286
                        int numShapes;
287
                        try {
288
                                numShapes = layer.getSource().getShapeCount();
289
                                // lo del 10 es porque escribimos los nodos despu?s de
290
                                // los tramos.
291
                                setFinalStep(numShapes + 10);
292
                                setDeterminatedProcess(true);
293
                                setStatusMessage(PluginServices.getText(this,
294
                                                "Generando_red_a_partir_de_capa_lineal"));
295
                        } catch (BaseException e) {
296
                                // TODO Auto-generated catch block
297
                                e.printStackTrace();
298
                        }
299

    
300
                }
301

    
302
                public void run() throws Exception {
303
                        netBuilder.setLayer(layer);
304
                        netBuilder.setCancellableMonitorable(this);
305
                        netBuilder.setRedFile(redFile);
306
                        netBuilder.writeNetwork();
307
                        enableControls();
308
                }
309

    
310
                public String getNote() {
311
                        String processText = PluginServices.getText(this, "Procesando_linea");
312
                        String of = PluginServices.getText(this, "de");
313
                        return processText + " " + getCurrentStep() + " " + of
314
                                        + " " + getFinishStep();
315
                }
316

    
317
                public void cancel() {
318
                        setCanceled(true);
319
                }
320

    
321
                public Object getResult(){
322
                        return null;
323

    
324
                }
325
                public void setEntry(Object object){
326
                        this.layer = (FLyrVect) object;
327
                }
328
        }
329

    
330
        /**
331
         * It returns a geoprocess to make a CLEAN of the input layer
332
         * */
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
                        return null;
388
                }
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

    
397
                } 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
                
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
                ImageIcon icon = new ImageIcon(this.getClass().getClassLoader()
416
                                .getResource("images/net-wizard-logo.jpg"));
417

    
418
                NetWizard wiz = new NetWizard(icon, lyr);
419
                PluginServices.getMDIManager().addWindow(wiz);
420
                if (!wiz.wasFinishPressed())
421
                        return;
422
                // try {
423
                String fieldType = wiz.getFieldType();
424
                String fieldLength = wiz.getFieldLength();
425
                String fieldCost = wiz.getFieldCost();
426
                String fieldSense = wiz.getFieldSense();
427
                
428
                netBuilder.setLayer(lyr);
429
                netBuilder.setFieldType(fieldType);
430
                netBuilder.setFieldDist(fieldLength);
431
                netBuilder.setFieldSense(fieldSense);
432
                netBuilder.setFieldCost(fieldCost);
433
                netBuilder.setDigitalizationDirection(wiz.getSenseDigitalization());
434
                netBuilder.setReverseDigitalizationDirection(wiz.getSenseReverseDigitalization());
435
                File redFile = wiz.getNetworkFile();
436

    
437
                boolean cleanOrigLyr = wiz.getCleanOriginalLayer();
438
                LineCleanGeoprocess clean = null;
439
                if(cleanOrigLyr)
440
                        clean = createCleanGeoprocess(lyr);
441
                boolean applySnap = wiz.getApplySnapTolerance();
442
                if(applySnap){
443
                        double snapTolerance = wiz.getSnapTolerance();
444
                        netBuilder.setSnapTolerance(snapTolerance);
445
                }
446
                if(clean != null){
447
                        //we wont start the process of network creation
448
                        //until clean geoprocess will be finished
449
                        IPipedTask cleanTask = (IPipedTask) clean.createTask();
450
                        GenerateRedNetworkAfterCleanTask task =
451
                                new GenerateRedNetworkAfterCleanTask(netBuilder, tocLyrs);
452

    
453
                        PipeTask pipe = new PipeTask(cleanTask, (IPipedTask)task);
454

    
455
                        PluginServices.cancelableBackgroundExecution(pipe);
456
//                        PluginServices.cancelableBackgroundExecution(task);
457

    
458
                }else{
459
                        GenerateRedNetworkTask task = new GenerateRedNetworkTask(lyr, redFile,
460
                                        netBuilder);
461
                        PluginServices.cancelableBackgroundExecution(task);
462
                }
463
        }
464

    
465
        public boolean isEnabled() {
466
                return true;
467
        }
468

    
469
        public boolean isVisible() {
470
                IWindow f = PluginServices.getMDIManager().getActiveWindow();
471

    
472
                if (f == null) {
473
                        return false;
474
                }
475

    
476
                if (f instanceof View) {
477
                        View vista = (View) f;
478
                        IProjectView model = vista.getModel();
479
                        MapContext mapa = model.getMapContext();
480
                        FLayer[] activeLayers = mapa.getLayers().getActives();
481
                        if (activeLayers.length > 0)
482
                                if (activeLayers[0] instanceof FLyrVect) {
483
                                        FLyrVect lyrVect = (FLyrVect) activeLayers[0];
484
                                        int shapeType;
485
                                        try {
486
                                                shapeType = lyrVect.getShapeType();
487
                                                if ((shapeType & FShape.LINE) == FShape.LINE) 
488
//                                                if (shapeType == FShape.LINE)
489
                                                        return true;
490
                                        } catch (BaseException e) {
491
                                                // TODO Auto-generated catch block
492
                                                e.printStackTrace();
493
                                        }
494
                                }
495
                }
496
                return false;
497

    
498
        }
499

    
500
        public IPreference[] getPreferencesPages() {
501
                return thePreferencePages;
502
        }
503

    
504
}