Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extNormalization / src / org / gvsig / normalization / gui / NormPanelModel.java @ 32312

History | View | Annotate | Download (23.2 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 development
26
 */
27

    
28
package org.gvsig.normalization.gui;
29

    
30
import java.awt.Component;
31
import java.io.File;
32
import java.io.FileNotFoundException;
33
import java.text.DecimalFormatSymbols;
34
import java.util.ArrayList;
35
import java.util.List;
36
import java.util.Locale;
37

    
38
import javax.swing.DefaultListModel;
39
import javax.swing.JFileChooser;
40
import javax.swing.JOptionPane;
41
import javax.swing.event.ChangeEvent;
42
import javax.swing.event.ChangeListener;
43

    
44
import org.apache.log4j.Logger;
45
import org.gvsig.normalization.operations.JoinedTableNormalization;
46
import org.gvsig.normalization.operations.NormAlgorithm;
47
import org.gvsig.normalization.operations.Normalization;
48
import org.gvsig.normalization.operations.NormalizationNewTable;
49
import org.gvsig.normalization.operations.StringListNormalization;
50
import org.gvsig.normalization.operations.TableNormalization;
51
import org.gvsig.normalization.patterns.Element;
52
import org.gvsig.normalization.patterns.Fieldseparator;
53
import org.gvsig.normalization.patterns.Fieldtype;
54
import org.gvsig.normalization.patterns.Infieldseparators;
55
import org.gvsig.normalization.patterns.NormalizationPattern;
56
import org.gvsig.normalization.patterns.Stringvalue;
57

    
58
import com.hardcode.gdbms.engine.data.DataSource;
59
import com.hardcode.gdbms.engine.data.DataSourceFactory;
60
import com.iver.andami.PluginServices;
61
import com.iver.cit.gvsig.ProjectExtension;
62
import com.iver.cit.gvsig.fmap.drivers.FieldDescription;
63
import com.iver.cit.gvsig.fmap.edition.EditableAdapter;
64
import com.iver.cit.gvsig.fmap.edition.IEditableSource;
65
import com.iver.cit.gvsig.fmap.edition.IRowEdited;
66
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
67
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
68
import com.iver.cit.gvsig.project.Project;
69
import com.iver.cit.gvsig.project.ProjectFactory;
70
import com.iver.cit.gvsig.project.documents.ProjectDocumentFactory;
71
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
72
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
73
import com.iver.cit.gvsig.project.documents.table.gui.Table;
74
import com.iver.utiles.GenericFileFilter;
75
import com.iver.utiles.XMLEntity;
76
import com.iver.utiles.extensionPoints.ExtensionPoints;
77
import com.iver.utiles.extensionPoints.ExtensionPointsSingleton;
78

    
79
/**
80
 * Model of the Normalization panel
81
 * 
82
 * @author <a href="mailto:jsanz@prodevelop.es"> Jorge Gaspar Sanz Salinas</a>
83
 * @author <a href="mailto:vsanjaime@prodevelop.es"> Vicent Sanjaime Calvet</a>
84
 */
85

    
86
public class NormPanelModel implements INormPanelModel {
87

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

    
90
        private List<ChangeListener> listeners = new ArrayList<ChangeListener>();
91
        private String fieldToNormalize;
92
        private String[] samples;
93
        private NormalizationPattern pattern;
94
        private Table tab;
95
        private boolean inNewTable;
96
        private int contador = 1;
97
        private String[] relateNames;
98
        private List<String> fileChains;
99
        private boolean isFile;
100
        private String nameFile;
101

    
102
        /* SINGLETON DEFINITION */
103
        private volatile static INormPanelModel uniqueInstance;
104

    
105
        /**
106
         * Get the instance of panel model
107
         * 
108
         * @return panel model
109
         */
110
        public static INormPanelModel getInstance() {
111
                if (uniqueInstance == null) {
112
                        synchronized (NormPanelModel.class) {
113
                                if (uniqueInstance == null) {
114
                                        uniqueInstance = new NormPanelModel();
115
                                }
116
                        }
117
                }
118
                return uniqueInstance;
119
        }
120

    
121
        /**
122
         * Constructor
123
         */
124
        private NormPanelModel() {
125
                initPattern();
126
        }
127

    
128
        /**
129
         * This method fills the GUI sample table with the samples
130
         * 
131
         * @return Object[][]
132
         */
133
        public Object[][] normalizeSamples() {
134

    
135
                int numFields = pattern.getElements().size();
136
                Object[][] results = new Object[NormalizationPanel.SAMPLES][numFields];
137

    
138
                NormAlgorithm na = new NormAlgorithm(this.pattern);
139
                List<String> chains;
140
                for (int i = 0; i < NormalizationPanel.SAMPLES; i++) {
141
                        chains = na.splitChain(samples[i]);
142
                        numFields = chains.size();
143
                        for (int j = 0; j < numFields; j++) {
144
                                results[i][j] = chains.get(j);
145
                        }
146
                }
147
                return results;
148
        }
149

    
150
        /**
151
         * Run the process of normalization
152
         * 
153
         * @return process ok
154
         */
155
        public boolean runModel(ChangeListener listener) {
156
                this.registerListener(listener);
157
                Normalization normAction = null;
158
                // REQUEST FILE TO OUPUT THE DBF
159
                File thefile = null;
160
                if (this.isFile || (!this.isFile && this.inNewTable)) {
161
                        thefile = getDBFFile();
162
                        if (thefile == null) {
163
                                update("INFO.endnormalizing");
164
                                return false;
165
                        }
166
                        if (thefile.exists()) {
167
                                update("INFO.fileexists");
168
                                update("INFO.endnormalizing");
169
                                return false;
170
                        }
171
                }
172

    
173
                // FILE NORMALIZATION
174
                if (this.isFile) {
175
                        normAction = new StringListNormalization(pattern, fileChains,
176
                                        thefile);
177
                } else {
178
                        IEditableSource source = tab.getModel().getModelo();
179
                        int index = tab.getSelectedFieldIndices().nextSetBit(0);
180

    
181
                        if (!this.inNewTable) {
182
                                // ONE TABLE
183
                                normAction = new TableNormalization(source, index, pattern);
184
                        } else {
185
                                // JOINED TABLE
186
                                normAction = new JoinedTableNormalization(source, index,
187
                                                pattern, relateNames, thefile);
188
                        }
189
                }
190

    
191
                normAction.registerListener(listener);
192
                boolean pre = normAction.preProcess();
193

    
194
                if (pre) {
195
                        PluginServices.cancelableBackgroundExecution(new NormalizationTask(
196
                                        normAction, this));
197
                } else {
198
                        log.error("Error preprocessing tables");
199
                        return false;
200
                }
201

    
202
                if (normAction instanceof NormalizationNewTable) {
203
                        NormalizationNewTable normTable = (NormalizationNewTable) normAction;
204
                        this.loadTable(normTable);
205
                }
206
                return true;
207
        }
208

    
209
        /**
210
         * This method up the selected element one position in the list of Elements
211
         * 
212
         * @param pos
213
         */
214
        public void fieldUp(int pos) {
215

    
216
                int nu = pattern.getElements().size();
217

    
218
                if (pos > 0 && nu > 1) {
219
                        int newpos = pos - 1;
220
                        Element[] ad = pattern.getArrayElements();
221
                        Element ele21 = ad[pos];
222
                        Element ele12 = ad[newpos];
223

    
224
                        ad[newpos] = ele21;
225
                        ad[pos] = ele12;
226
                        List<Element> elems = new ArrayList<Element>();
227
                        for (int i = 0; i < ad.length; i++) {
228
                                elems.add(ad[i]);
229
                        }
230
                        pattern.setElements(elems);
231
                }
232
        }
233

    
234
        /**
235
         * This method down the selected element one position in the list of
236
         * Elements
237
         * 
238
         * @param pos
239
         */
240
        public void fieldDown(int pos) {
241
                int nu = pattern.getElements().size();
242

    
243
                if (pos != (nu - 1) && nu > 1) {
244
                        int newpos = pos + 1;
245
                        Element[] ad = pattern.getArrayElements();
246
                        Element ele21 = ad[pos];
247
                        Element ele12 = ad[newpos];
248

    
249
                        ad[newpos] = ele21;
250
                        ad[pos] = ele12;
251
                        List<Element> elems = new ArrayList<Element>();
252
                        for (int i = 0; i < ad.length; i++) {
253
                                elems.add(ad[i]);
254
                        }
255
                        pattern.setElements(elems);
256
                }
257
        }
258

    
259
        /**
260
         * This method adds a new element to the pattern
261
         */
262

    
263
        public void addField() {
264

    
265
                contador++;
266
                int tam = pattern.getElements().size();
267
                Element eleme = new Element();
268

    
269
                Fieldseparator fsep = new Fieldseparator();
270
                fsep.setSemicolonsep(true);
271
                fsep.setJoinsep(false);
272
                fsep.setColonsep(false);
273
                fsep.setSpacesep(false);
274
                fsep.setTabsep(false);
275

    
276
                String nam = "";
277
                boolean isOkName = true;
278
                do {
279
                        isOkName = true;
280
                        nam = "NewField" + contador;
281
                        for (int i = 0; i < tam; i++) {
282
                                String napat = ((Element) pattern.getElements().get(i))
283
                                                .getFieldname();
284
                                if (napat.compareToIgnoreCase(nam) == 0) {
285
                                        isOkName = false;
286
                                        break;
287
                                }
288
                        }
289
                        if (!isOkName) {
290
                                contador++;
291
                        }
292

    
293
                } while (!isOkName);
294

    
295
                // validate the new field name
296
                String vname = validateFieldName(nam);
297
                eleme.setFieldname(vname);
298
                eleme.setFieldseparator(fsep);
299
                eleme.setInfieldseparators(getDefaultInfieldseparators());
300
                eleme.setFieldtype(getDefaultNewFieldType());
301
                eleme.setFieldwidth(0);
302
                eleme.setImportfield(true);
303

    
304
                List<Element> elems = pattern.getElements();
305
                elems.add(tam, eleme);
306
        }
307

    
308
        /**
309
         * This method erases a selected element to the list
310
         * 
311
         * @param pos
312
         *            position
313
         */
314
        public void deleteField(int pos) {
315
                int conta = pattern.getElements().size();
316
                if (conta > 1) {
317
                        pattern.getElements().remove(pos);
318
                }
319
        }
320

    
321
        /**
322
         * This method saves a Normalization pattern to XML file *
323
         */
324
        public void savePatternXML() {
325

    
326
                JFileChooser jfc = new JFileChooser();
327
                jfc.setDialogTitle(PluginServices.getText(this, "save_norm_pattern"));
328
                String[] extensions = { "xml" };
329
                jfc.setCurrentDirectory(new File(getFolderPattern()));
330
                jfc.addChoosableFileFilter(new GenericFileFilter(extensions,
331
                                PluginServices.getText(this, "pattern_norm_file")));
332
                int returnval = jfc.showSaveDialog((Component) PluginServices
333
                                .getMainFrame());
334

    
335
                if (returnval == JFileChooser.APPROVE_OPTION) {
336
                        File thefile = jfc.getSelectedFile();
337
                        // Check if the file has extension
338
                        if (!(thefile.getPath().toLowerCase().endsWith(".xml"))) {
339
                                thefile = new File(thefile.getPath() + ".xml");
340
                        }
341

    
342
                        if (thefile.exists()) {
343

    
344
                                int n = JOptionPane.showConfirmDialog(null, PluginServices
345
                                                .getText(null, "file_exists"), PluginServices.getText(
346
                                                null, "save_norm_pattern"), JOptionPane.YES_NO_OPTION);
347
                                if (n == JOptionPane.YES_OPTION) {
348
                                        writeSaveFile(thefile);
349
                                } else if (n == JOptionPane.NO_OPTION) {
350
                                        update("INFO.filenotoverwrite");
351
                                } else {
352
                                        update("INFO.filenotsave");
353
                                }
354
                        } else {
355
                                writeSaveFile(thefile);
356
                        }
357
                } else {
358
                        update("INFO.nosave");
359
                }
360
        }
361

    
362
        /**
363
         * This method loads a Normalization pattern from a XML file and return the
364
         * pattern and the String info
365
         * 
366
         * @return pattern
367
         */
368
        public NormalizationPattern loadPatternXML() {
369

    
370
                NormalizationPattern pat = new NormalizationPattern();
371
                File thefile = null;
372

    
373
                // Show the FileChooser to select a pattern
374
                JFileChooser jfc = new JFileChooser();
375
                jfc.setCurrentDirectory(new File(getFolderPattern()));
376
                jfc.setDialogTitle(PluginServices.getText(this, "load_norm_pattern"));
377
                String[] extensions = { "xml" };
378
                jfc.addChoosableFileFilter(new GenericFileFilter(extensions,
379
                                PluginServices.getText(this, "pattern_norm_file")));
380

    
381
                int returnval = jfc.showOpenDialog((Component) PluginServices
382
                                .getMainFrame());
383

    
384
                if (returnval == JFileChooser.APPROVE_OPTION) {
385
                        thefile = jfc.getSelectedFile();
386
                } else {
387
                        update("INFO.noload");
388
                        return null;
389
                }
390

    
391
                try {
392
                        pat.loadFromXML(thefile);
393
                        update("INFO.loadsuccess");
394
                } catch (FileNotFoundException e) {
395
                        pat = null;
396
                        update("ERROR.filenotfound");
397
                        log.error("File not found", e);
398
                } catch (Exception e) {
399
                        pat = null;
400
                        update("ERROR.parsingpatternxml");
401
                        update("INFO.noformatok");
402
                        update("INFO.noload");
403
                        log.error("ERROR Parsing xml", e);
404
                }
405

    
406
                return pat;
407
        }
408

    
409
        /* GETTERS Y SETTERS */
410

    
411
        /**
412
         * Return the name of the field to normalize
413
         * 
414
         * @return field name
415
         */
416
        public String getFieldToNormalize() {
417
                return fieldToNormalize;
418
        }
419

    
420
        /**
421
         * Set the name of the field to normalize
422
         * 
423
         * @param fieldToNormalize
424
         */
425
        public void setFieldToNormalize(String fieldToNormalize) {
426

    
427
                this.fieldToNormalize = fieldToNormalize;
428

    
429
                /* Get samples to put in the GUI table */
430
                getSamplesFromTable();
431
        }
432

    
433
        /**
434
         * This method returns the names of the fields from the pattern
435
         * 
436
         * @return new fields names
437
         */
438
        public String[] getNewFieldNames() {
439

    
440
                int numFields = pattern.getElements().size();
441
                String[] res = new String[numFields];
442

    
443
                for (int i = 0; i < numFields; i++) {
444
                        res[i] = ((Element) pattern.getElements().get(i)).getFieldname();
445
                }
446
                return res;
447
        }
448

    
449
        /**
450
         * Get the first or random samples from data source (FILE)
451
         */
452
        public void getSamplesFromFile(int numNoRows) {
453

    
454
                int num = NormalizationPanel.SAMPLES;
455
                String[] res = new String[num];
456
                for (int i = 0; i < num; i++) {
457
                        try {
458
                                res[i] = (String) fileChains.get(i + numNoRows);
459
                        } catch (Exception e) {
460
                                res[i] = "";
461
                        }
462
                }
463
                this.samples = res;
464
        }
465

    
466
        /**
467
         * Return the samples Table
468
         * 
469
         * @return samples from table
470
         */
471
        public String[] getSamplesTable() {
472
                return samples;
473
        }
474

    
475
        /**
476
         * Return the samples File
477
         * 
478
         * @return samples from file
479
         */
480
        public String[] getSamplesFile() {
481
                return samples;
482
        }
483

    
484
        /**
485
         * This method sets the original table to the model
486
         * 
487
         * @param _table
488
         */
489
        public void setTable(Table _table) {
490
                tab = _table;
491
        }
492

    
493
        /**
494
         * This method says if the process will be in a new table (true) or in the
495
         * original table (false)
496
         * 
497
         * @return
498
         */
499
        public boolean isInNewTable() {
500
                return inNewTable;
501
        }
502

    
503
        /**
504
         * Assign value the flag
505
         * 
506
         * @param inNewTable
507
         */
508
        public void setInNewTable(boolean inNewTable) {
509
                this.inNewTable = inNewTable;
510
        }
511

    
512
        /**
513
         * This method returns a Element of one position
514
         * 
515
         * @param index
516
         * @return
517
         */
518
        public Element getElement(int index) {
519
                Element[] adrs = pattern.getArrayElements();
520
                return adrs[index];
521
        }
522

    
523
        /**
524
         * This method returns the fields names of the original table
525
         * 
526
         * @return list model
527
         */
528
        public DefaultListModel getAllOriginalFields() {
529

    
530
                FieldDescription[] fields = tab.getModel().getModelo()
531
                                .getFieldsDescription();
532
                int num = fields.length;
533
                String names = "";
534
                DefaultListModel dlm = new DefaultListModel();
535
                dlm.add(0, PluginServices.getText(this, "none_field"));
536
                dlm.add(1, PluginServices.getText(this, "all_fields"));
537
                for (int i = 0; i < num; i++) {
538
                        names = fields[i].getFieldName();
539
                        dlm.addElement(names);
540
                }
541
                return dlm;
542
        }
543

    
544
        /**
545
         * This method generates and returns field separators
546
         * 
547
         * @return default separators between fields
548
         */
549
        public Fieldseparator getDefaultFieldseparators() {
550

    
551
                Fieldseparator filsep = new Fieldseparator();
552
                filsep.setSemicolonsep(true);
553
                filsep.setJoinsep(false);
554
                filsep.setColonsep(false);
555
                filsep.setSpacesep(false);
556
                filsep.setTabsep(false);
557

    
558
                return filsep;
559
        }
560

    
561
        /**
562
         * Set the names of the relate Fields
563
         * 
564
         * @param list
565
         *            of the names
566
         */
567

    
568
        public void setNameRelateFields(String[] names) {
569
                relateNames = names;
570
        }
571

    
572
        /**
573
         * This method returns the fields names of the original table
574
         * 
575
         * @return fields names of the main table
576
         */
577
        public String[] getFieldNamesMainTable() {
578
                FieldDescription[] fds = tab.getModel().getModelo()
579
                                .getFieldsDescription();
580
                String[] na = new String[fds.length];
581
                for (int i = 0; i < fds.length; i++) {
582
                        na[i] = fds[i].getFieldName();
583
                }
584
                return na;
585
        }
586

    
587
        /**
588
         * This method sets the pattern
589
         * 
590
         * @pat pattern
591
         */
592
        public void setPattern(NormalizationPattern pat) {
593
                pattern = pat;
594
        }
595

    
596
        // /**
597
        // * This method returns the debug info
598
        // *
599
        // * @return info about the process
600
        // */
601
        // public String getInfo() {
602
        // return infob.toString();
603
        // }
604
        //
605
        // /**
606
        // * This method adds info about the process
607
        // *
608
        // * @param chain
609
        // * message
610
        // */
611
        // public void addInfo(String chain) {
612
        // infob.append(chain);
613
        // }
614

    
615
        /**
616
         * This method returns the File name to normalize
617
         * 
618
         * @return file name
619
         */
620
        public String getFileName() {
621
                return nameFile;
622
        }
623

    
624
        /**
625
         * set the number of first rows that not normalize
626
         * 
627
         * @param first
628
         *            select the first row
629
         */
630
        public void setFirstRows(int first) {
631
                pattern.setNofirstrows(first);
632

    
633
        }
634

    
635
        /**
636
         * Set the table
637
         * 
638
         * @param tab
639
         *            the tab to set
640
         */
641
        public void setTab(Table tab) {
642
                this.tab = tab;
643
        }
644

    
645
        /**
646
         * Set the file strings
647
         * 
648
         * @param fileChains
649
         *            the fileChains to set
650
         */
651
        public void setFileChains(List<String> fileChains) {
652
                this.fileChains = fileChains;
653
                this.isFile = true;
654
                getSamplesFromFile(getFirstRows());
655
        }
656

    
657
        /**
658
         * Get the file strings
659
         * 
660
         * @return the file strings
661
         */
662
        public List<String> getFileChains() {
663
                return fileChains;
664
        }
665

    
666
        /**
667
         * Get the file name
668
         * 
669
         * @return the nameFile
670
         */
671
        public String getNameFile() {
672
                return nameFile;
673
        }
674

    
675
        /**
676
         * Get the table
677
         * 
678
         * @return the tab
679
         */
680
        public Table getTab() {
681
                return tab;
682
        }
683

    
684
        /**
685
         * Set the file name
686
         * 
687
         * @param nameFile
688
         *            the nameFile to set
689
         */
690
        public void setNameFile(String nameFile) {
691
                this.nameFile = nameFile;
692
        }
693

    
694
        /**
695
         * get Normalize the first row
696
         * 
697
         * @return normalize first row
698
         */
699
        public int getFirstRows() {
700
                return pattern.getNofirstrows();
701

    
702
        }
703

    
704
        /**
705
         * Set the file type
706
         * 
707
         * @param file
708
         */
709
        public void isFile(boolean file) {
710
                this.isFile = file;
711
        }
712

    
713
        // /**
714
        // * This method cleans the information about the process
715
        // */
716
        // public void clearConsole() {
717
        // int con = infob.length() > 0 ? infob.length() - 1 : 0;
718
        // if (con > 0) {
719
        // infob.delete(0, con);
720
        // }
721
        // }
722

    
723
        /**
724
         * This method creates the default Normalization pattern
725
         */
726
        public void initPattern() {
727

    
728
                NormalizationPattern pat = new NormalizationPattern();
729

    
730
                pat.setPatternname("defaultPattern");
731
                pat.setNofirstrows(0);
732

    
733
                /* Create the first Address Element */
734
                Element elem = new Element();
735

    
736
                elem.setFieldname("NewField");
737
                elem.setFieldseparator(getDefaultFieldseparators());
738
                elem.setInfieldseparators(getDefaultInfieldseparators());
739
                elem.setFieldtype(getDefaultNewFieldType());
740
                elem.setFieldwidth(0);
741
                elem.setImportfield(true);
742

    
743
                List<Element> elems = new ArrayList<Element>();
744
                elems.add(elem);
745

    
746
                pat.setElements(elems);
747

    
748
                this.pattern = pat;
749
        }
750

    
751
        /* METHODS PRIVATES */
752

    
753
        /**
754
         * This method loads the new table
755
         * 
756
         * @param normTable
757
         */
758
        private void loadTable(NormalizationNewTable normTable) {
759
                String name = normTable.getOuputFile().getName();
760

    
761
                LayerFactory.getDataSourceFactory().addDataSource(
762
                                normTable.getDriver(), name);
763

    
764
                EditableAdapter editAdapterSecond = null;
765

    
766
                DataSource dtSecond;
767
                try {
768
                        dtSecond = LayerFactory.getDataSourceFactory()
769
                                        .createRandomDataSource(name,
770
                                                        DataSourceFactory.AUTOMATIC_OPENING);
771

    
772
                        editAdapterSecond = new EditableAdapter();
773
                        editAdapterSecond.setOriginalDataSource(new SelectableDataSource(
774
                                        dtSecond));
775

    
776
                        // add to doc factory
777
                        ProjectTable ptsec = ProjectFactory.createTable(name,
778
                                        editAdapterSecond);
779
                        ExtensionPoints extensionPoints = ExtensionPointsSingleton
780
                                        .getInstance();
781

    
782
                        extensionPoints.get("Documents");
783

    
784
                        ProjectDocumentFactory documentFactory = null;
785

    
786
                        documentFactory = new ProjectTableFactory();
787

    
788
                        ptsec.setProjectDocumentFactory(documentFactory);
789
                        Table secondTable = new Table();
790
                        secondTable.setModel(ptsec);
791
                        PluginServices.getMDIManager().addWindow(secondTable);
792
                        ProjectExtension pe = (ProjectExtension) PluginServices
793
                                        .getExtension(ProjectExtension.class);
794
                        Project theProject = pe.getProject();
795
                        theProject.addDocument(ptsec);
796
                        pe.getProjectFrame().refreshControls();
797
                } catch (Exception e) {
798
                        log.error("Error loading the new table", e);
799
                }
800
        }
801

    
802
        /**
803
         * This method validates the name of a new field
804
         * 
805
         * @param text
806
         * @return field name formatted
807
         */
808
        private String validateFieldName(String text) {
809

    
810
                // String temp = Normalizer.normalize(text, Normalizer.DECOMP, 0);
811
                String temp = text.replaceAll("[^\\p{ASCII}]", "");
812
                temp = temp.replaceAll("[\\s]+", "_");
813
                temp = temp.toUpperCase();
814

    
815
                return temp;
816
        }
817

    
818
        /**
819
         * Get the first or random samples from data source (TABLE)
820
         */
821
        private void getSamplesFromTable() {
822
                int num = NormalizationPanel.SAMPLES;
823
                String[] res = new String[num];
824

    
825
                ProjectTable pt = tab.getModel();
826
                IEditableSource ies = pt.getModelo();
827
                try {
828

    
829
                        long tamTab = ies.getRowCount();
830
                        if (tamTab > num)
831
                                tamTab = num;
832

    
833
                        for (int i = 0; i < (int) tamTab; i++) {
834
                                IRowEdited rowVals = ies.getRow(i);
835

    
836
                                res[i] = rowVals.getAttribute(
837
                                                tab.getSelectedFieldIndices().nextSetBit(0)).toString()
838
                                                .trim();
839
                        }
840
                } catch (Exception e) {
841
                        log.error("ERROR al obtener el recorset de la tabla", e);
842

    
843
                }
844

    
845
                this.samples = res;
846
        }
847

    
848
        /**
849
         * This method returns the dbf file
850
         * 
851
         * @return dbf file
852
         */
853
        private File getDBFFile() {
854
                File thefile = null;
855
                JFileChooser jfc = new JFileChooser();
856
                jfc.setAcceptAllFileFilterUsed(false);
857
                jfc.addChoosableFileFilter(new GenericFileFilter("dbf", PluginServices
858
                                .getText(this, "gdbms dbf drver")));
859
                jfc.setDialogTitle(PluginServices.getText(this, "new_table"));
860
                int returnval = jfc.showSaveDialog((Component) PluginServices
861
                                .getMainFrame());
862
                if (returnval == JFileChooser.APPROVE_OPTION) {
863
                        thefile = jfc.getSelectedFile();
864
                        if (!(thefile.getPath().toLowerCase().endsWith(".dbf"))) {
865
                                thefile = new File(thefile.getPath() + ".dbf");
866
                        }
867
                }
868
                return thefile;
869
        }
870

    
871
        /**
872
         * This method generates and returns in field separators
873
         * 
874
         * @return special characters within one string
875
         */
876

    
877
        private Infieldseparators getDefaultInfieldseparators() {
878

    
879
                /* create the default in-field separators */
880
                Locale loc = Locale.getDefault();
881
                DecimalFormatSymbols dfs = new DecimalFormatSymbols(loc);
882
                Infieldseparators infilsep = new Infieldseparators();
883
                infilsep.setThousandseparator(Character.toString(dfs
884
                                .getGroupingSeparator()));
885
                infilsep.setDecimalseparator(Character.toString(dfs
886
                                .getDecimalSeparator()));
887
                infilsep.setTextseparator("\"");
888

    
889
                return infilsep;
890
        }
891

    
892
        /**
893
         * This method generates and returns a new field type of type Stringvalue
894
         * 
895
         * @return field type
896
         */
897
        private Fieldtype getDefaultNewFieldType() {
898

    
899
                Fieldtype newtype = new Fieldtype();
900
                Stringvalue strval = new Stringvalue();
901
                strval.setStringvaluewidth(50);
902
                newtype.setStringvalue(strval);
903

    
904
                return newtype;
905
        }
906

    
907
        /**
908
         * This method write the save xml file
909
         * 
910
         * @param file
911
         */
912
        private void writeSaveFile(File thefile) {
913

    
914
                pattern.setPatternname(thefile.getName());
915

    
916
                try {
917
                        pattern.saveToXML(thefile);
918
                        update("INFO.savesuccess");
919

    
920
                } catch (Exception e) {
921
                        log.error("Error al parsear el patron", e);
922
                        update("ERROR.savingpat");
923
                }
924
        }
925

    
926
        /**
927
         * This method return the folder where gvSIG stores the patterns
928
         * 
929
         * @return
930
         */
931
        private String getFolderPattern() {
932
                XMLEntity xml = PluginServices.getPluginServices(this)
933
                                .getPersistentXML();
934
                String pathFolder = String.valueOf(xml
935
                                .getStringProperty("Normalization_pattern_folder"));
936
                return pathFolder;
937
        }
938

    
939
        /**
940
         * This method registers the listeners
941
         * 
942
         * @param l
943
         *            listener
944
         */
945
        public void registerListener(ChangeListener l) {
946
                this.listeners.add(l);
947
        }
948

    
949
        /**
950
         * This method remove the listeners registred
951
         * 
952
         * @param l
953
         *            listener
954
         */
955
        public void removeListener(ChangeListener l) {
956
                this.listeners.remove(l);
957
        }
958

    
959
        /**
960
         * This method removes all listeners
961
         */
962
        public void removeAllListeners() {
963
                this.listeners.clear();
964
        }
965

    
966
        /**
967
         * 
968
         * @param evt
969
         *            event
970
         */
971
        public void update(ChangeEvent evt) {
972

    
973
                for (int i = 0; i < listeners.size(); i++) {
974
                        ((ChangeListener) listeners.get(i)).stateChanged(evt);
975
                }
976
        }
977

    
978
        /**
979
         * Add message
980
         * 
981
         * @param message
982
         */
983
        public void update(String message) {
984
                ChangeEvent evt = new ChangeEvent(message);
985
                update(evt);
986
        }
987

    
988
        /**
989
         * @return the pattern
990
         */
991
        public NormalizationPattern getPattern() {
992
                return pattern;
993
        }
994

    
995
}