root / trunk / applications / appgvSIG / src / com / iver / cit / gvsig / project / documents / table / ExportStatisticsFile.java @ 26064
History | View | Annotate | Download (13.1 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 com.iver.cit.gvsig.project.documents.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.sql.Types; |
28 |
import java.util.Hashtable; |
29 |
import java.util.Iterator; |
30 |
import java.util.Map; |
31 |
|
32 |
import javax.swing.JFileChooser; |
33 |
import javax.swing.JOptionPane; |
34 |
import javax.swing.filechooser.FileFilter; |
35 |
|
36 |
import org.apache.log4j.Logger; |
37 |
|
38 |
import com.hardcode.driverManager.DriverLoadException; |
39 |
import com.hardcode.gdbms.driver.exceptions.InitializeWriterException; |
40 |
import com.hardcode.gdbms.driver.exceptions.OpenDriverException; |
41 |
import com.hardcode.gdbms.driver.exceptions.ReadDriverException; |
42 |
import com.hardcode.gdbms.engine.data.driver.FileDriver; |
43 |
import com.hardcode.gdbms.engine.values.Value; |
44 |
import com.hardcode.gdbms.engine.values.ValueFactory; |
45 |
import com.iver.andami.PluginServices; |
46 |
import com.iver.cit.gvsig.exceptions.visitors.StartWriterVisitorException; |
47 |
import com.iver.cit.gvsig.exceptions.visitors.StopWriterVisitorException; |
48 |
import com.iver.cit.gvsig.exceptions.visitors.VisitorException; |
49 |
import com.iver.cit.gvsig.fmap.core.DefaultFeature; |
50 |
import com.iver.cit.gvsig.fmap.core.IFeature; |
51 |
import com.iver.cit.gvsig.fmap.drivers.FieldDescription; |
52 |
import com.iver.cit.gvsig.fmap.drivers.ITableDefinition; |
53 |
import com.iver.cit.gvsig.fmap.drivers.TableDefinition; |
54 |
import com.iver.cit.gvsig.fmap.edition.DefaultRowEdited; |
55 |
import com.iver.cit.gvsig.fmap.edition.IWriteable; |
56 |
import com.iver.cit.gvsig.fmap.edition.IWriter; |
57 |
import com.iver.cit.gvsig.fmap.layers.LayerFactory; |
58 |
import com.iver.cit.gvsig.project.documents.table.gui.CSVSeparatorOptionsPanel; |
59 |
|
60 |
|
61 |
/**
|
62 |
* Class to create dbf and csv files at disk with the statistics group generated from a table.
|
63 |
*
|
64 |
* dbf -> Data Base File
|
65 |
* csv -> Comma Separated Value
|
66 |
*
|
67 |
* @author ?ngel Fraile Gri??n e-mail: angel.fraile@iver.es
|
68 |
*
|
69 |
*/
|
70 |
|
71 |
|
72 |
public class ExportStatisticsFile { |
73 |
|
74 |
|
75 |
private String lastPath = null; |
76 |
private Hashtable<String, MyFileFilter> dbfExtensionsSupported; // Supported extensions. |
77 |
private Hashtable<String, MyFileFilter> csvExtensionsSupported; |
78 |
|
79 |
private static Logger logger = Logger.getLogger(ExportStatisticsFile.class.getName()); |
80 |
|
81 |
|
82 |
public ExportStatisticsFile(Hashtable<String, Number> valores) { |
83 |
|
84 |
JFileChooser jfc = new JFileChooser(lastPath); |
85 |
jfc.removeChoosableFileFilter(jfc.getAcceptAllFileFilter()); |
86 |
|
87 |
// Adding required extensions (dbf, csv)
|
88 |
dbfExtensionsSupported = new Hashtable<String, MyFileFilter>(); |
89 |
csvExtensionsSupported = new Hashtable<String, MyFileFilter>(); |
90 |
dbfExtensionsSupported.put("dbf", new MyFileFilter("dbf",PluginServices.getText(this, "Ficheros_dbf"), "dbf")); |
91 |
csvExtensionsSupported.put("csv", new MyFileFilter("csv",PluginServices.getText(this, "Ficheros_csv"), "csv")); |
92 |
|
93 |
Iterator<MyFileFilter> iter = csvExtensionsSupported.values().iterator();
|
94 |
while (iter.hasNext()) {
|
95 |
jfc.addChoosableFileFilter(iter.next()); |
96 |
} |
97 |
|
98 |
iter = dbfExtensionsSupported.values().iterator(); |
99 |
while (iter.hasNext()) {
|
100 |
jfc.addChoosableFileFilter(iter.next()); |
101 |
} |
102 |
|
103 |
// Opening a JFileCooser
|
104 |
if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) { |
105 |
File endFile = jfc.getSelectedFile();
|
106 |
if (endFile.exists()){// File exists in the directory. |
107 |
int resp = JOptionPane.showConfirmDialog( |
108 |
(Component) PluginServices.getMainFrame(),
|
109 |
PluginServices.getText(this,
|
110 |
"fichero_ya_existe_seguro_desea_guardarlo")+"\n"+endFile.getAbsolutePath(), |
111 |
PluginServices.getText(this,"guardar"), JOptionPane.YES_NO_OPTION);// Informing the user |
112 |
if (resp != JOptionPane.YES_OPTION) {//cancel pressed. |
113 |
return;
|
114 |
} |
115 |
}//end if exits.
|
116 |
MyFileFilter filter = (MyFileFilter)jfc.getFileFilter();// dbf, csv
|
117 |
endFile = filter.normalizeExtension(endFile);//"name" + "." + "dbf", "name" + "." + "csv"
|
118 |
|
119 |
if(filter.getExtensionOfAFile(endFile).toLowerCase().compareTo("csv") == 0) { // csv file |
120 |
exportToCSVFile(valores,endFile); // export to csv format
|
121 |
} |
122 |
else if(filter.getExtensionOfAFile(endFile).toLowerCase().compareTo("dbf") == 0) {// dbf file |
123 |
exportToDBFFile(valores,endFile); // export to dbf format
|
124 |
} |
125 |
}//end if aprove option.
|
126 |
} |
127 |
|
128 |
/**
|
129 |
* Creating cvs format file with the statistics.
|
130 |
* Option to select the two columns separator.
|
131 |
*
|
132 |
* Example with semicolon: Name;data\n
|
133 |
* Name2;data2\n
|
134 |
*
|
135 |
* @param valores
|
136 |
* - Pairs: String name (key) + Double value (
|
137 |
* @param endFile
|
138 |
* - File to write the information
|
139 |
*/
|
140 |
|
141 |
private void exportToCSVFile(Hashtable<String, Number> valores, File endFile) { |
142 |
|
143 |
try {
|
144 |
CSVSeparatorOptionsPanel csvSeparatorOptions = new CSVSeparatorOptionsPanel();
|
145 |
PluginServices.getMDIManager().addWindow(csvSeparatorOptions); |
146 |
|
147 |
String separator = csvSeparatorOptions.getSeparator();
|
148 |
|
149 |
if(separator != null) { |
150 |
|
151 |
FileWriter fileCSV = new FileWriter(endFile); |
152 |
|
153 |
fileCSV.write(PluginServices.getText(this, "Nombre") + separator + PluginServices.getText(this, "Valor")+ "\n"); |
154 |
|
155 |
Iterator<?> it = valores.entrySet().iterator();
|
156 |
while (it.hasNext()) {// Writing value,value\n |
157 |
Map.Entry e = (Map.Entry)it.next(); |
158 |
//System.out.println(e.getKey() + " " + e.getValue());
|
159 |
fileCSV.write((String)e.getKey() + separator + Double.toString((Double)valores.get(e.getKey()).doubleValue())+ "\n"); |
160 |
} |
161 |
fileCSV.close(); |
162 |
JOptionPane.showMessageDialog(null, PluginServices.getText(this, "fichero_creado_en") + " " + endFile.getAbsolutePath(), |
163 |
PluginServices.getText(this, "fichero_creado_en_formato")+ " csv "+ |
164 |
PluginServices.getText(this, "mediante_el_separador")+ |
165 |
" \""+ separator + "\"", JOptionPane.INFORMATION_MESSAGE);// Informing the user |
166 |
} |
167 |
else
|
168 |
return;
|
169 |
|
170 |
} catch (IOException e) {// Informing the user |
171 |
logger.error("Error exportando a formato csv");
|
172 |
JOptionPane.showMessageDialog(null, PluginServices.getText(this, "Error_exportando_las_estadisticas") + " " + endFile.getAbsolutePath(), |
173 |
PluginServices.getText(this, "Error"), JOptionPane.ERROR_MESSAGE); |
174 |
} |
175 |
|
176 |
} |
177 |
|
178 |
/**
|
179 |
* Creating dbf format file with the statistics
|
180 |
* @param valores
|
181 |
* - Pairs String name (key) + Double value
|
182 |
* @param endFile
|
183 |
* - File to write the information
|
184 |
*/
|
185 |
private void exportToDBFFile(Hashtable<String, Number> valores, File endFile) { |
186 |
|
187 |
try {
|
188 |
FileDriver driver = null;
|
189 |
try {
|
190 |
driver = (FileDriver) LayerFactory.getDM().getDriver("gdbms dbf driver");
|
191 |
} catch (DriverLoadException e1) {
|
192 |
logger.error("Error Creando el driver dbf");
|
193 |
} |
194 |
|
195 |
try {
|
196 |
if (!endFile.exists()){
|
197 |
try {
|
198 |
driver.createSource(endFile.getAbsolutePath(),new String[] {"0"},new int[] {Types.DOUBLE} ); |
199 |
} catch (ReadDriverException e) {
|
200 |
logger.error("Error en createSource");
|
201 |
} |
202 |
endFile.createNewFile(); |
203 |
} |
204 |
|
205 |
try {
|
206 |
driver.open(endFile); |
207 |
} catch (OpenDriverException e) {
|
208 |
logger.error("Error abriendo el fichero de destino");
|
209 |
} |
210 |
} catch (IOException e) { |
211 |
try {
|
212 |
throw new Exception("Error creando el fichero de destino", e); |
213 |
} catch (Exception e1) { |
214 |
logger.error("Error creando el fichero de destino");
|
215 |
} |
216 |
} |
217 |
|
218 |
IWriter writer = ((IWriteable)driver).getWriter(); |
219 |
ITableDefinition orgDef = new TableDefinition();
|
220 |
try {
|
221 |
// Preparing the total rows in the new dbf file, in this case two rows : Name Value
|
222 |
FieldDescription[] fields = new FieldDescription[2]; |
223 |
fields[0] = new FieldDescription(); |
224 |
fields[0].setFieldType(Types.VARCHAR); |
225 |
fields[0].setFieldName(PluginServices.getText(this, "Nombre")); |
226 |
fields[0].setFieldLength(50); |
227 |
fields[1] = new FieldDescription(); |
228 |
fields[1].setFieldType(Types.DOUBLE); |
229 |
fields[1].setFieldName(PluginServices.getText(this, "Valor")); |
230 |
fields[1].setFieldLength(50); |
231 |
fields[1].setFieldDecimalCount(25); |
232 |
fields[1].setFieldLength(100); |
233 |
orgDef.setFieldsDesc(fields); |
234 |
writer.initialize(orgDef); |
235 |
} catch (InitializeWriterException e) {
|
236 |
logger.error("Error en la inicializaci?n del writer");
|
237 |
} |
238 |
try {
|
239 |
writer.preProcess(); |
240 |
} catch (StartWriterVisitorException e) {
|
241 |
logger.error("Error en el preProcess del writer");
|
242 |
} |
243 |
try {
|
244 |
int index = 0; |
245 |
Value[] value = new Value[2]; |
246 |
IFeature feat = null;
|
247 |
|
248 |
|
249 |
Iterator<?> it = valores.entrySet().iterator();
|
250 |
// Writing the fields, fill to fill
|
251 |
while (it.hasNext()) {
|
252 |
Map.Entry e = (Map.Entry)it.next(); |
253 |
value[0] = ValueFactory.createValue((String)e.getKey()); |
254 |
value[1] = ValueFactory.createValue((Double)valores.get(e.getKey()).doubleValue()); |
255 |
feat = new DefaultFeature(null, value,"" + index++); |
256 |
write(writer, feat, index); |
257 |
} |
258 |
} catch (Exception e) { |
259 |
logger.error("Error en el write");
|
260 |
} |
261 |
try {
|
262 |
writer.postProcess();// Operation finished
|
263 |
JOptionPane.showMessageDialog(null, PluginServices.getText(this, "fichero_creado_en") + " " + endFile.getAbsolutePath(), |
264 |
PluginServices.getText(this, "fichero_creado_en_formato")+ " dbf", JOptionPane.INFORMATION_MESSAGE);// Informing the user |
265 |
} catch (StopWriterVisitorException e) {
|
266 |
logger.error("Error en el postProcess del writer");
|
267 |
} |
268 |
} catch (Exception e) {// Informing the user |
269 |
logger.error("Error exportando a formato dbf");
|
270 |
JOptionPane.showMessageDialog(null, PluginServices.getText(this, "Error_exportando_las_estadisticas") + " " + endFile.getAbsolutePath(), |
271 |
PluginServices.getText(this, "Error"), JOptionPane.ERROR_MESSAGE); |
272 |
} |
273 |
|
274 |
} |
275 |
|
276 |
/**
|
277 |
* Writer to create dbf file
|
278 |
*
|
279 |
* @param writer
|
280 |
* @param feature
|
281 |
* - fill with the corresponding rows
|
282 |
* @param index
|
283 |
* - fill file position
|
284 |
*/
|
285 |
private void write(IWriter writer, IFeature feature, int index) { |
286 |
DefaultRowEdited edRow = new DefaultRowEdited(feature,
|
287 |
DefaultRowEdited.STATUS_ADDED, index); |
288 |
try {
|
289 |
writer.process(edRow); |
290 |
} catch (VisitorException e) {
|
291 |
logger.error("Error en la generaci?n del fichero dbf");
|
292 |
} |
293 |
} |
294 |
} |
295 |
|
296 |
/**
|
297 |
* @author ?ngel Fraile Gri??n e-mail: angel.fraile@iver.es
|
298 |
*
|
299 |
* Class to work with the file extensions.
|
300 |
*/
|
301 |
class MyFileFilter extends FileFilter { |
302 |
|
303 |
private String[] extensiones = new String[1]; |
304 |
private String description; |
305 |
private boolean dirs = true; |
306 |
private String info = null; |
307 |
|
308 |
public MyFileFilter(String[] ext, String desc) { |
309 |
extensiones = ext; |
310 |
description = desc; |
311 |
} |
312 |
|
313 |
public MyFileFilter(String[] ext, String desc, String info) { |
314 |
extensiones = ext; |
315 |
description = desc; |
316 |
this.info = info;
|
317 |
} |
318 |
|
319 |
public MyFileFilter(String ext, String desc) { |
320 |
extensiones[0] = ext;
|
321 |
description = desc; |
322 |
} |
323 |
|
324 |
public MyFileFilter(String ext, String desc, String info) { |
325 |
extensiones[0] = ext;
|
326 |
description = desc; |
327 |
this.info = info;
|
328 |
} |
329 |
|
330 |
public MyFileFilter(String ext, String desc, boolean dirs) { |
331 |
extensiones[0] = ext;
|
332 |
description = desc; |
333 |
this.dirs = dirs;
|
334 |
} |
335 |
|
336 |
public MyFileFilter(String ext, String desc, boolean dirs, String info) { |
337 |
extensiones[0] = ext;
|
338 |
description = desc; |
339 |
this.dirs = dirs;
|
340 |
this.info = info;
|
341 |
} |
342 |
|
343 |
public boolean accept(File f) { |
344 |
if (f.isDirectory()) {
|
345 |
if (dirs) {
|
346 |
return true; |
347 |
} else {
|
348 |
return false; |
349 |
} |
350 |
} |
351 |
for (int i = 0; i < extensiones.length; i++) { |
352 |
if (extensiones[i].equals("")) { |
353 |
continue;
|
354 |
} |
355 |
if (getExtensionOfAFile(f).equalsIgnoreCase(extensiones[i])) {
|
356 |
return true; |
357 |
} |
358 |
} |
359 |
return false; |
360 |
} |
361 |
|
362 |
public String getDescription() { |
363 |
return description;
|
364 |
} |
365 |
|
366 |
public String[] getExtensions() { |
367 |
return extensiones;
|
368 |
} |
369 |
|
370 |
public boolean isDirectory() { |
371 |
return dirs;
|
372 |
} |
373 |
|
374 |
public String getExtensionOfAFile(File file) { |
375 |
String name;
|
376 |
int dotPos;
|
377 |
name = file.getName(); |
378 |
dotPos = name.lastIndexOf(".");
|
379 |
if (dotPos < 1) { |
380 |
return ""; |
381 |
} |
382 |
return name.substring(dotPos + 1); |
383 |
} |
384 |
|
385 |
public File normalizeExtension(File file) { |
386 |
String ext = getExtensionOfAFile(file);
|
387 |
if (ext.equals("") || !(this.accept(file))) { |
388 |
return new File(file.getAbsolutePath() + "." + extensiones[0]); |
389 |
} |
390 |
return file;
|
391 |
} |
392 |
|
393 |
public String getInfo() { |
394 |
return this.info; |
395 |
} |
396 |
|
397 |
public void setInfo(String info) { |
398 |
this.info = info;
|
399 |
} |
400 |
} |