Statistics
| Revision:

root / branches / v2_0_0_prep / applications / appgvSIG / src / org / gvsig / project / document / table / ExportStatisticsFile.java @ 27723

History | View | Annotate | Download (11 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
*
3
* Copyright (C) 2005 IVER T.I. and Generalitat Valenciana.
4
*
5
* This program is free software; you can redistribute it and/or
6
* modify it under the terms of the GNU General Public License
7
* as published by the Free Software Foundation; either version 2
8
* of the License, or (at your option) any later version.
9
*
10
* This program is distributed in the hope that it will be useful,
11
* but WITHOUT ANY WARRANTY; without even the implied warranty of
12
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
* GNU General Public License for more details.
14
*
15
* You should have received a copy of the GNU General Public License
16
* along with this program; if not, write to the Free Software
17
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
*/
19

    
20

    
21
package org.gvsig.project.document.table;
22

    
23
import java.awt.Component;
24
import java.io.File;
25
import java.io.FileWriter;
26
import java.io.IOException;
27
import java.util.Hashtable;
28
import java.util.Iterator;
29
import java.util.List;
30

    
31
import javax.swing.JFileChooser;
32
import javax.swing.JOptionPane;
33
import javax.swing.filechooser.FileFilter;
34

    
35
import org.apache.log4j.Logger;
36
import org.gvsig.fmap.dal.DALLocator;
37
import org.gvsig.fmap.dal.DataManager;
38
import org.gvsig.fmap.dal.DataTypes;
39
import org.gvsig.fmap.dal.exception.DataException;
40
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
41
import org.gvsig.fmap.dal.feature.EditableFeature;
42
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
43
import org.gvsig.fmap.dal.feature.EditableFeatureType;
44
import org.gvsig.fmap.dal.feature.FeatureStore;
45
import org.gvsig.fmap.dal.feature.FeatureType;
46
import org.gvsig.fmap.dal.feature.NewFeatureStoreParameters;
47
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemServerExplorer;
48
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemServerExplorerParameters;
49
import org.gvsig.project.document.table.gui.CSVSeparatorOptionsPanel;
50
import org.gvsig.project.document.table.gui.Statistics.MyObjectStatistics;
51

    
52
import com.iver.andami.PluginServices;
53
import com.iver.andami.messages.NotificationManager;
54

    
55
/**
56
 * Class to create dbf and csv files at disk with the statistics group generated from a table.
57
 *
58
 * dbf -> Data Base File
59
 * csv -> Comma Separated Value
60
 *
61
 * @author ?ngel Fraile Gri??n  e-mail: angel.fraile@iver.es
62
 *
63
 */
64

    
65

    
66
public class ExportStatisticsFile {
67

    
68

    
69
        private String lastPath = null;
70
        private Hashtable<String, MyFileFilter> dbfExtensionsSupported; // Supported extensions.
71
        private Hashtable<String, MyFileFilter> csvExtensionsSupported;
72

    
73
        private static Logger logger = Logger.getLogger(ExportStatisticsFile.class.getName());
74

    
75

    
76
        public ExportStatisticsFile(List<MyObjectStatistics> valores) {
77

    
78
                JFileChooser jfc = new JFileChooser(lastPath);
79
                        jfc.removeChoosableFileFilter(jfc.getAcceptAllFileFilter());
80

    
81
                        // Adding required extensions (dbf, csv)
82
                        dbfExtensionsSupported = new Hashtable<String, MyFileFilter>();
83
                        csvExtensionsSupported = new Hashtable<String, MyFileFilter>();
84
                        dbfExtensionsSupported.put("dbf", new MyFileFilter("dbf",PluginServices.getText(this, "Ficheros_dbf"), "dbf"));
85
                        csvExtensionsSupported.put("csv", new MyFileFilter("csv",PluginServices.getText(this, "Ficheros_csv"), "csv"));
86

    
87
                        Iterator<MyFileFilter> iter = csvExtensionsSupported.values().iterator();
88
                        while (iter.hasNext()) {
89
                                jfc.addChoosableFileFilter(iter.next());
90
                        }
91

    
92
                        iter = dbfExtensionsSupported.values().iterator();
93
                        while (iter.hasNext()) {
94
                                jfc.addChoosableFileFilter(iter.next());
95
                        }
96

    
97
                        // Opening a JFileCooser
98
                        if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
99
                                        File endFile = jfc.getSelectedFile();
100
                                                if (endFile.exists()){// File exists in the directory.
101
                                                        int resp = JOptionPane.showConfirmDialog(
102
                                                                        (Component) PluginServices.getMainFrame(),
103
                                                                        PluginServices.getText(this,
104
                                                                                        "fichero_ya_existe_seguro_desea_guardarlo")+"\n"+endFile.getAbsolutePath(),
105
                                                                        PluginServices.getText(this,"guardar"), JOptionPane.YES_NO_OPTION);// Informing the user
106
                                                        if (resp != JOptionPane.YES_OPTION) {//cancel pressed.
107
                                                                return;
108
                                                        }
109
                                                }//end if exits.
110
                                                MyFileFilter filter = (MyFileFilter)jfc.getFileFilter();// dbf, csv
111
                                                endFile = filter.normalizeExtension(endFile);//"name" + "." + "dbf", "name" + "." + "csv"
112

    
113
                                                if(filter.getExtensionOfAFile(endFile).toLowerCase().compareTo("csv") == 0) { // csv file
114
                                                        exportToCSVFile(valores,endFile); // export to csv format
115
                                                }
116
                                                else if(filter.getExtensionOfAFile(endFile).toLowerCase().compareTo("dbf") == 0) {// dbf file
117
                                                        try {
118
                                                                exportToDBFFile(valores,endFile);
119
                                                        } catch (Exception e) {
120
                                                                NotificationManager.addError(e);
121
                                                        } // export to dbf format
122
                                                }
123
                        }//end if aprove option.
124
        }
125

    
126
        /**
127
         * Creating  cvs format file with the statistics.
128
         * Option to select the two columns separator.
129
         *
130
         * Example with semicolon: Name;data\n
131
         *                                            Name2;data2\n
132
         *
133
         * @param valores
134
         *                         - Pairs: String name (key) + Double value (
135
         * @param endFile
136
         *                         - File to write the information
137
         */
138

    
139
        private void exportToCSVFile(List<MyObjectStatistics> valores, File endFile) {
140

    
141
                try {
142
                        CSVSeparatorOptionsPanel csvSeparatorOptions = new CSVSeparatorOptionsPanel();
143
                        PluginServices.getMDIManager().addWindow(csvSeparatorOptions);
144

    
145
                        String separator = csvSeparatorOptions.getSeparator();
146

    
147
                        if(separator != null) {
148

    
149
                                FileWriter fileCSV = new FileWriter(endFile);
150

    
151
                                fileCSV.write(PluginServices.getText(this, "Nombre") + separator + PluginServices.getText(this, "Valor")+ "\n");
152

    
153
                                Iterator<MyObjectStatistics> iterador = valores.listIterator();
154

    
155
                                while (iterador.hasNext()) {// Writing value,value\n
156
                                         MyObjectStatistics data= iterador.next();
157
                                         fileCSV.write(data.getKey() + separator + (data.getValue())+ "\n");
158
                                }
159
                                fileCSV.close();
160
                                JOptionPane.showMessageDialog(null, PluginServices.getText(this, "fichero_creado_en") + " " + endFile.getAbsolutePath(),
161
                                                PluginServices.getText(this, "fichero_creado_en_formato")+ " csv "+
162
                                                PluginServices.getText(this, "mediante_el_separador")+
163
                                                " \""+ separator + "\"", JOptionPane.INFORMATION_MESSAGE);// Informing the user
164
                        } else {
165
                                return;
166
                        }
167

    
168
                } catch (IOException e) {// Informing the user
169
                        logger.error("Error exportando a formato csv");
170
                        JOptionPane.showMessageDialog(null, PluginServices.getText(this, "Error_exportando_las_estadisticas") + " " + endFile.getAbsolutePath(),
171
                                        PluginServices.getText(this, "Error"), JOptionPane.ERROR_MESSAGE);
172
                }
173

    
174
        }
175

    
176
        public void exportToDBFFile(List<MyObjectStatistics> valores, File endFile)
177
                        throws DataException, ValidateDataParametersException {
178
                DataManager datamanager=DALLocator.getDataManager();
179
                FilesystemServerExplorerParameters explorerParams=(FilesystemServerExplorerParameters) datamanager.createServerExplorerParameters(FilesystemServerExplorer.NAME);
180
                explorerParams.setRoot(endFile.getParent());
181
                FilesystemServerExplorer explorer=(FilesystemServerExplorer) datamanager.createServerExplorer(explorerParams);
182
                NewFeatureStoreParameters newParams = (NewFeatureStoreParameters) explorer.getAddParameters(endFile);
183
                try {
184
                        EditableFeatureType type = newParams.getDefaultFeatureType()
185
                                        .getEditable();
186
                        EditableFeatureAttributeDescriptor efad1 = type.add(PluginServices.getText(this, "Nombre"), DataTypes.STRING, 50);
187
                        EditableFeatureAttributeDescriptor efad2 = type.add(PluginServices.getText(this, "Valor"), DataTypes.DOUBLE, 100);
188
                        efad2.setPrecision(25);
189
                        newParams.setDefaultFeatureType(type);
190
                        explorer.add(newParams, true);
191
                        DataManager manager = DALLocator.getDataManager();
192
                        FeatureStore target = (FeatureStore) manager
193
                        .createStore(newParams);
194
                        FeatureType targetType = target.getDefaultFeatureType();
195
                        target.edit(FeatureStore.MODE_APPEND);
196
                        Iterator<MyObjectStatistics> iterador = valores.listIterator();
197
                        while (iterador.hasNext()) {
198
                                MyObjectStatistics data= iterador.next();
199
                                EditableFeature ef=target.createNewFeature().getEditable();//new DefaultFeature(target).getEditable();//EditableFeature();
200
                                ef.set(PluginServices.getText(this, "Nombre"), data.getKey());
201
                                ef.set(PluginServices.getText(this, "Valor"), data.getValue());
202
                                target.insert(ef);
203
                        }
204
                        target.finishEditing();
205
                        target.dispose();
206
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), PluginServices.getText(this, "fichero_creado_en") + " " + endFile.getAbsolutePath(),
207
                                        PluginServices.getText(this, "fichero_creado_en_formato")+ " dbf", JOptionPane.INFORMATION_MESSAGE);// Informing the user
208
                } catch (Exception e) {
209
                        e.printStackTrace();
210
                }
211
        }
212
}
213

    
214
/**
215
 * @author ?ngel Fraile Gri??n  e-mail: angel.fraile@iver.es
216
 *
217
 * Class to work with the file extensions.
218
 */
219
class MyFileFilter extends FileFilter {
220

    
221
        private String[] extensiones = new String[1];
222
        private String description;
223
        private boolean dirs = true;
224
        private String info = null;
225

    
226
        public MyFileFilter(String[] ext, String desc) {
227
                extensiones = ext;
228
                description = desc;
229
        }
230

    
231
        public MyFileFilter(String[] ext, String desc, String info) {
232
                extensiones = ext;
233
                description = desc;
234
                this.info = info;
235
        }
236

    
237
        public MyFileFilter(String ext, String desc) {
238
                extensiones[0] = ext;
239
                description = desc;
240
        }
241

    
242
        public MyFileFilter(String ext, String desc, String info) {
243
                extensiones[0] = ext;
244
                description = desc;
245
                this.info = info;
246
        }
247

    
248
        public MyFileFilter(String ext, String desc, boolean dirs) {
249
                extensiones[0] = ext;
250
                description = desc;
251
                this.dirs = dirs;
252
        }
253

    
254
        public MyFileFilter(String ext, String desc, boolean dirs, String info) {
255
                extensiones[0] = ext;
256
                description = desc;
257
                this.dirs = dirs;
258
                this.info = info;
259
        }
260

    
261
        public boolean accept(File f) {
262
                if (f.isDirectory()) {
263
                        if (dirs) {
264
                                return true;
265
                        } else {
266
                                return false;
267
                        }
268
                }
269
                for (int i = 0; i < extensiones.length; i++) {
270
                        if (extensiones[i].equals("")) {
271
                                continue;
272
                        }
273
                        if (getExtensionOfAFile(f).equalsIgnoreCase(extensiones[i])) {
274
                                return true;
275
                        }
276
                }
277
                return false;
278
        }
279

    
280
        public String getDescription() {
281
                return description;
282
        }
283

    
284
        public String[] getExtensions() {
285
                return extensiones;
286
        }
287

    
288
        public boolean isDirectory() {
289
                return dirs;
290
        }
291

    
292
        public String getExtensionOfAFile(File file) {
293
                String name;
294
                int dotPos;
295
                name = file.getName();
296
                dotPos = name.lastIndexOf(".");
297
                if (dotPos < 1) {
298
                        return "";
299
                }
300
                return name.substring(dotPos + 1);
301
        }
302

    
303
        public File normalizeExtension(File file) {
304
                String ext = getExtensionOfAFile(file);
305
                if (ext.equals("") || !(this.accept(file))) {
306
                        return new File(file.getAbsolutePath() + "." + extensiones[0]);
307
                }
308
                return file;
309
        }
310

    
311
        public String getInfo() {
312
                return this.info;
313
        }
314

    
315
        public void setInfo(String info) {
316
                this.info = info;
317
        }
318
}