Statistics
| Revision:

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

History | View | Annotate | Download (24.8 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.io.FileReader;
34
import java.io.FileWriter;
35
import java.text.DecimalFormatSymbols;
36
import java.util.ArrayList;
37
import java.util.List;
38
import java.util.Locale;
39

    
40
import javax.swing.DefaultListModel;
41
import javax.swing.JFileChooser;
42
import javax.swing.JOptionPane;
43
import javax.swing.event.ChangeListener;
44

    
45
import org.apache.log4j.Logger;
46
import org.gvsig.normalization.operations.JoinedTableNormalization;
47
import org.gvsig.normalization.operations.NormAlgorithm;
48
import org.gvsig.normalization.operations.Normalization;
49
import org.gvsig.normalization.operations.NormalizationNewTable;
50
import org.gvsig.normalization.operations.StringListNormalization;
51
import org.gvsig.normalization.operations.TableNormalization;
52
import org.gvsig.normalization.patterns.Element;
53
import org.gvsig.normalization.patterns.Fieldseparator;
54
import org.gvsig.normalization.patterns.Fieldtype;
55
import org.gvsig.normalization.patterns.Infieldseparators;
56
import org.gvsig.normalization.patterns.Patternnormalization;
57
import org.gvsig.normalization.patterns.Stringvalue;
58
import org.gvsig.tools.storage.IStorage;
59
import org.gvsig.tools.storage.StorageXML;
60

    
61
import sun.text.Normalizer;
62

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

    
85
/**
86
 * Model of the Normalization panel
87
 * 
88
 * @author <a href="mailto:jsanz@prodevelop.es"> Jorge Gaspar Sanz Salinas</a>
89
 * @author <a href="mailto:vsanjaime@prodevelop.es"> Vicente Sanjaime Calvet</a>
90
 */
91

    
92
public class NormPanelModel implements INormPanelModel {
93

    
94
        /* ATTRIBUTES */
95

    
96
        private static final Logger log = PluginServices.getLogger();
97

    
98
        private static final String ERROR = "ERROR: ";
99

    
100
        private static final String INFO = "INFO: ";
101

    
102
        private static StringBuffer infob = new StringBuffer();
103

    
104
        private String fieldToNormalize;
105

    
106
        private String[] samples;
107

    
108
        private Patternnormalization pattern;
109

    
110
        private Table tab;
111

    
112
        private boolean inNewTable;
113

    
114
        private int selectedFieldInList = 0;
115

    
116
        private int contador = 1;
117

    
118
        private String[] relateNames;
119

    
120
        private ArrayList<String> fileChains;
121

    
122
        private boolean isFile;
123

    
124
        private String nameFile;
125

    
126
        /* SINGLETON DEFINITION */
127
        private volatile static INormPanelModel uniqueInstance;
128

    
129
        /**
130
         * Get the instance of panel model
131
         * 
132
         * @return panel model
133
         */
134
        public static INormPanelModel getInstance() {
135
                if (uniqueInstance == null) {
136
                        synchronized (NormPanelModel.class) {
137
                                if (uniqueInstance == null) {
138
                                        uniqueInstance = new NormPanelModel();
139
                                }
140
                        }
141
                }
142
                return uniqueInstance;
143
        }
144

    
145
        /**
146
         * Constructor
147
         */
148
        private NormPanelModel() {
149
                initPattern();
150
        }
151

    
152
        /* METHODS */
153

    
154
        /**
155
         * This method fills the GUI sample table with the samples
156
         * 
157
         * @return Object[][]
158
         */
159
        @SuppressWarnings("unchecked")
160
        public Object[][] normalizeSamples() {
161

    
162
                int numFields = pattern.getElements().size();
163
                Object[][] results = new Object[NormalizationPanel.SAMPLES][numFields];
164

    
165
                NormAlgorithm na = new NormAlgorithm(this.pattern);
166
                List<String> chains;
167
                for (int i = 0; i < NormalizationPanel.SAMPLES; i++) {
168
                        chains = na.splitChain(samples[i]);
169
                        numFields = chains.size();
170
                        for (int j = 0; j < numFields; j++) {
171
                                results[i][j] = chains.get(j);
172
                        }
173
                }
174
                return results;
175
        }
176

    
177
        /**
178
         * This method updates the model of the names FieldList
179
         * 
180
         * @return list model
181
         */
182
        public DefaultListModel updateListModel() {
183

    
184
                DefaultListModel dlmodel = new DefaultListModel();
185
                Element[] adr = this.pattern.getArrayElements();
186
                String name = "";
187
                for (int i = 0; i < adr.length; i++) {
188
                        name = adr[i].getFieldname();
189
                        dlmodel.add(i, name);
190
                }
191
                return dlmodel;
192
        }
193

    
194
        /**
195
         * Run the process of normalization
196
         * 
197
         * @return process ok
198
         */
199
        public boolean runModel(ChangeListener listener) {
200

    
201
                Normalization normAction = null;
202
                // REQUEST FILE TO OUPUT THE DBF
203
                File thefile = null;
204
                if (this.isFile || (!this.isFile && this.inNewTable)) {
205
                        thefile = getDBFFile();
206
                        if (thefile == null) {
207
                                addInfo(INFO + PluginServices.getText(null, "endnormalizing")
208
                                                + " \n");
209
                                return false;
210
                        }
211
                        if (thefile.exists()) {
212
                                addInfo(ERROR + PluginServices.getText(null, "fileexists")
213
                                                + " \n");
214
                                addInfo(INFO + PluginServices.getText(null, "endnormalizing")
215
                                                + " \n");
216
                                return false;
217
                        }
218
                }
219

    
220
                // FILE NORMALIZATION
221
                if (this.isFile) {
222
                        normAction = new StringListNormalization(pattern, fileChains,
223
                                        thefile);
224
                } else {
225
                        IEditableSource source = tab.getModel().getModelo();
226
                        int index = tab.getSelectedFieldIndices().nextSetBit(0);
227

    
228
                        if (!this.inNewTable) {
229
                                // ONE TALBE
230
                                log.debug("New fields in the original table");
231
                                normAction = new TableNormalization(source, index, pattern);
232
                        } else {
233
                                // JOINED TABLE
234
                                normAction = new JoinedTableNormalization(source, index,
235
                                                pattern, relateNames, thefile);
236
                        }
237
                }
238

    
239
                normAction.registerListener(listener);
240
                boolean pre = normAction.preProcess();
241

    
242
                if (pre) {
243
                        PluginServices.cancelableBackgroundExecution(new NormalizationTask(
244
                                        normAction, this));
245
                } else {
246
                        log.error("Error preprocessing tables");
247
                        return false;
248
                }
249

    
250
                if (normAction instanceof NormalizationNewTable) {
251
                        NormalizationNewTable normTable = (NormalizationNewTable) normAction;
252
                        this.loadTable(normTable);
253
                        addInfo(INFO + PluginServices.getText(null, "endnormalizing")
254
                                        + " \n");
255
                }
256

    
257
                return true;
258
        }
259

    
260
        /**
261
         * This method up the selected element one position in the list of Elements
262
         * 
263
         * @param pos
264
         */
265
        public void fieldUp(int pos) {
266

    
267
                int nu = pattern.getElements().size();
268

    
269
                if (pos > 0 && nu > 1) {
270
                        int newpos = pos - 1;
271
                        Element[] ad = pattern.getArrayElements();
272
                        Element ele21 = ad[pos];
273
                        Element ele12 = ad[newpos];
274

    
275
                        ad[newpos] = ele21;
276
                        ad[pos] = ele12;
277
                        List<Element> elems = new ArrayList<Element>();
278
                        for (int i = 0; i < ad.length; i++) {
279
                                elems.add(ad[i]);
280
                        }
281

    
282
                        pattern.setElements(elems);
283
                }
284
        }
285

    
286
        /**
287
         * This method down the selected element one position in the list of
288
         * Elements
289
         * 
290
         * @param pos
291
         */
292
        public void fieldDown(int pos) {
293
                int nu = pattern.getElements().size();
294

    
295
                if (pos != (nu - 1) && nu > 1) {
296
                        int newpos = pos + 1;
297
                        Element[] ad = pattern.getArrayElements();
298
                        Element ele21 = ad[pos];
299
                        Element ele12 = ad[newpos];
300

    
301
                        ad[newpos] = ele21;
302
                        ad[pos] = ele12;
303
                        List<Element> elems = new ArrayList<Element>();
304
                        for (int i = 0; i < ad.length; i++) {
305
                                elems.add(ad[i]);
306
                        }
307

    
308
                        pattern.setElements(elems);
309
                }
310
        }
311

    
312
        /**
313
         * This method adds a new element to the pattern
314
         */
315

    
316
        @SuppressWarnings("unchecked")
317
        public void addField() {
318

    
319
                contador++;
320
                int tam = pattern.getElements().size();
321
                Element elem = new Element();
322

    
323
                Fieldseparator fsep = new Fieldseparator();
324
                fsep.setSemicolonsep(true);
325
                fsep.setJoinsep(false);
326
                fsep.setColonsep(false);
327
                fsep.setSpacesep(false);
328
                fsep.setTabsep(false);
329

    
330
                String nam = "";
331
                boolean isOkName = true;
332
                do {
333
                        isOkName = true;
334
                        nam = "NewField" + contador;
335
                        for (int i = 0; i < tam; i++) {
336
                                String napat = ((Element) pattern.getElements().get(i))
337
                                                .getFieldname();
338
                                if (napat.compareToIgnoreCase(nam) == 0) {
339
                                        isOkName = false;
340
                                        break;
341
                                }
342
                        }
343
                        if (!isOkName) {
344
                                contador++;
345
                        }
346

    
347
                } while (!isOkName);
348

    
349
                // validate the new field name
350
                elem.setFieldname(validateFieldName(nam));
351
                elem.setFieldseparator(fsep);
352
                elem.setInfieldseparators(getDefaultInfieldseparators());
353
                elem.setFieldtype(getDefaultNewFieldType());
354
                elem.setFieldwidth(0);
355
                elem.setImportfield(true);
356

    
357
                pattern.getElements().add(tam, elem);
358
        }
359

    
360
        /**
361
         * This method erases a selected element to the list
362
         * 
363
         * @param pos
364
         *            position
365
         */
366
        public void deleteField(int pos) {
367
                int conta = pattern.getElements().size();
368
                if (conta > 1) {
369
                        pattern.getElements().remove(pos);
370
                }
371
        }
372

    
373
        /**
374
         * This method saves a Normalization pattern to XML file *
375
         */
376
        public void savePatternXML() {
377

    
378
                JFileChooser jfc = new JFileChooser();
379
                jfc.setDialogTitle(PluginServices.getText(this, "save_norm_pattern"));
380
                String[] extensions = { "xml" };
381
                jfc.setCurrentDirectory(new File(getFolderPattern()));
382
                jfc.addChoosableFileFilter(new GenericFileFilter(extensions,
383
                                PluginServices.getText(this, "pattern_norm_file")));
384
                int returnval = jfc.showSaveDialog((Component) PluginServices
385
                                .getMainFrame());
386

    
387
                if (returnval == JFileChooser.APPROVE_OPTION) {
388
                        File thefile = jfc.getSelectedFile();
389
                        // Check if the file has extension
390
                        if (!(thefile.getPath().toLowerCase().endsWith(".xml"))) {
391
                                thefile = new File(thefile.getPath() + ".xml");
392
                        }
393

    
394
                        if (thefile.exists()) {
395

    
396
                                int n = JOptionPane.showConfirmDialog(null, PluginServices
397
                                                .getText(null, "file_exists"), PluginServices.getText(
398
                                                null, "save_norm_pattern"), JOptionPane.YES_NO_OPTION);
399
                                if (n == JOptionPane.YES_OPTION) {
400
                                        writeSaveFile(thefile);
401
                                        log.debug("overwrite file");
402
                                } else if (n == JOptionPane.NO_OPTION) {
403
                                        log.debug("Don't save the file");
404
                                        addInfo(INFO
405
                                                        + PluginServices.getText(null, "filenotoverwrite")
406
                                                        + " \n");
407
                                } else {
408
                                        log.debug("Don't save the file");
409
                                        addInfo(INFO + PluginServices.getText(null, "filenotsave")
410
                                                        + " \n");
411
                                }
412
                        } else {
413
                                writeSaveFile(thefile);
414
                        }
415
                } else {
416
                        addInfo(INFO + PluginServices.getText(null, "nosave") + " \n");
417
                }
418
        }
419

    
420
        /**
421
         * This method loads a Normalization pattern from a XML file and return the
422
         * pattern and the String info
423
         * 
424
         * @return pattern
425
         */
426
        public Patternnormalization loadPatternXML() {
427

    
428
                Patternnormalization pat = new Patternnormalization();
429
                File thefile = null;
430
                StringBuffer infob = new StringBuffer();
431

    
432
                // Show the FileChooser to select a pattern
433
                JFileChooser jfc = new JFileChooser();
434
                jfc.setCurrentDirectory(new File(getFolderPattern()));
435
                jfc.setDialogTitle(PluginServices.getText(this, "load_norm_pattern"));
436
                String[] extensions = { "xml" };
437
                jfc.addChoosableFileFilter(new GenericFileFilter(extensions,
438
                                PluginServices.getText(this, "pattern_norm_file")));
439

    
440
                int returnval = jfc.showOpenDialog((Component) PluginServices
441
                                .getMainFrame());
442

    
443
                if (returnval == JFileChooser.APPROVE_OPTION) {
444
                        thefile = jfc.getSelectedFile();
445
                        log.debug("file to open: " + thefile);
446
                } else {
447
                        addInfo(INFO + PluginServices.getText(null, "noload") + " \n");
448
                        return null;
449
                }
450
                FileReader red;
451
                IStorage storage;
452

    
453
                try {
454
                        red = new FileReader(thefile);
455
                        storage = new StorageXML();
456
                        storage.load(red);
457
                        pat.setstate(storage);
458
                        addInfo(INFO + thefile.getName() + " "
459
                                        + PluginServices.getText(null, "loadsuccess") + " \n");
460
                } catch (FileNotFoundException e) {
461
                        pat = null;
462
                        addInfo(ERROR + PluginServices.getText(null, "filenotfound")
463
                                        + " \n");
464
                        log.error("File not found", e);
465
                } catch (Exception e) {
466
                        pat = null;
467
                        addInfo(ERROR + PluginServices.getText(null, "parsingpatternxml")
468
                                        + " \n");
469
                        log.error("ERROR Parsing xml", e);
470
                }
471

    
472
                addInfo(infob.toString());
473
                return pat;
474
        }
475

    
476
        /* GETTERS Y SETTERS */
477

    
478
        /**
479
         * Return the name of the field to normalize
480
         * 
481
         * @return field name
482
         */
483
        public String getFieldToNormalize() {
484
                return fieldToNormalize;
485
        }
486

    
487
        /**
488
         * Set the name of the field to normalize
489
         * 
490
         * @param fieldToNormalize
491
         */
492
        public void setFieldToNormalize(String fieldToNormalize) {
493

    
494
                this.fieldToNormalize = fieldToNormalize;
495

    
496
                /* Get samples to put in the GUI table */
497
                getSamplesFromTable();
498
        }
499

    
500
        /**
501
         * This method returns the names of the fields from the pattern
502
         * 
503
         * @return new fields names
504
         */
505
        public String[] getNewFieldNames() {
506

    
507
                int numFields = pattern.getElements().size();
508
                String[] res = new String[numFields];
509

    
510
                for (int i = 0; i < numFields; i++) {
511
                        res[i] = ((Element) pattern.getElements().get(i)).getFieldname();
512
                }
513
                return res;
514
        }
515

    
516
        /**
517
         * Get the first or random samples from data source (FILE)
518
         */
519
        public void getSamplesFromFile(int numNoRows) {
520

    
521
                int num = NormalizationPanel.SAMPLES;
522
                String[] res = new String[num];
523
                for (int i = 0; i < num; i++) {
524
                        try {
525
                                res[i] = (String) fileChains.get(i + numNoRows);
526
                        } catch (Exception e) {
527
                                res[i] = "";
528
                        }
529
                }
530
                this.samples = res;
531
        }
532

    
533
        /**
534
         * Return the samples Table
535
         * 
536
         * @return samples from table
537
         */
538
        public String[] getSamplesTable() {
539
                return samples;
540
        }
541

    
542
        /**
543
         * Return the samples File
544
         * 
545
         * @return samples from file
546
         */
547
        public String[] getSamplesFile() {
548
                return samples;
549
        }
550

    
551
        /**
552
         * This method sets the original table to the model
553
         * 
554
         * @param _table
555
         */
556
        public void setTable(Table _table) {
557
                tab = _table;
558
        }
559

    
560
        /**
561
         * This method says if the process will be in a new table (true) or in the
562
         * original table (false)
563
         * 
564
         * @return
565
         */
566
        public boolean isInNewTable() {
567
                return inNewTable;
568
        }
569

    
570
        /**
571
         * Assign value the flag
572
         * 
573
         * @param inNewTable
574
         */
575
        public void setInNewTable(boolean inNewTable) {
576
                this.inNewTable = inNewTable;
577
        }
578

    
579
        /**
580
         * This method returns a Element of one position
581
         * 
582
         * @param index
583
         * @return
584
         */
585
        public Element getElement(int index) {
586
                Element[] adrs = pattern.getArrayElements();
587
                return adrs[index];
588
        }
589

    
590
        /**
591
         * This method gets the position of the selected element in the List of
592
         * names
593
         * 
594
         * @return position in the list
595
         */
596
        public int getSelectedFieldInList() {
597
                return selectedFieldInList;
598
        }
599

    
600
        /**
601
         * This method set the position of the selected element in the List
602
         * 
603
         * @param selectedFieldInList
604
         */
605
        public void setSelectedFieldInList(int selectedFieldInList) {
606
                this.selectedFieldInList = selectedFieldInList;
607
        }
608

    
609
        /**
610
         * This method returns the fields names of the original table
611
         * 
612
         * @return list model
613
         */
614
        public DefaultListModel getAllOriginalFields() {
615

    
616
                FieldDescription[] fields = tab.getModel().getModelo()
617
                                .getFieldsDescription();
618
                int num = fields.length;
619
                String names = "";
620
                DefaultListModel dlm = new DefaultListModel();
621
                dlm.add(0, PluginServices.getText(this, "none_field"));
622
                dlm.add(1, PluginServices.getText(this, "all_fields"));
623
                for (int i = 0; i < num; i++) {
624
                        names = fields[i].getFieldName();
625
                        dlm.addElement(names);
626
                }
627
                return dlm;
628
        }
629

    
630
        /**
631
         * This method generates and returns field separators
632
         * 
633
         * @return default separators between fields
634
         */
635
        public Fieldseparator getDefaultFieldseparators() {
636

    
637
                Fieldseparator filsep = new Fieldseparator();
638
                filsep.setSemicolonsep(true);
639
                filsep.setJoinsep(false);
640
                filsep.setColonsep(false);
641
                filsep.setSpacesep(false);
642
                filsep.setTabsep(false);
643

    
644
                return filsep;
645
        }
646

    
647
        /**
648
         * Set the names of the relate Fields
649
         * 
650
         * @param list
651
         *            of the names
652
         */
653

    
654
        public void setNameRelateFields(String[] names) {
655
                relateNames = names;
656
        }
657

    
658
        /**
659
         * This method returns the fields names of the original table
660
         * 
661
         * @return fields names of the main table
662
         */
663
        public String[] getFieldNamesMainTable() {
664
                FieldDescription[] fds = tab.getModel().getModelo()
665
                                .getFieldsDescription();
666
                String[] na = new String[fds.length];
667
                for (int i = 0; i < fds.length; i++) {
668
                        na[i] = fds[i].getFieldName();
669
                }
670
                return na;
671
        }
672

    
673
        /**
674
         * This method sets the pattern
675
         * 
676
         * @pat pattern
677
         */
678
        public void setPattern(Patternnormalization pat) {
679
                pattern = pat;
680
        }
681

    
682
        /**
683
         * This method returns the debug info
684
         * 
685
         * @return info about the process
686
         */
687
        public String getInfo() {
688
                return infob.toString();
689
        }
690

    
691
        /**
692
         * This method adds info about the process
693
         * 
694
         * @param chain
695
         *            message
696
         */
697
        public void addInfo(String chain) {
698
                infob.append(chain);
699
        }
700

    
701
        /**
702
         * This method returns the File name to normalize
703
         * 
704
         * @return file name
705
         */
706
        public String getFileName() {
707
                return nameFile;
708
        }
709

    
710
        /**
711
         * set the number of first rows that not normalize
712
         * 
713
         * @param first
714
         *            select the first row
715
         */
716
        public void setFirstRows(int first) {
717
                pattern.setNofirstrows(first);
718

    
719
        }
720

    
721
        /**
722
         * Set the table
723
         * 
724
         * @param tab
725
         *            the tab to set
726
         */
727
        public void setTab(Table tab) {
728
                this.tab = tab;
729
        }
730

    
731
        /**
732
         * Set the file strings
733
         * 
734
         * @param fileChains
735
         *            the fileChains to set
736
         */
737
        public void setFileChains(ArrayList<String> fileChains) {
738
                this.fileChains = fileChains;
739
                this.isFile = true;
740
                getSamplesFromFile(getFirstRows());
741
        }
742

    
743
        /**
744
         * Get the file strings
745
         * 
746
         * @return the file strings
747
         */
748
        public ArrayList<String> getFileChains() {
749
                return fileChains;
750
        }
751

    
752
        /**
753
         * Get the file name
754
         * 
755
         * @return the nameFile
756
         */
757
        public String getNameFile() {
758
                return nameFile;
759
        }
760

    
761
        /**
762
         * Get the table
763
         * 
764
         * @return the tab
765
         */
766
        public Table getTab() {
767
                return tab;
768
        }
769

    
770
        /**
771
         * Set the file name
772
         * 
773
         * @param nameFile
774
         *            the nameFile to set
775
         */
776
        public void setNameFile(String nameFile) {
777
                this.nameFile = nameFile;
778
        }
779

    
780
        /**
781
         * get Normalize the first row
782
         * 
783
         * @return normalize first row
784
         */
785
        public int getFirstRows() {
786
                return pattern.getNofirstrows();
787

    
788
        }
789

    
790
        /**
791
         * Set the file type
792
         * 
793
         * @param file
794
         */
795
        public void isFile(boolean file) {
796
                this.isFile = file;
797
        }
798

    
799
        /**
800
         * This method cleans the information about the process
801
         */
802
        public void clearConsole() {
803
                int con = infob.length() > 0 ? infob.length() - 1 : 0;
804
                if (con > 0) {
805
                        infob.delete(0, con);
806
                }
807
        }
808

    
809
        /**
810
         * This method creates the default Normalization pattern
811
         */
812
        public void initPattern() {
813

    
814
                Patternnormalization pat = new Patternnormalization();
815

    
816
                pat.setPatternname("defaultPattern");
817
                pat.setPatternurl("\\");
818
                pat.setNofirstrows(0);
819

    
820
                /* Create the first Address Element */
821
                Element elem = new Element();
822

    
823
                elem.setFieldname("NewField");
824
                elem.setFieldseparator(getDefaultFieldseparators());
825
                elem.setInfieldseparators(getDefaultInfieldseparators());
826
                elem.setFieldtype(getDefaultNewFieldType());
827
                elem.setFieldwidth(0);
828
                elem.setImportfield(true);
829

    
830
                List<Element> elems = new ArrayList<Element>();
831
                elems.add(elem);
832

    
833
                pat.setElements(elems);
834

    
835
                this.pattern = pat;
836
        }
837

    
838
        /* METHODS PRIVATES */
839

    
840
        /**
841
         * This method loads the new table
842
         * 
843
         * @param normTable
844
         */
845
        private void loadTable(NormalizationNewTable normTable) {
846
                String name = normTable.getOuputFile().getName();
847

    
848
                LayerFactory.getDataSourceFactory().addDataSource(
849
                                normTable.getDriver(), name);
850

    
851
                EditableAdapter editAdapterSecond = null;
852

    
853
                DataSource dtSecond;
854
                try {
855
                        dtSecond = LayerFactory.getDataSourceFactory()
856
                                        .createRandomDataSource(name,
857
                                                        DataSourceFactory.AUTOMATIC_OPENING);
858

    
859
                        editAdapterSecond = new EditableAdapter();
860
                        editAdapterSecond.setOriginalDataSource(new SelectableDataSource(
861
                                        dtSecond));
862

    
863
                        // add to doc factory
864
                        ProjectTable ptsec = ProjectFactory.createTable(name,
865
                                        editAdapterSecond);
866
                        ExtensionPoints extensionPoints = ExtensionPointsSingleton
867
                                        .getInstance();
868

    
869
                        extensionPoints.get("Documents");
870

    
871
                        ProjectDocumentFactory documentFactory = null;
872

    
873
                        documentFactory = new ProjectTableFactory();
874

    
875
                        ptsec.setProjectDocumentFactory(documentFactory);
876
                        Table secondTable = new Table();
877
                        secondTable.setModel(ptsec);
878
                        PluginServices.getMDIManager().addWindow(secondTable);
879
                        ProjectExtension pe = (ProjectExtension) PluginServices
880
                                        .getExtension(ProjectExtension.class);
881
                        Project theProject = pe.getProject();
882
                        theProject.addDocument(ptsec);
883
                        pe.getProjectFrame().refreshControls();
884
                } catch (Exception e) {
885
                        log.error("Error loading the new table", e);
886
                }
887
        }
888

    
889
        /**
890
         * This method validates the name of a new field
891
         * 
892
         * @param text
893
         * @return field name formatted
894
         */
895
        private String validateFieldName(String text) {
896

    
897
                String temp = Normalizer.normalize(text, Normalizer.DECOMP, 0);
898
                temp = temp.replaceAll("[^\\p{ASCII}]", "");
899
                temp = temp.replaceAll("[\\s]+", "_");
900
                temp = temp.toUpperCase();
901

    
902
                return temp;
903
        }
904

    
905
        /**
906
         * Get the first or random samples from data source (TABLE)
907
         */
908
        private void getSamplesFromTable() {
909
                int num = NormalizationPanel.SAMPLES;
910
                String[] res = new String[num];
911

    
912
                ProjectTable pt = tab.getModel();
913
                IEditableSource ies = pt.getModelo();
914
                try {
915

    
916
                        long tamTab = ies.getRowCount();
917
                        if (tamTab > num)
918
                                tamTab = num;
919

    
920
                        for (int i = 0; i < (int) tamTab; i++) {
921
                                IRowEdited rowVals = ies.getRow(i);
922

    
923
                                res[i] = rowVals.getAttribute(
924
                                                tab.getSelectedFieldIndices().nextSetBit(0)).toString()
925
                                                .trim();
926
                        }
927
                } catch (ReadDriverException e) {
928
                        log.error("ERROR al obtener el recorset de la tabla");
929
                        e.printStackTrace();
930
                }
931

    
932
                this.samples = res;
933
        }
934

    
935
        /**
936
         * This method returns the dbf file
937
         * 
938
         * @return dbf file
939
         */
940
        private File getDBFFile() {
941
                File thefile = null;
942
                JFileChooser jfc = new JFileChooser();
943
                jfc.setAcceptAllFileFilterUsed(false);
944
                jfc.addChoosableFileFilter(new GenericFileFilter("dbf", PluginServices
945
                                .getText(this, "gdbms dbf drver")));
946
                jfc.setDialogTitle(PluginServices.getText(this, "new_table"));
947
                int returnval = jfc.showSaveDialog((Component) PluginServices
948
                                .getMainFrame());
949
                if (returnval == JFileChooser.APPROVE_OPTION) {
950
                        thefile = jfc.getSelectedFile();
951
                        if (!(thefile.getPath().toLowerCase().endsWith(".dbf"))) {
952
                                thefile = new File(thefile.getPath() + ".dbf");
953
                        }
954
                }
955
                return thefile;
956
        }
957

    
958
        /**
959
         * This method generates and returns in field separators
960
         * 
961
         * @return special characters within one string
962
         */
963

    
964
        private Infieldseparators getDefaultInfieldseparators() {
965

    
966
                /* create the default in-field separators */
967
                Locale loc = Locale.getDefault();
968
                DecimalFormatSymbols dfs = new DecimalFormatSymbols(loc);
969
                Infieldseparators infilsep = new Infieldseparators();
970
                infilsep.setThousandseparator(Character.toString(dfs
971
                                .getGroupingSeparator()));
972
                infilsep.setDecimalseparator(Character.toString(dfs
973
                                .getDecimalSeparator()));
974
                infilsep.setTextseparator("\"");
975

    
976
                return infilsep;
977
        }
978

    
979
        /**
980
         * This method generates and returns a new field type of type Stringvalue
981
         * 
982
         * @return field type
983
         */
984
        private Fieldtype getDefaultNewFieldType() {
985

    
986
                Fieldtype newtype = new Fieldtype();
987
                Stringvalue strval = new Stringvalue();
988
                strval.setStringvaluewidth(50);
989
                newtype.setStringvalue(strval);
990

    
991
                return newtype;
992
        }
993

    
994
        /**
995
         * This method write the save xml file
996
         * 
997
         * @param file
998
         */
999
        private void writeSaveFile(File thefile) {
1000

    
1001
                StringBuffer infob = new StringBuffer();
1002

    
1003
                /* insert the name and the path */
1004
                pattern.setPatternname(thefile.getName());
1005
                pattern.setPatternurl(thefile.getAbsolutePath());
1006

    
1007
                FileWriter writer;
1008
                IStorage storage;
1009
                try {
1010
                        storage = new StorageXML();
1011
                        pattern.getstate(storage);
1012

    
1013
                        writer = new FileWriter(thefile);
1014
                        // Parser the pattern
1015
                        storage.dump(writer);
1016
                        infob.append(INFO + thefile.getName() + " "
1017
                                        + PluginServices.getText(null, "savesuccess") + " \n");
1018
                        writer.close();
1019
                } catch (Exception e) {
1020
                        log.error("Error al parsear el patron", e);
1021
                        infob.append(ERROR + PluginServices.getText(null, "savingpat")
1022
                                        + " \n");
1023
                }
1024

    
1025
                addInfo(infob.toString());
1026
        }
1027

    
1028
        /**
1029
         * This method return the folder where gvSIG stores the patterns
1030
         * 
1031
         * @return
1032
         */
1033
        private String getFolderPattern() {
1034
                XMLEntity xml = PluginServices.getPluginServices(this)
1035
                                .getPersistentXML();
1036
                String pathFolder = String.valueOf(xml
1037
                                .getStringProperty("Normalization_pattern_folder"));
1038
                return pathFolder;
1039
        }
1040

    
1041
}