Statistics
| Revision:

svn-gvsig-desktop / branches / v2_0_0_prep / extensions / extGeocoding / src / org / gvsig / geocoding / extension / GeocoController.java @ 27140

History | View | Annotate | Download (17.1 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

    
23
/*
24
 * AUTHORS (In addition to CIT):
25
 * 2008 Prodevelop S.L. main developer
26
 */
27

    
28
package org.gvsig.geocoding.extension;
29

    
30
import java.io.BufferedReader;
31
import java.io.File;
32
import java.io.FileReader;
33
import java.io.IOException;
34
import java.util.ArrayList;
35
import java.util.Iterator;
36
import java.util.List;
37
import java.util.Locale;
38

    
39
import javax.swing.DefaultComboBoxModel;
40
import javax.swing.JFileChooser;
41
import javax.swing.JOptionPane;
42
import javax.swing.table.DefaultTableModel;
43

    
44
import org.gvsig.fmap.dal.DALLocator;
45
import org.gvsig.fmap.dal.DataManager;
46
import org.gvsig.fmap.dal.exception.DataException;
47
import org.gvsig.fmap.dal.exception.ReadException;
48
import org.gvsig.fmap.dal.feature.FeatureStore;
49
import org.gvsig.fmap.dal.feature.FeatureType;
50
import org.gvsig.fmap.mapcontext.layers.FLayer;
51
import org.gvsig.fmap.mapcontext.layers.FLayers;
52
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
53
import org.gvsig.fmap.mapcontrol.MapControl;
54
import org.gvsig.geocoding.gui.GeocodingModel;
55
import org.gvsig.geocoding.gui.GeocodingPanel;
56
import org.gvsig.geocoding.gui.IGeocodingModel;
57
import org.gvsig.geocoding.gui.newpattern.GeocoNewPatternPanel;
58
import org.gvsig.geocoding.patterns.Component;
59
import org.gvsig.geocoding.patterns.Patterngeocoding;
60
import org.gvsig.geocoding.patterns.Settings;
61
import org.gvsig.geocoding.patterns.Source;
62
import org.gvsig.geocoding.results.GeocoLocationSet;
63
import org.gvsig.geocoding.utils.GeocoUtils;
64
import org.gvsig.geocoding.utils.PatternLoader;
65
import org.gvsig.geocoding.utils.ResultProof;
66
import org.gvsig.project.document.table.FeatureTableDocument;
67
import org.slf4j.Logger;
68

    
69
import com.iver.andami.PluginServices;
70
import com.iver.andami.ui.mdiManager.IWindow;
71
import com.iver.cit.gvsig.project.Project;
72
import com.iver.cit.gvsig.project.documents.ProjectDocument;
73
import com.iver.cit.gvsig.project.documents.gui.ProjectWindow;
74
import com.iver.cit.gvsig.project.documents.view.gui.View;
75
import com.iver.utiles.GenericFileFilter;
76
import com.iver.utiles.XMLEntity;
77

    
78
/**
79
 * Controller of all panels
80
 * 
81
 * @author <a href="mailto:jsanz@prodevelop.es"> Jorge Gaspar Sanz Salinas</a>
82
 * @author <a href="mailto:vsanjaime@prodevelop.es"> Vicente Sanjaime Calvet</a>
83
 */
84
public class GeocoController {
85

    
86
        public static final String GEOCODINGELEMENTS = "GeocodingElements";
87

    
88
        private static final Logger log = PluginServices.getLogger();
89

    
90
        private IGeocodingModel gmodel = null;
91

    
92
        private GeocodingPanel gpanel = null;
93

    
94
        private DataManager manager;
95

    
96
        /**
97
         * Controller Constructor
98
         * 
99
         * @param ps
100
         */
101
        public GeocoController() {
102

    
103
                manager = DALLocator.getDataManager();
104

    
105
                /* Load the model */
106
                this.gmodel = new GeocodingModel(this);
107

    
108
                /* Load the view */
109
                this.gpanel = new GeocodingPanel(this);
110
                PluginServices.getMDIManager().addWindow(gpanel);
111

    
112
                /* Show geocoding panel */
113
                this.gpanel.setVisible(true);
114
        }
115

    
116
        /**
117
         * This method loads a Pattern from XML file
118
         * 
119
         * @return
120
         */
121
        public boolean loadPatternXML() {
122
                boolean apto = true;
123
                File thefile = null;
124
                JFileChooser jfc = null;
125
                /* Show the FileChooser to select a pattern file */
126
                try {
127
                        jfc = new JFileChooser();
128
                        jfc.setDialogTitle(PluginServices.getText(this,
129
                                        "load_geoco_pattern"));
130
                        String[] extensions = { "xml" };
131
                        jfc.setCurrentDirectory(new File(""));
132
                        jfc.addChoosableFileFilter(new GenericFileFilter(extensions,
133
                                        PluginServices.getText(this, "pattern_geoco_file")));
134
                        int returnval = jfc
135
                                        .showOpenDialog((java.awt.Component) PluginServices
136
                                                        .getMainFrame());
137
                        if (returnval == JFileChooser.APPROVE_OPTION) {
138
                                thefile = jfc.getSelectedFile();
139
                                log.debug("file opened: " + thefile);
140
                        } else {
141
                                return false;
142
                        }
143
                } catch (Exception e) {
144
                        String mes = PluginServices.getText(this, "geocoerrorloadingfile");
145
                        String tit = PluginServices.getText(this, "geocoding");
146
                        JOptionPane.showMessageDialog(null, mes, tit,
147
                                        JOptionPane.ERROR_MESSAGE);
148
                        log.error("Error loading pattern file", e);
149
                }
150
                /* Parse the xml file */
151
                PatternLoader load = new PatternLoader(thefile);
152
                load.run();
153
                if (apto) {
154
                        apto = load.isApto();
155
                        this.gmodel.setPatternFile(load.getFile());
156
                        this.gmodel.setPattern(load.getPattern());
157
                }
158
                return apto;
159
        }
160

    
161
        /**
162
         * This method gets the structure from the pattern and this shows it
163
         * 
164
         * @return
165
         */
166
        public String showPatternStructure() {
167

    
168
                StringBuffer strbuf = new StringBuffer();
169

    
170
                List<String> components = this.createPatternStructure();
171
                Iterator<String> it = components.iterator();
172
                while (it.hasNext()) {
173
                        strbuf.append("|" + it.next().toUpperCase());
174
                }
175
                strbuf.append("|");
176

    
177
                return strbuf.toString();
178
        }
179

    
180
        /**
181
         * This method creates the structure from the pattern and this shows it
182
         * 
183
         * @return
184
         */
185
        public List<String> createPatternStructure() {
186

    
187
                List<String> structure = new ArrayList<String>();
188
                List<Component> components = this.getGmodel().getPattern().getSource()
189
                                .getAddressComponents();
190
                if (components != null && components.size() > 0) {
191
                        for (int i = 0; i < components.size(); i++) {
192
                                Component compo = components.get(i);
193
                                String element = compo.getElement();
194
                                if (element.compareToIgnoreCase("") != 0) {
195
                                        structure.add(element);
196
                                }
197
                        }
198
                }
199
                return structure;
200
        }
201

    
202
        /**
203
         * This method returns the selected layer by id
204
         * 
205
         * @param capa
206
         */
207
        public void getSelectedLayer(int poscapa) {
208

    
209
                List<FLyrVect> vectCapas = this.getListgvSIGLayers();
210
                if (vectCapas.size() > 0) {
211
                        this.getGmodel().setLyr(vectCapas.get(poscapa));
212
                }
213
        }
214

    
215
        /**
216
         * This method gets the names list of the selected layer
217
         * 
218
         * @return
219
         */
220
        public List<String> getListFieldsLayer() {
221

    
222
                List<String> campos = new ArrayList<String>();
223
                FeatureStore store = null;
224
                FeatureType types = null;
225
                try {
226
                        store = this.getGmodel().getLyr().getFeatureStore();
227
                        types = store.getDefaultFeatureType();
228
                } catch (ReadException e) {
229
                        log.error("Getting layer store", e);
230
                } catch (DataException e) {
231
                        log.error("Reading layer store", e);
232
                }
233
                for (int i = 0; i < types.size(); i++) {
234
                        campos.add(types.getAttributeDescriptor(i).getName());
235
                }
236
                return campos;
237
        }
238

    
239
        /**
240
         * This method creates the table model
241
         * 
242
         * @param nameFields
243
         * @return
244
         */
245
        public DefaultTableModel createTableModel(List<String> nameFields) {
246

    
247
                DefaultTableModel tmod = new DefaultTableModel();
248
                int fils = nameFields.size();
249
                String deftext = PluginServices.getText(this, "combodefaulttext");
250
                String namefields = PluginServices.getText(this, "combonamefields");
251
                String elements = PluginServices.getText(this, "comboaddresselements");
252
                Object[][] data = new String[fils][2];
253
                Object[] titles = new String[] { namefields, elements };
254
                for (int i = 0; i < fils; i++) {
255
                        data[i][0] = nameFields.get(i);
256
                        data[i][1] = deftext;
257
                }
258
                tmod.setDataVector(data, titles);
259
                return tmod;
260
        }
261

    
262
        /**
263
         * This method loads the initial pattern in the model
264
         * 
265
         * @return
266
         */
267
        public Patterngeocoding loadInitialPattern() {
268

    
269
                Patterngeocoding pat = new Patterngeocoding();
270

    
271
                pat.setPatternname("default pattern");
272

    
273
                Source source = new Source();
274

    
275
                List<Component> adrComponents = new ArrayList<Component>();
276
                Component compo1 = new Component("calle", "STREET");
277
                Component compo2 = new Component("via", "TYPE");
278
                Component compo3 = new Component("policia", "NUMBER");
279
                Component compo4 = new Component("puerta", "DOOR");
280
                adrComponents.add(compo1);
281
                adrComponents.add(compo2);
282
                adrComponents.add(compo3);
283
                adrComponents.add(compo4);
284
                source.setAddressComponents(adrComponents);
285
                source.setLayerSource("<![CDATA[prodevelop]]>");
286
                pat.setSource(source);
287

    
288
                pat.setSettings(new Settings());
289

    
290
                return pat;
291
        }
292

    
293
        /**
294
         * This method gets the list with the address components that the user has
295
         * defined in the Geocoding Preferences
296
         * 
297
         * @return
298
         */
299
        public List<String> getListAddressComponents() {
300

    
301
                List<String> components = new ArrayList<String>();
302
                PluginServices ps = PluginServices.getPluginServices(this);
303
                XMLEntity xml = ps.getPersistentXML();
304

    
305
                String tag = GEOCODINGELEMENTS + "_" + getLanguage();
306
                if (xml.contains(tag)) {
307

    
308
                        String nam = String.valueOf(xml.getStringProperty(tag));
309
                        File persistenceFile = new File(nam);
310
                        String str = "";
311

    
312
                        try {
313
                                BufferedReader br = new BufferedReader(new FileReader(
314
                                                persistenceFile));
315
                                while ((str = br.readLine()) != null) {
316
                                        components.add(str);
317
                                }
318
                        } catch (IOException e) {
319
                                log.error("Reading the geocoding elements file", e);
320
                        }
321
                }
322
                return components;
323
        }
324

    
325
        /**
326
         * This method gets the FLyrVect list of the View
327
         * 
328
         * @return
329
         */
330
        public List<FLyrVect> getListgvSIGLayers() {
331

    
332
                List<FLyrVect> layers = new ArrayList<FLyrVect>();
333

    
334
                View view = GeocoUtils.getCurrentView();
335

    
336
                if (view != null) {
337
                        /* Get the layers of the view */
338
                        MapControl mapControl = ((View) view).getMapControl();
339
                        FLayers lyrs = mapControl.getMapContext().getLayers();
340
                        if (lyrs.getLayersCount() > 0) {
341
                                /* Get the layers (FLyrVect) of the view */
342
                                for (int i = 0; i < lyrs.getLayersCount(); i++) {
343
                                        FLayer lyr = lyrs.getLayer(i);
344
                                        if (lyr instanceof FLyrVect) {
345
                                                layers.add((FLyrVect) lyr);
346
                                        }
347
                                }
348
                        }
349
                }
350
                return layers;
351
        }
352

    
353
        /**
354
         * This method gets the application language
355
         * 
356
         * @return
357
         */
358
        private String getLanguage() {
359

    
360
                ArrayList<Locale> myLocs = org.gvsig.i18n.Messages
361
                                .getPreferredLocales();
362
                Locale myLoc = myLocs.size() == 0 ? Locale.ENGLISH : myLocs.get(0);
363

    
364
                /*
365
                 * TODO review and test with differente language codes, included Spanish
366
                 * languages
367
                 */
368
                String lang = myLoc.getLanguage().toLowerCase();
369

    
370
                return lang;
371
        }
372

    
373
        /**
374
         * This method saves the Geocoding Pattern
375
         * 
376
         * @return
377
         */
378
        public boolean savePattern() {
379

    
380
                boolean savedOK = false;
381

    
382
                JFileChooser jfc = new JFileChooser();
383
                jfc.setDialogTitle(PluginServices.getText(this, "save_geoco_pattern"));
384
                String[] extensions = { "xml" };
385
                jfc.addChoosableFileFilter(new GenericFileFilter(extensions,
386
                                PluginServices.getText(this, "pattern_geoco_file")));
387
                int returnval = jfc.showSaveDialog((java.awt.Component) PluginServices
388
                                .getMainFrame());
389

    
390
                if (returnval == JFileChooser.APPROVE_OPTION) {
391

    
392
                        File file = jfc.getSelectedFile();
393
                        log.debug("file created: " + file);
394
                        if (file != null) {
395
                                file = GeocoUtils.addXMLSuffix(file);
396
                                Patterngeocoding pat = this.getGmodel().getPattern();
397
                                pat.setPatternname(file.getName());
398
                                try {
399
                                        pat.saveToXML(file);
400
                                        savedOK = true;
401
                                        log.debug("pattern saved: " + file);
402
                                        this.gmodel.setPatternFile(file);
403
                                } catch (Exception e) {
404
                                        log.error("Serializing the pattern", e);
405
                                        String mes = PluginServices.getText(this,
406
                                                        "geocorrorsavingfile");
407
                                        String tit = PluginServices.getText(this, "geocoding");
408
                                        JOptionPane.showMessageDialog(null, mes, tit,
409
                                                        JOptionPane.ERROR_MESSAGE);
410
                                }
411
                        }
412
                }
413
                return savedOK;
414
        }
415

    
416
        /**
417
         * Run the geocoding process
418
         */
419
        public void runGeocoding() {
420

    
421
        }
422

    
423
        /**
424
         * Run the massive geocoding process
425
         */
426
        public void runMassive() {
427

    
428
        }
429

    
430
        /**
431
         * This method launches the New Pattern Panel
432
         * 
433
         */
434
        public void launchNewPatternPanel() {
435

    
436
                /* Launch the new pattern panel */
437
                GeocoNewPatternPanel ppanel = new GeocoNewPatternPanel(this);
438
                PluginServices.getMDIManager().addWindow(ppanel);
439
                ppanel.setVisible(true);
440

    
441
        }
442

    
443
        /**
444
         * This method updates the GeocodingPanel after save
445
         */
446
        public void updateGeocoGUI() {
447

    
448
                gpanel.setJTextPatternPath(this.getGmodel().getPatternFile()
449
                                .getAbsolutePath());
450
                gpanel.setStructurePattern(this.showPatternStructure());
451
                gpanel.setParamMaxresults(this.getPattern().getSettings().getResults());
452
                gpanel.setParamAccuracy(this.getPattern().getSettings().getAccuracy());
453
                gpanel.setParamQuality(this.getPattern().getSettings().getQuality());
454

    
455
        }
456

    
457
        /**
458
         * Get the pattern from the model
459
         * 
460
         * @return pattern
461
         */
462
        public Patterngeocoding getPattern() {
463
                return this.getGmodel().getPattern();
464
        }
465

    
466
        /**
467
         * This method returns the address formated
468
         * 
469
         * @param dtm
470
         * @return
471
         */
472
        private String getAddressFormated(DefaultTableModel dtm) {
473

    
474
                int cant = dtm.getRowCount();
475
                String str = "";
476

    
477
                if (cant > 0) {
478

    
479
                        str = (String) dtm.getValueAt(0, 1);
480

    
481
                        if (cant > 1) {
482
                                for (int i = 1; i < cant; i++) {
483
                                        String sub = (String) dtm.getValueAt(i, 1);
484
                                        if (i != cant - 1) {
485
                                                str = str + "," + sub;
486
                                        }
487
                                }
488
                        }
489
                }
490
                return str;
491
        }
492

    
493
        /**
494
         * This method saves in the model the formatted address
495
         * 
496
         * @param address
497
         * @param type
498
         * @param typeA
499
         * @return
500
         */
501
        public void saveAddress(String address, int position, int type) {
502
                if (position == gmodel.STREET1) {
503
                        this.getGmodel().setAddress1(address);
504
                        if (type == gmodel.ONE)
505
                                this.getGpanel().getOneA().setStreet1(address);
506
                        if (type == gmodel.CROSS)
507
                                this.getGpanel().getTwoA().setStreet1(address);
508
                        if (type == gmodel.THREE)
509
                                this.getGpanel().getThreeA().setStreet1(address);
510
                }
511
                if (position == gmodel.STREET2) {
512
                        this.getGmodel().setAddress2(address);
513
                        if (type == gmodel.CROSS)
514
                                this.getGpanel().getTwoA().setStreet2(address);
515
                        if (type == gmodel.THREE)
516
                                this.getGpanel().getThreeA().setStreet2(address);
517
                }
518
                if (position == gmodel.STREET3) {
519
                        this.getGmodel().setAddress3(address);
520
                        this.getGpanel().getThreeA().setStreet3(address);
521
                }
522
        }
523

    
524
        /**
525
         * 
526
         * @return
527
         */
528
        public FeatureStore getLayerStore() {
529
                FeatureStore store = null;
530
                try {
531
                        store = gmodel.getLyr().getFeatureStore();
532
                } catch (ReadException e) {
533
                        log.error("Obteniendo el Recorset de la capa", e);
534
                }
535
                return store;
536
        }
537

    
538
        /**
539
         * @return the gmodel
540
         */
541
        public IGeocodingModel getGmodel() {
542
                return gmodel;
543
        }
544

    
545
        /**
546
         * @param gmodel
547
         *            the gmodel to set
548
         */
549
        public void setGmodel(IGeocodingModel gmodel) {
550
                this.gmodel = gmodel;
551
        }
552

    
553
        /**
554
         * @return the gpanel
555
         */
556
        public GeocodingPanel getGpanel() {
557
                return gpanel;
558
        }
559

    
560
        /**
561
         * @param gpanel
562
         *            the gpanel to set
563
         */
564
        public void setGpanel(GeocodingPanel gpanel) {
565
                this.gpanel = gpanel;
566
        }
567

    
568
        /**
569
         * Get a list gvSIG Project tables
570
         * 
571
         * @return
572
         */
573
        public List<FeatureTableDocument> getListgvSIGTables() {
574

    
575
                List<FeatureTableDocument> tables = new ArrayList<FeatureTableDocument>();
576

    
577
                IWindow[] wins = PluginServices.getMDIManager().getAllWindows();
578
                ProjectWindow projWindow = null;
579
                for (int i = 0; i < wins.length; i++) {
580
                        if (wins[i] instanceof ProjectWindow) {
581
                                projWindow = (ProjectWindow) wins[i];
582
                                break;
583
                        }
584
                }
585
                if (projWindow != null) {
586
                        Project p = (Project) projWindow.getWindowModel();
587
                        List<ProjectDocument> documents = p.getDocuments();
588
                        for (ProjectDocument docu : documents) {
589
                                if (docu instanceof FeatureTableDocument) {
590
                                        tables.add((FeatureTableDocument) docu);
591
                                }
592
                        }
593
                }
594

    
595
                return tables;
596
        }
597

    
598
        /**
599
         * Get a list gvSIG Project tables
600
         * 
601
         * @return
602
         */
603
        public DefaultComboBoxModel getModelgvSIGTables() {
604

    
605
                DefaultComboBoxModel comboModel = null;
606

    
607
                List<FeatureTableDocument> tables = this.getListgvSIGTables();
608

    
609
                if (tables.size() > 0) {
610
                        comboModel = new DefaultComboBoxModel();
611
                        for (int i = 0; i < tables.size(); i++) {
612
                                FeatureTableDocument table = tables.get(i);
613
                                comboModel.addElement(table);
614
                        }
615

    
616
                }
617
                return comboModel;
618
        }
619

    
620
        /**
621
         * 
622
         * @return
623
         */
624
        public void geocoding() {
625
                List<GeocoLocationSet> res = ResultProof.getDefaultResult();
626
                this.gmodel.setResults(res);
627
        }
628

    
629
        /**
630
         * 
631
         * @return
632
         */
633
        public List<String> getTableFields() {
634

    
635
                List<String> fields = new ArrayList<String>();
636

    
637
                FeatureTableDocument table = this.getGpanel().getSelectedTable();
638
                FeatureStore store = table.getStore();
639
                FeatureType type = null;
640
                try {
641
                        type = store.getDefaultFeatureType();
642
                } catch (DataException e) {
643
                        log.error("Getting the feature type", e);
644
                }
645
                for (int i = 0; i < type.size(); i++) {
646
                        fields.add(type.getAttributeDescriptor(i).getName());
647
                }
648
                return fields;
649
        }
650
}