Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.fmap.dal / org.gvsig.fmap.dal.file / org.gvsig.fmap.dal.file.csv / src / main / java / org / gvsig / fmap / dal / store / csv / CSVFeatureWriter.java @ 44669

History | View | Annotate | Download (7.14 KB)

1
/*
2
 * To change this license header, choose License Headers in Project Properties.
3
 * To change this template file, choose Tools | Templates
4
 * and open the template in the editor.
5
 */
6
package org.gvsig.fmap.dal.store.csv;
7

    
8
import java.io.File;
9
import java.io.FileOutputStream;
10
import java.io.FileWriter;
11
import java.io.IOException;
12
import java.io.OutputStreamWriter;
13
import java.io.Writer;
14
import org.apache.commons.lang3.ArrayUtils;
15
import org.gvsig.fmap.dal.DataTypes;
16
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
17
import org.gvsig.fmap.dal.feature.FeatureType;
18
import org.gvsig.fmap.dal.feature.exception.PerformEditingException;
19
import org.gvsig.fmap.dal.feature.spi.FeatureProvider;
20
import org.gvsig.fmap.geom.Geometry;
21
import org.gvsig.fmap.geom.primitive.Envelope;
22
import org.gvsig.tools.ToolsLocator;
23
import org.gvsig.tools.dataTypes.CoercionException;
24
import org.gvsig.tools.dataTypes.DataTypeUtils;
25
import org.gvsig.tools.dataTypes.Coercion;
26
import org.slf4j.Logger;
27
import org.slf4j.LoggerFactory;
28
import org.supercsv.io.CsvListWriter;
29
import org.supercsv.prefs.CsvPreference;
30
import org.gvsig.tools.dataTypes.CoercionContext;
31

    
32
/**
33
 *
34
 * @author osc
35
 */
36
@SuppressWarnings("UseSpecificCatch")
37
public class CSVFeatureWriter {
38

    
39
  private static final Logger LOGGER = LoggerFactory.getLogger(CSVFeatureWriter.class);
40

    
41
  private Envelope envelope = null;
42
  private boolean calculate_envelope = false;
43
  private CsvListWriter listWriter = null;
44
  private CsvPreference csvpreferences = null;
45
  private Writer writer = null;
46
  private FeatureType ftype;
47
  private File file;
48
  private String[] values;
49
  private FeatureAttributeDescriptor[] descriptors;
50
  private Coercion convert = null;
51
  private CoercionContext converContext = null;
52
  private int errorcounts = 0;
53
  private Throwable lasterror = null;
54
  private CSVStoreParameters storeParameters;
55
  private String charset = null;
56

    
57
  public void initialize(CSVStoreParameters storeParameters, File file, FeatureType ftype, CsvPreference csvpreferences) {
58
    this.file = file;
59
    this.ftype = ftype;
60
    this.storeParameters = storeParameters;
61
    if (csvpreferences == null) {
62
      this.csvpreferences = CSVStoreParameters.getPredefinedCSVPreferences(storeParameters);
63
    } else {
64
      this.csvpreferences = csvpreferences;
65
    }
66

    
67
    if (this.ftype != null) {
68
      this.descriptors = this.ftype.getAttributeDescriptors();
69
      if (ftype.getDefaultGeometryAttributeName() != null) {
70
        this.calculate_envelope = true;
71
      }
72
    }
73
    this.convert = ToolsLocator.getDataTypesManager().getCoercion(DataTypes.STRING);
74
    this.converContext = DataTypeUtils.coerceContextLocale(CSVStoreParameters.getLocale(this.storeParameters));
75
    this.errorcounts = 0;
76
    this.charset = CSVStoreParameters.getCharset(storeParameters);
77
  }
78

    
79
  public void beginAppend() {
80
    try {
81
      FileOutputStream fos = new FileOutputStream(file, true);
82
      if (this.charset != null) {
83
        this.writer = new OutputStreamWriter(fos, this.charset);
84
      } else {
85
        this.writer = new OutputStreamWriter(fos);
86
      }
87
      this.listWriter = new CsvListWriter(this.writer, this.csvpreferences);
88
      if (ftype != null) {
89
        this.descriptors = ftype.getAttributeDescriptors();
90
        int n = 0;
91
        for (FeatureAttributeDescriptor descriptor : descriptors) {
92
          if (descriptor.getEvaluator() == null) {
93
            n++;
94
          }
95
        }
96
        this.values = new String[n];
97
      }
98

    
99
    } catch (IOException e) {
100
      LOGGER.warn("Can't open file for write (" + file.getAbsolutePath() + ").", e);
101
      throw new RuntimeException(e);
102
    }
103
  }
104

    
105
  public void begin() {
106
    try {
107
      this.writer = new FileWriter(file);
108
    } catch (IOException e) {
109
      LOGGER.warn("Can't open file for write (" + file.getAbsolutePath() + ").", e);
110
      throw new RuntimeException(e);
111
    }
112
    this.listWriter = new CsvListWriter(this.writer, this.csvpreferences);
113
    int n = 0;
114
    for (FeatureAttributeDescriptor descriptor : descriptors) {
115
      if (descriptor.getEvaluator() == null) {
116
        n++;
117
      }
118
    }
119

    
120
    String[] header = new String[n];
121
    this.values = new String[n];
122
    n = 0;
123
    for (int i = 0; i < descriptors.length; i++) {
124
      FeatureAttributeDescriptor descriptor = descriptors[i];
125
      if (descriptor.getEvaluator() == null) {
126
        String name = descriptor.getName();
127
        String typeName = descriptor.getDataTypeName();
128
        if (descriptor.getDataType().getType() == DataTypes.STRING) {
129
          header[n++] = name + "__" + typeName + "__" + descriptor.getSize();
130
        } else {
131
          header[n++] = name + "__" + typeName;
132
        }
133
      }
134
    }
135
    try {
136
      listWriter.writeHeader(header);
137
    } catch (Exception e) {
138
      LOGGER.warn("Can't write header '" + ArrayUtils.toString(header) + "' file for write (" + file.getAbsolutePath() + ").", e);
139
      throw new RuntimeException(e);
140
    }
141
  }
142

    
143
  public void add(FeatureProvider feature) {
144
    if (this.calculate_envelope) {
145
      Geometry geom = feature.getDefaultGeometry();
146
      if (geom != null) {
147
        if (envelope == null) {
148
          try {
149
            envelope = (Envelope) geom.getEnvelope().clone();
150
          } catch (CloneNotSupportedException e) {
151
            LOGGER.warn("Este error no deberia pasar, siempre se puede hacer un clone de un envelope.", e);
152
          }
153
        } else {
154
          envelope.add(geom.getEnvelope());
155
        }
156
      }
157
    }
158

    
159
    for (int i = 0; i < descriptors.length; i++) {
160
      FeatureAttributeDescriptor descriptor = descriptors[i];
161
      if (descriptor.getEvaluator() == null) {
162
        Object value = feature.get(i);
163
        try {
164
          values[i] = (String) this.convert.coerce(value, this.converContext);
165
        } catch (CoercionException e) {
166
          try {
167
            values[i] = value.toString();
168
          } catch (Exception ex) {
169
            values[i] = "";
170
          }
171
          if (errorcounts++ <= 10) {
172
            this.lasterror = e;
173
            LOGGER.warn("Can't convert value of field " + i + " to string in CVS file '" + this.file.getAbsolutePath() + "'.", e);
174
            if (errorcounts == 10) {
175
              LOGGER.warn("Too many error writing CVS file '" + this.file.getAbsolutePath() + "', don't output more.");
176
            }
177
          }
178
        }
179
      }
180
    }
181
    try {
182
      this.listWriter.writeHeader(values);
183
    } catch (IOException e) {
184
      if (errorcounts++ <= 10) {
185
        this.lasterror = e;
186
        LOGGER.warn("Can't write values to CVS file '" + this.file.getAbsolutePath() + "'.", e);
187
        if (errorcounts == 10) {
188
          LOGGER.warn("Too many error writing CVS file '" + this.file.getAbsolutePath() + "', don't output more.");
189
        }
190
      }
191
    }
192

    
193
  }
194

    
195
  public void end() throws PerformEditingException {
196
    if (this.errorcounts > 0) {
197
      throw new PerformEditingException(this.file.getAbsolutePath(), lasterror);
198
    }
199
    if (listWriter != null) {
200
      try {
201
        listWriter.close();
202
      } catch (Exception ex) {
203
        // Ignore error
204
      }
205
      listWriter = null;
206
    }
207
    if (writer != null) {
208
      try {
209
        writer.close();
210
      } catch (Exception ex) {
211
        // Ignore error
212
      }
213
      writer = null;
214
    }
215
  }
216

    
217
  public Envelope getEnvelope() {
218
    return this.envelope;
219
  }
220
}