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 @ 45359

History | View | Annotate | Download (7.41 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 java.util.Locale;
15
import org.apache.commons.lang3.ArrayUtils;
16
import org.gvsig.fmap.dal.DataTypes;
17
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
18
import org.gvsig.fmap.dal.feature.FeatureType;
19
import org.gvsig.fmap.dal.feature.exception.PerformEditingException;
20
import org.gvsig.fmap.dal.feature.spi.FeatureProvider;
21
import org.gvsig.fmap.geom.Geometry;
22
import org.gvsig.fmap.geom.primitive.Envelope;
23
import org.gvsig.tools.ToolsLocator;
24
import org.gvsig.tools.dataTypes.CoercionException;
25
import org.gvsig.tools.dataTypes.DataTypeUtils;
26
import org.gvsig.tools.dataTypes.Coercion;
27
import org.slf4j.Logger;
28
import org.slf4j.LoggerFactory;
29
import org.supercsv.io.CsvListWriter;
30
import org.supercsv.prefs.CsvPreference;
31
import org.gvsig.tools.dataTypes.CoercionContext;
32

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

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

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

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

    
70
    if (this.ftype != null) {
71
      this.descriptors = this.ftype.getAttributeDescriptors();
72
      if (ftype.getDefaultGeometryAttributeName() != null) {
73
        this.calculate_envelope = true;
74
      }
75
    }
76
    this.convert = ToolsLocator.getDataTypesManager().getCoercion(DataTypes.STRING);
77
//    this.converContext = DataTypeUtils.coerceContextLocale(CSVStoreParameters.getLocale(this.storeParameters));
78
    this.errorcounts = 0;
79
    this.charset = CSVStoreParameters.getCharset(storeParameters);
80
    this.includeMetadataInHeader = CSVStoreParameters.getIncludeMetadataInHeader(storeParameters);
81
    this.locale = CSVStoreParameters.getLocale(storeParameters);
82
    }
83

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

    
104
    } catch (IOException e) {
105
      LOGGER.warn("Can't open file for write (" + file.getAbsolutePath() + ").", e);
106
      throw new RuntimeException(e);
107
    }
108
  }
109

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

    
125
    String[] header = new String[n];
126
    this.values = new String[n];
127
    n = 0;
128
      for (FeatureAttributeDescriptor descriptor : descriptors) {
129
          if (!descriptor.isComputed()) {
130
              if (includeMetadataInHeader) {
131
                header[n++] = (String) descriptor.get("all");
132
              } else {
133
                header[n++] = (String) descriptor.getName();
134
              }
135
          }
136
      }
137
    try {
138
      listWriter.writeHeader(header);
139
    } catch (Exception e) {
140
      LOGGER.warn("Can't write header '" + ArrayUtils.toString(header) + "' file for write (" + file.getAbsolutePath() + ").", e);
141
      throw new RuntimeException(e);
142
    }
143
  }
144

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

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

    
199
  }
200

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

    
223
  public Envelope getEnvelope() {
224
    return this.envelope;
225
  }
226
}