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

History | View | Annotate | Download (7.29 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
  private boolean includeMetadataInHeader;
57

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

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

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

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

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

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

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

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

    
196
  }
197

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

    
220
  public Envelope getEnvelope() {
221
    return this.envelope;
222
  }
223
}