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 / CSVStoreProvider.java @ 42220

History | View | Annotate | Download (46 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA 02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.fmap.dal.store.csv;
25

    
26
import java.io.File;
27
import java.io.FileReader;
28
import java.io.FileWriter;
29
import java.io.IOException;
30
import java.net.URL;
31
import java.text.SimpleDateFormat;
32
import java.util.ArrayList;
33
import java.util.HashMap;
34
import java.util.Iterator;
35
import java.util.List;
36
import java.util.Locale;
37

    
38
import org.apache.commons.io.FilenameUtils;
39
import org.apache.commons.lang3.StringUtils;
40
import org.cresques.cts.IProjection;
41
import org.gvsig.fmap.dal.DALLocator;
42
import org.gvsig.fmap.dal.DataManager;
43
import org.gvsig.fmap.dal.DataServerExplorer;
44
import org.gvsig.fmap.dal.DataStore;
45
import org.gvsig.fmap.dal.DataStoreNotification;
46
import org.gvsig.fmap.dal.DataTypes;
47
import org.gvsig.fmap.dal.FileHelper;
48
import org.gvsig.fmap.dal.exception.DataException;
49
import org.gvsig.fmap.dal.exception.InitializeException;
50
import org.gvsig.fmap.dal.exception.OpenException;
51
import org.gvsig.fmap.dal.exception.ReadException;
52
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
53
import org.gvsig.fmap.dal.feature.EditableFeature;
54
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
55
import org.gvsig.fmap.dal.feature.EditableFeatureType;
56
import org.gvsig.fmap.dal.feature.Feature;
57
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
58
import org.gvsig.fmap.dal.feature.FeatureAttributeEmulator;
59
import org.gvsig.fmap.dal.feature.FeatureSet;
60
import org.gvsig.fmap.dal.feature.FeatureStore;
61
import org.gvsig.fmap.dal.feature.FeatureType;
62
import org.gvsig.fmap.dal.feature.exception.PerformEditingException;
63
import org.gvsig.fmap.dal.feature.spi.FeatureProvider;
64
import org.gvsig.fmap.dal.feature.spi.FeatureStoreProviderServices;
65
import org.gvsig.fmap.dal.feature.spi.memory.AbstractMemoryStoreProvider;
66
import org.gvsig.fmap.dal.resource.ResourceAction;
67
import org.gvsig.fmap.dal.resource.file.FileResource;
68
import org.gvsig.fmap.dal.resource.spi.ResourceConsumer;
69
import org.gvsig.fmap.dal.resource.spi.ResourceProvider;
70
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemServerExplorer;
71
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemServerExplorerParameters;
72
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
73
import org.gvsig.fmap.dal.store.csv.simplereaders.CSVReader;
74
import org.gvsig.fmap.dal.store.csv.simplereaders.FixedLenReader;
75
import org.gvsig.fmap.dal.store.csv.simplereaders.SimpleReader;
76
import org.gvsig.fmap.geom.Geometry;
77
import org.gvsig.fmap.geom.GeometryLocator;
78
import org.gvsig.fmap.geom.GeometryManager;
79
import org.gvsig.fmap.geom.aggregate.MultiPoint;
80
import org.gvsig.fmap.geom.primitive.Envelope;
81
import org.gvsig.fmap.geom.primitive.Point;
82
import org.gvsig.fmap.geom.type.GeometryType;
83
import org.gvsig.tools.ToolsLocator;
84
import org.gvsig.tools.dataTypes.CoercionException;
85
import org.gvsig.tools.dataTypes.DataType;
86
import org.gvsig.tools.dataTypes.DataTypesManager;
87
import org.gvsig.tools.dataTypes.DataTypesManager.Coercion;
88
import org.gvsig.tools.dataTypes.DataTypesManager.CoercionWithLocale;
89
import org.gvsig.tools.dispose.DisposableIterator;
90
import org.gvsig.tools.dynobject.exception.DynFieldNotFoundException;
91
import org.gvsig.tools.evaluator.AbstractEvaluator;
92
import org.gvsig.tools.evaluator.EvaluatorData;
93
import org.gvsig.tools.evaluator.EvaluatorException;
94
import org.gvsig.tools.exception.BaseException;
95
import org.gvsig.tools.exception.NotYetImplemented;
96
import org.gvsig.tools.persistence.PersistentState;
97
import org.gvsig.tools.persistence.exception.PersistenceException;
98
import org.gvsig.tools.task.SimpleTaskStatus;
99
import org.gvsig.tools.task.TaskStatusManager;
100
import org.gvsig.tools.visitor.VisitCanceledException;
101
import org.gvsig.tools.visitor.Visitor;
102
import org.slf4j.Logger;
103
import org.slf4j.LoggerFactory;
104
import org.supercsv.io.CsvListWriter;
105
import org.supercsv.prefs.CsvPreference;
106

    
107
public class CSVStoreProvider extends AbstractMemoryStoreProvider implements
108
        ResourceConsumer {
109

    
110
    private static final Logger logger = LoggerFactory.getLogger(CSVStoreProvider.class);
111

    
112
    public static final String NAME = "CSV";
113
    public static final String DESCRIPTION = "CSV file";
114

    
115
    public static final String METADATA_DEFINITION_NAME = NAME;
116

    
117
    private ResourceProvider resource;
118

    
119
    private long counterNewsOIDs = 0;
120
    private Envelope envelope;
121
    private boolean need_calculate_envelope = false;
122
    private SimpleTaskStatus taskStatus;
123

    
124
    public CSVStoreProvider(CSVStoreParameters parameters,
125
            DataStoreProviderServices storeServices) throws InitializeException {
126
        super(
127
                parameters,
128
                storeServices,
129
                FileHelper.newMetadataContainer(METADATA_DEFINITION_NAME)
130
        );
131

    
132
        TaskStatusManager manager = ToolsLocator.getTaskStatusManager();
133
        this.taskStatus = manager.createDefaultSimpleTaskStatus("CSV");
134

    
135
        counterNewsOIDs = 0;
136

    
137
        File file = getCSVParameters().getFile();
138
        resource = this.createResource(
139
                FileResource.NAME,
140
                new Object[]{file.getAbsolutePath()}
141
        );
142

    
143
        resource.addConsumer(this);
144
        initializeFeatureTypes();
145
    }
146

    
147
    private CSVStoreParameters getCSVParameters() {
148
        return (CSVStoreParameters) this.getParameters();
149
    }
150

    
151
    public String getProviderName() {
152
        return NAME;
153
    }
154

    
155
    public boolean allowWrite() {
156
        return false;
157
    }
158

    
159
    private String getFullFileName() {
160
        // Usar solo para mostrar mensajes en el logger.
161
        String s = "(unknow)";
162
        try {
163
            s = getCSVParameters().getFile().getAbsolutePath();
164
        } catch (Exception e2) {
165
            s = "(unknow)";
166
        }
167
        return s;
168
    }
169

    
170
    public void open() throws OpenException {
171
        if ( this.data != null ) {
172
            return;
173
        }
174
        this.data = new ArrayList<FeatureProvider>();
175
        resource.setData(new HashMap());
176
        counterNewsOIDs = 0;
177
        try {
178
            loadFeatures();
179
        } catch (RuntimeException e) {
180
            logger.warn("Can't load features from CSV '" + getFullFileName() + "'.", e);
181
            throw e;
182
        } catch (Exception e) {
183
            logger.warn("Can't load features from CSV '" + getFullFileName() + "'.", e);
184
            throw new RuntimeException(e);
185
        }
186
    }
187

    
188
    public DataServerExplorer getExplorer() throws ReadException {
189
        DataManager manager = DALLocator.getDataManager();
190
        FilesystemServerExplorerParameters params;
191
        try {
192
            params = (FilesystemServerExplorerParameters) manager
193
                    .createServerExplorerParameters(FilesystemServerExplorer.NAME);
194
            params.setRoot(this.getCSVParameters().getFile().getParent());
195
            return manager.openServerExplorer(FilesystemServerExplorer.NAME, params);
196
        } catch (DataException e) {
197
            throw new ReadException(this.getProviderName(), e);
198
        } catch (ValidateDataParametersException e) {
199
            throw new ReadException(this.getProviderName(), e);
200
        }
201

    
202
    }
203

    
204
    class Writer {
205

    
206
        private Envelope envelope = null;
207
        private boolean calculate_envelope = false;
208
        private CsvListWriter listWriter = null;
209
        private CsvPreference csvpreferences = null;
210
        private FileWriter fwriter = null;
211
        private FeatureType ftype;
212
        private File file;
213
        private String[] values;
214
        private FeatureAttributeDescriptor[] descriptors;
215
        private Coercion convert = null;
216
        private int errorcounts = 0;
217
        private Throwable lasterror = null;
218
        private Locale locale = null;
219

    
220
        public void initialize(File file, FeatureType ftype, CsvPreference csvpreferences) {
221
            this.file = file;
222
            this.ftype = ftype;
223
            this.csvpreferences = csvpreferences;
224
            this.locale = CSVStoreParameters.getLocale(getCSVParameters());
225
            if ( csvpreferences == null ) {
226
                this.csvpreferences = CsvPreference.STANDARD_PREFERENCE;
227
            }
228
            if ( ftype.getDefaultGeometryAttributeName() != null ) {
229
                this.calculate_envelope = true;
230
            }
231
            this.descriptors = this.ftype.getAttributeDescriptors();
232
            this.convert = ToolsLocator.getDataTypesManager().getCoercion(org.gvsig.tools.dataTypes.DataTypes.STRING);
233
            this.errorcounts = 0;
234
        }
235

    
236
        public void begin() {
237
            try {
238
                this.fwriter = new FileWriter(file);
239
            } catch (IOException e) {
240
                logger.warn("Can't open file for write (" + file.getAbsolutePath() + ").", e);
241
                throw new RuntimeException(e);
242
            }
243
            this.listWriter = new CsvListWriter(this.fwriter, this.csvpreferences);
244
            int n = 0;
245
            for ( int i = 0; i < descriptors.length; i++ ) {
246
                FeatureAttributeDescriptor descriptor = descriptors[i];
247
                if ( descriptor.getEvaluator() == null ) {
248
                    n++;
249
                }
250
            }
251

    
252
            String[] header = new String[n];
253
            this.values = new String[n];
254
            n = 0;
255
            for ( int i = 0; i < descriptors.length; i++ ) {
256
                FeatureAttributeDescriptor descriptor = descriptors[i];
257
                if ( descriptor.getEvaluator() == null ) {
258
                    String name = descriptor.getName();
259
                    String typeName = descriptor.getDataTypeName();
260
                    if ( descriptor.getDataType().getType() == DataTypes.STRING ) {
261
                        header[n++] = name + "__" + typeName + "__" + descriptor.getSize();
262
                    } else {
263
                        header[n++] = name + "__" + typeName;
264
                    }
265
                }
266
            }
267
            try {
268
                listWriter.writeHeader(header);
269
            } catch (Exception e) {
270
                logger.warn("Can't write header '" + header.toString() + "' file for write (" + file.getAbsolutePath() + ").", e);
271
                throw new RuntimeException(e);
272
            }
273
        }
274

    
275
        public void add(FeatureProvider feature) {
276
            if ( this.calculate_envelope ) {
277
                Geometry geom = feature.getDefaultGeometry();
278
                if ( geom != null ) {
279
                    if ( envelope == null ) {
280
                        try {
281
                            envelope = (Envelope) geom.getEnvelope().clone();
282
                        } catch (CloneNotSupportedException e) {
283
                            logger.warn("Este error no deberia pasar, siempre se puede hacer un clone de un envelope.", e);
284
                        }
285
                    } else {
286
                        envelope.add(geom.getEnvelope());
287
                    }
288
                }
289
            }
290
            int n = 0;
291
            for ( int i = 0; i < descriptors.length; i++ ) {
292
                FeatureAttributeDescriptor descriptor = descriptors[i];
293
                if ( descriptor.getEvaluator() == null ) {
294
                    Object value = feature.get(i);
295
                    try {
296
                        n++;
297
                        if ( this.convert != null && this.convert instanceof CoercionWithLocale ) {
298
                            values[n] = (String) ((CoercionWithLocale) this.convert).coerce(value, this.locale);
299
                        } else {
300
                            values[n] = (String) this.convert.coerce(value);
301
                        }
302
                    } catch (CoercionException e) {
303
                        try {
304
                            values[n] = value.toString();
305
                        } catch (Exception ex) {
306
                            values[n] = "";
307
                        }
308
                        if ( errorcounts++ <= 10 ) {
309
                            this.lasterror = e;
310
                            logger.warn("Can't convert value of field " + i + " to string in CVS file '" + getFullFileName() + "'.", e);
311
                            if ( errorcounts == 10 ) {
312
                                logger.warn("Too many error writing CVS file '" + getFullFileName() + "', don't output more.");
313
                            }
314
                        }
315
                    }
316
                }
317
            }
318
            try {
319
                this.listWriter.writeHeader(values);
320
            } catch (IOException e) {
321
                if ( errorcounts++ <= 10 ) {
322
                    this.lasterror = e;
323
                    logger.warn("Can't write values to CVS file '" + getFullFileName() + "'.", e);
324
                    if ( errorcounts == 10 ) {
325
                        logger.warn("Too many error writing CVS file '" + getFullFileName() + "', don't output more.");
326
                    }
327
                }
328
            }
329

    
330
        }
331

    
332
        public void end() throws PerformEditingException {
333
            if ( this.errorcounts > 0 ) {
334
                throw new PerformEditingException(this.file.getAbsolutePath(), lasterror);
335
            }
336
            if ( listWriter != null ) {
337
                try {
338
                    listWriter.close();
339
                } catch (Exception ex) {
340
                    // Ignore error
341
                }
342
                listWriter = null;
343
            }
344
            if ( fwriter != null ) {
345
                try {
346
                    fwriter.close();
347
                } catch (Exception ex) {
348
                    // Ignore error
349
                }
350
                fwriter = null;
351
            }
352
        }
353

    
354
        public Envelope getEnvelope() {
355
            return this.envelope;
356
        }
357
    }
358

    
359
    public void performChanges(Iterator deleteds, Iterator inserteds, Iterator updateds, Iterator originalFeatureTypesUpdated) throws PerformEditingException {
360

    
361
        try {
362
            this.taskStatus.add();
363
            taskStatus.message("_preparing");
364
            getResource().execute(new ResourceAction() {
365
                public Object run() throws Exception {
366
                    FeatureSet features = null;
367
                    DisposableIterator it = null;
368
                    try {
369
                        File file = (File) resource.get();
370

    
371
                        Writer writer = new Writer();
372
                        writer.initialize(file, getStoreServices().getDefaultFeatureType(), getCSVPreferences());
373
                        features
374
                                = getStoreServices().getFeatureStore()
375
                                .getFeatureSet();
376
                        List<FeatureProvider> newdata = new ArrayList<FeatureProvider>();
377
                        writer.begin();
378
                        it = features.fastIterator();
379
                        taskStatus.setRangeOfValues(0, 0);
380
                        long counter = 0;
381
                        while ( it.hasNext() ) {
382
                            taskStatus.setCurValue(counter++);
383
                            FeatureProvider feature = getStoreServices().getFeatureProviderFromFeature(
384
                                    (org.gvsig.fmap.dal.feature.Feature) it.next());
385
                            writer.add(feature);
386
                            if ( feature.getOID() == null ) {
387
                                logger.warn("feature without OID");
388
                                feature.setOID(createNewOID());
389
                            }
390
                            newdata.add(feature);
391
                        }
392
                        data = newdata;
393
                        if ( writer.getEnvelope() != null ) {
394
                            envelope = writer.getEnvelope().getGeometry().getEnvelope();
395
                        }
396
                        resource.notifyChanges();
397
                        writer.end();
398
                    } finally {
399
                        if ( it != null ) {
400
                            it.dispose();
401
                        }
402
                        if ( features != null ) {
403
                            features.dispose();
404
                        }
405
                    }
406
                    return null;
407
                }
408

    
409
                private CsvPreference getCSVPreferences() {
410
                    CSVReader reader = new CSVReader(getCSVParameters());
411
                    return reader.getCSVPreferences();
412
                }
413

    
414
            });
415
            this.taskStatus.terminate();
416
        } catch (Exception e) {
417
            this.taskStatus.abort();
418
            throw new PerformEditingException(getResource().toString(), e);
419
        } finally {
420
            this.taskStatus.remove();
421
        }
422
    }
423

    
424
    public boolean closeResourceRequested(ResourceProvider resource) {
425
        return true;
426
    }
427

    
428
    public int getOIDType() {
429
        return DataTypes.LONG;
430
    }
431

    
432
    public boolean supportsAppendMode() {
433
        return false;
434
    }
435

    
436
    public void append(FeatureProvider featureProvider) {
437
        throw new UnsupportedOperationException();
438
    }
439

    
440
    public void beginAppend() {
441
        throw new UnsupportedOperationException();
442
    }
443

    
444
    public void endAppend() {
445
        throw new UnsupportedOperationException();
446
    }
447

    
448
    public void saveToState(PersistentState state) throws PersistenceException {
449
        throw new NotYetImplemented();
450
    }
451

    
452
    public void loadFromState(PersistentState state) throws PersistenceException {
453
        throw new NotYetImplemented();
454
    }
455

    
456
    public Object createNewOID() {
457
        return new Long(counterNewsOIDs++);
458
    }
459

    
460
    protected void initializeFeatureTypes() throws InitializeException {
461
        try {
462
            this.open();
463
        } catch (OpenException e) {
464
            throw new InitializeException(this.getProviderName(), e);
465
        }
466
    }
467

    
468
    public Envelope getEnvelope() throws DataException {
469
        this.open();
470
        if ( this.envelope != null ) {
471
            return this.envelope;
472
        }
473
        if ( !this.need_calculate_envelope ) {
474
            return null;
475
        }
476
        FeatureStore fs = this.getFeatureStore();
477
        FeatureType ft = fs.getDefaultFeatureType();
478
        FeatureAttributeDescriptor fad = ft.getAttributeDescriptor(ft.getDefaultGeometryAttributeIndex());
479

    
480
        try {
481
            this.envelope = GeometryLocator.getGeometryManager().createEnvelope(fad.getGeomType().getSubType());
482
            fs.accept(new Visitor() {
483
                public void visit(Object obj) throws VisitCanceledException, BaseException {
484
                    Feature f = (Feature) obj;
485
                    Geometry geom = f.getDefaultGeometry();
486
                    if ( geom != null ) {
487
                        envelope.add(geom.getEnvelope());
488
                    }
489
                }
490
            });
491
        } catch (BaseException e) {
492
            logger.warn("Can't calculate the envelope of CSV file '" + this.getFullName() + "'.", e);
493
            this.envelope = null;
494
        }
495

    
496
        this.need_calculate_envelope = false;
497
        return this.envelope;
498
    }
499

    
500
    public Object getDynValue(String name) throws DynFieldNotFoundException {
501
        if ( DataStore.METADATA_ENVELOPE.equalsIgnoreCase(name) ) {
502
            try {
503
                return this.getEnvelope();
504
            } catch (DataException e) {
505
                return null;
506
            }
507
        } else {
508
            if ( DataStore.METADATA_CRS.equalsIgnoreCase(name) ) {
509
                IProjection pro = CSVStoreParameters.getCRS(this.getCSVParameters());
510
                if ( pro != null ) {
511
                    return pro;
512
                }
513
            }
514
        }
515
        return super.getDynValue(name);
516
    }
517

    
518
    public void resourceChanged(ResourceProvider resource) {
519
        this.getStoreServices().notifyChange(
520
                DataStoreNotification.RESOURCE_CHANGED,
521
                resource);
522
    }
523

    
524
    public Object getSourceId() {
525
        return this.getCSVParameters().getFile();
526
    }
527

    
528
    public String getName() {
529
        String name = this.getCSVParameters().getFile().getName();
530
        return FilenameUtils.getBaseName(name);
531
    }
532

    
533
    public String getFullName() {
534
        return this.getCSVParameters().getFile().getAbsolutePath();
535
    }
536

    
537
    public ResourceProvider getResource() {
538
        return resource;
539
    }
540

    
541
    private boolean isEmpty(String s) {
542
        if ( s == null ) {
543
            return true;
544
        }
545
        return s.trim().length() == 0;
546
    }
547

    
548
    private class FieldTypeParser {
549

    
550
        public String name = null;
551
        public int type = DataTypes.STRING;
552
        public int size = 0;
553
        public boolean allowNulls = true;
554
        public int geometryType = Geometry.TYPES.GEOMETRY;
555

    
556
        private String typename = "string";
557

    
558
        FieldTypeParser() {
559
        }
560

    
561
        private int getType(String value) {
562
            DataTypesManager dataTypesManager = ToolsLocator.getDataTypesManager();
563
            return dataTypesManager.getType(typename);
564
        }
565

    
566
        // El formato seria:
567
        //   name[:typename[:size[:notnull|null]]]
568
        //   name[:GEOMETRY[:geometry_type[:notnull|null]]]
569
        //   name[__typename[__size[__notnull|null]]]
570
        //
571
        public boolean parse(String value) {
572
            String typename = null;
573
            String[] ss = null;
574
            if ( value.contains(":") ) {
575
                ss = value.split(":");
576
            } else if ( value.contains("__") ) {
577
                ss = value.split("__");
578
            }
579
            if ( ss == null ) {
580
                this.name = value;
581
                return true;
582
            }
583
            switch (ss.length) {
584
            case 4:
585
                if ( !StringUtils.isBlank(ss[3]) ) {
586
                    if ( "notnull".equalsIgnoreCase(ss[3].trim()) ) {
587
                        this.allowNulls = false;
588
                    } else {
589
                        this.allowNulls = true;
590
                    }
591
                }
592
            case 3:
593
                if ( !StringUtils.isBlank(ss[1]) ) {
594
                    this.typename = ss[1].trim();
595
                    this.type = this.getType(this.typename);
596
                    if ( this.type == DataTypes.INVALID ) {
597
                        this.type = DataTypes.STRING;
598
                        logger.info("Type '" + typename + "' not valid for attribute '" + value + "' in CSV file '" + getFullFileName() + "'.");
599
                    }
600
                }
601
                if ( !StringUtils.isBlank(ss[2]) ) {
602
                    if( this.type == DataTypes.GEOMETRY ) {
603
                        String s = ss[2].trim();
604
                        if( s.equalsIgnoreCase("line") || s.equalsIgnoreCase("linestring") || s.equalsIgnoreCase("curve") ) {
605
                            this.geometryType = Geometry.TYPES.CURVE;
606
                        } else if( s.equalsIgnoreCase("multiline") || s.equalsIgnoreCase("multilinestring")  || s.equalsIgnoreCase("multicurve") ) {
607
                            this.geometryType = Geometry.TYPES.MULTICURVE;
608
                        } else if( s.equalsIgnoreCase("point") ) {
609
                            this.geometryType = Geometry.TYPES.POINT;
610
                        } else if( s.equalsIgnoreCase("multipoint") ) {
611
                            this.geometryType = Geometry.TYPES.MULTIPOINT;
612
                        } else if( s.equalsIgnoreCase("polygon") || s.equalsIgnoreCase("surface") ) {
613
                            this.geometryType = Geometry.TYPES.POLYGON;
614
                        } else if( s.equalsIgnoreCase("multipolygon") || s.equalsIgnoreCase("multisurface") ) {
615
                            this.geometryType = Geometry.TYPES.MULTISURFACE;
616
                        }
617
                        this.size = 1;
618
                    } else {
619
                        try {
620
                            this.size = Integer.parseInt(ss[2]);
621
                        } catch (Exception ex) {
622
                            logger.warn("Ignore incorrect field size for field " + value + " in CSV header of '" + getFullFileName() + "'.", ex);
623
                        }
624
                    }
625
                }
626
                this.name = ss[0].trim();
627
                break;
628
            case 2:
629
                if ( !StringUtils.isBlank(ss[1]) ) {
630
                    this.typename = ss[1].trim();
631
                    this.type = this.getType(this.typename);
632
                    if ( this.type == DataTypes.INVALID ) {
633
                        this.type = DataTypes.STRING;
634
                        logger.info("Type '" + typename + "' not valid for attribute '" + value + "' in CSV file '" + getFullFileName() + "'.");
635
                    }
636
                }
637
            case 1:
638
                this.name = ss[0].trim();
639
                break;
640
            }
641

    
642
            if ( this.type != DataTypes.STRING ) {
643
                this.size = 0;
644
            }
645
            return true;
646
        }
647

    
648
    }
649

    
650
    private EditableFeatureType getFeatureType(String headers[], int automaticTypes[]) {
651
        EditableFeatureType fType = getStoreServices().createFeatureType(this.getName());
652
        fType.setHasOID(true);
653

    
654
        FieldTypeParser[] fieldTypes = new FieldTypeParser[headers.length];
655
        //
656
        // Calculamos cuales pueden ser los tipos de datos
657
        //
658
        for ( int i = 0; i < fieldTypes.length; i++ ) {
659
            fieldTypes[i] = new FieldTypeParser();
660
        }
661

    
662
        // Asuminos los tipos pasados por parametro, que se supone
663
        // son los detectados automaticamente.
664
        if ( automaticTypes != null ) {
665
            for ( int i = 0; i < fieldTypes.length && i < automaticTypes.length; i++ ) {
666
                fieldTypes[i].type = automaticTypes[i];
667
            }
668
        }
669
        // Luego probamos con lo que diga las cabezeras del CVS, sobreescribiendo
670
        // los tipos anteriores en caso de definirse en la cabezara.
671
        for ( int i = 0; i < fieldTypes.length; i++ ) {
672
            if ( !fieldTypes[i].parse(headers[i]) ) {
673
                continue;
674
            }
675

    
676
        }
677

    
678
        // Y por ultimo hacemos caso a lo que se haya especificado en los parametros
679
        // de apertura del CSV, teniendo esto prioridad sobre todo.
680
        String param_types_def = CSVStoreParameters.getRawFieldTypes(this.getParameters());
681
        if (StringUtils.isNotBlank(param_types_def)) {
682
            String sep = CSVStoreParameters.getDelimiter(param_types_def);
683
            if ( StringUtils.isNotBlank(sep) ) {
684
                String[] param_types = param_types_def.split(sep);
685
                for (int i = 0; i < fieldTypes.length && i < param_types.length; i++) {
686
                    if (!fieldTypes[i].parse(param_types[i])) {
687
                        continue;
688
                    }
689

    
690
                }
691
            }
692
        }
693
        //
694
        // Una vez ya sabemos los tipos de datos rellenamos el feature-type
695
        //
696
        for ( int i = 0; i < fieldTypes.length; i++ ) {
697
            EditableFeatureAttributeDescriptor fad = fType.add(
698
                    fieldTypes[i].name,
699
                    fieldTypes[i].type
700
            );
701
            fad.setSize(fieldTypes[i].size);
702
            fad.setAllowNull(fieldTypes[i].allowNulls);
703
            if ( fieldTypes[i].type == DataTypes.GEOMETRY ) {
704
                if( fType.getDefaultGeometryAttributeName() == null ) {
705
                    fType.setDefaultGeometryAttributeName(fieldTypes[i].name);
706
                }
707
                fad.setGeometryType(fieldTypes[i].geometryType);
708
            }
709
        }
710
        String[] pointDimensionNames = CSVStoreParameters.getPointDimensionNames(this.getParameters());
711
        if ( pointDimensionNames != null ) {
712
            PointAttributeEmulator emulator = new PointAttributeEmulator(pointDimensionNames);
713
            EditableFeatureAttributeDescriptor attr = fType.add("GEOM", DataTypes.GEOMETRY, emulator);
714
            GeometryManager geommgr = GeometryLocator.getGeometryManager();
715
            GeometryType gt;
716
            try {
717
                gt = geommgr.getGeometryType(Geometry.TYPES.GEOMETRY, Geometry.SUBTYPES.GEOM3D);
718
                attr.setGeometryType(gt);
719
                attr.setGeometryType(Geometry.TYPES.POINT);
720
                attr.setGeometrySubType(Geometry.SUBTYPES.GEOM3D);
721
            } catch (Exception e) {
722
                logger.warn("Can't set geometry type for the calculated field in CSV file '" + getFullFileName() + "'.", e);
723
            }
724
        }
725
        return fType;
726
    }
727

    
728
    static class PointAttributeEmulator implements FeatureAttributeEmulator {
729

    
730
        private static final Logger logger = LoggerFactory.getLogger(ToPointEvaluaror.class);
731

    
732
        private static final int XNAME = 0;
733
        private static final int YNAME = 1;
734
        private static final int ZNAME = 2;
735

    
736
        private final GeometryManager geommgr;
737
        private final String[] fieldNames;
738
        private final Coercion toDouble;
739
        private final DataType dataType;
740
        private int errorcount = 0;
741

    
742
        public PointAttributeEmulator(String[] pointDimensionNames) {
743
            if ( pointDimensionNames.length > 2 ) {
744
                this.fieldNames = new String[3];
745
                this.fieldNames[ZNAME] = pointDimensionNames[2];
746
            } else {
747
                this.fieldNames = new String[2];
748
            }
749
            this.fieldNames[XNAME] = pointDimensionNames[0];
750
            this.fieldNames[YNAME] = pointDimensionNames[1];
751
            this.geommgr = GeometryLocator.getGeometryManager();
752
            DataTypesManager datatypeManager = ToolsLocator.getDataTypesManager();
753

    
754
            this.toDouble = datatypeManager.getCoercion(DataTypes.DOUBLE);
755
            this.dataType = datatypeManager.get(DataTypes.GEOMETRY);
756
        }
757

    
758
        public Object get(Feature feature) {
759
            try {
760
                Object valueX = feature.get(this.fieldNames[XNAME]);
761
                valueX = toDouble.coerce(valueX);
762
                if ( valueX == null ) {
763
                    return null;
764
                }
765
                Object valueY = feature.get(this.fieldNames[YNAME]);
766
                valueY = toDouble.coerce(valueY);
767
                if ( valueY == null ) {
768
                    return null;
769
                }
770
                Object valueZ = null;
771
                if ( this.fieldNames.length > 2 ) {
772
                    valueZ = toDouble.coerce(feature.get(this.fieldNames[ZNAME]));
773
                    if ( valueZ == null ) {
774
                        return null;
775
                    }
776
                }
777

    
778
                double x = ((Double) valueX).doubleValue();
779
                double y = ((Double) valueY).doubleValue();
780
                Point point = geommgr.createPoint(x, y, Geometry.SUBTYPES.GEOM3D);
781
                if ( this.fieldNames.length > 2 ) {
782
                    double z = ((Double) valueZ).doubleValue();
783
                    point.setCoordinateAt(2, z);
784
                }
785
                return point;
786
            } catch (Exception ex) {
787
                if ( ++errorcount < 5 ) {
788
                    logger.warn("[" + errorcount + "] Can't create point in CSV provider. XNAME='"
789
                            + this.fieldNames[XNAME] + "', YNAME='" + this.fieldNames[XNAME] + "' feature=" + feature.toString(), ex);
790
                }
791
                return null;
792
            }
793
        }
794

    
795
        public void set(EditableFeature feature, Object value) {
796
            if ( value == null ) {
797
                return;
798
            }
799
            Point point = null;
800
            if ( value instanceof MultiPoint ) {
801
                point = (Point) ((MultiPoint) value).getPrimitiveAt(0);
802
            } else {
803
                point = (Point) value;
804
            }
805
            feature.set(this.fieldNames[XNAME], point.getX());
806
            feature.set(this.fieldNames[YNAME], point.getY());
807
            if ( this.fieldNames.length > 2 ) {
808
                feature.set(this.fieldNames[ZNAME], point.getCoordinateAt(2));
809
            }
810
        }
811

    
812
        public boolean allowSetting() {
813
            return true;
814
        }
815

    
816
        public String[] getRequiredFieldNames() {
817
            return this.fieldNames;
818
        }
819

    
820
    }
821

    
822
    static class ToPointEvaluaror extends AbstractEvaluator {
823

    
824
        private static final Logger logger = LoggerFactory.getLogger(ToPointEvaluaror.class);
825

    
826
        private GeometryManager geommgr = null;
827
        private String xname = null;
828
        private String yname = null;
829
        private String zname = null;
830
        private Coercion toDouble;
831
        private int errorcount = 0;
832

    
833
        ToPointEvaluaror(String[] pointDimensionNames) {
834
            this.xname = pointDimensionNames[0];
835
            this.yname = pointDimensionNames[1];
836
            if ( pointDimensionNames.length > 2 ) {
837
                this.zname = pointDimensionNames[2];
838
            }
839
            this.geommgr = GeometryLocator.getGeometryManager();
840
            this.toDouble = ToolsLocator.getDataTypesManager().getCoercion(DataTypes.DOUBLE);
841
        }
842

    
843
        public Object evaluate(EvaluatorData data) throws EvaluatorException {
844
            try {
845
                double x = ((Double) toDouble.coerce(data.getDataValue(xname))).doubleValue();
846
                double y = ((Double) toDouble.coerce(data.getDataValue(yname))).doubleValue();
847
                Point point = geommgr.createPoint(x, y, Geometry.SUBTYPES.GEOM3D);
848
                if ( zname != null ) {
849
                    double z = ((Double) toDouble.coerce(data.getDataValue(zname))).doubleValue();
850
                    point.setCoordinateAt(2, z);
851
                }
852
                return point;
853
            } catch (Exception ex) {
854
                if ( ++errorcount < 5 ) {
855
                    logger.warn("[" + errorcount + "] Can't create point in CSV provider. XNAME='"
856
                            + xname + "', YNAME='" + yname + "', ZNAME='" + zname + "', data=" + data.toString());
857
                }
858
                return null;
859
            }
860
        }
861

    
862
        public String getName() {
863
            return "ToPointEvaluaror";
864
        }
865

    
866
    }
867

    
868
    private SimpleReader getSimpleReader(FileReader in) {
869
        SimpleReader reader;
870
        if ( CSVStoreParameters.getRawFieldsDefinition(getCSVParameters()) != null ) {
871
            reader = new FixedLenReader(in, getCSVParameters());
872
        } else {
873
            reader = new CSVReader(in, getCSVParameters());
874
        }
875
        return reader;
876
    }
877

    
878
    private void loadFeatures() throws IOException, DataException,
879
            CoercionException, CloneNotSupportedException {
880
        FileReader in = null;
881
        SimpleReader reader = null;
882
        try {
883
            String headers[] = null;
884
            FeatureStoreProviderServices store = this.getStoreServices();
885

    
886
            boolean ignore_errors = CSVStoreParameters.getIgnoreErrors(getCSVParameters());
887

    
888
            in = new FileReader(this.getCSVParameters().getFile());
889

    
890
            reader = getSimpleReader(in);
891

    
892
            headers = CSVStoreParameters.getHeaders(getCSVParameters());
893
            if ( headers == null ) {
894
                headers = reader.getHeader();
895
                if ( headers == null ) {
896
                    String msg = "Can't retrieve header from csv file '"
897
                            + this.getCSVParameters().getFile()
898
                            .getAbsolutePath()
899
                            + "' and not specified in the parameters.";
900
                    logger.warn(msg);
901
                    throw new RuntimeException(msg);
902
                }
903
            }
904

    
905
            // Initialize the feature types
906
            EditableFeatureType edftype = this.getFeatureType(headers, automaticDetectionOfTypes());
907
            FeatureType ftype = edftype.getNotEditableCopy();
908
            List<FeatureType> ftypes = new ArrayList<FeatureType>();
909
            ftypes.add(ftype);
910
            store.setFeatureTypes(ftypes, ftype);
911

    
912
            Coercion coercion[] = new Coercion[ftype.size()];
913
            int sizes[] = new int[ftype.size()];
914
            for ( int i = 0; i < ftype.size(); i++ ) {
915
                sizes[i] = -1;
916
                FeatureAttributeDescriptor ad = ftype.getAttributeDescriptor(i);
917
                coercion[i] = ad.getDataType().getCoercion();
918
                if ( ad.getDataType().getType() == DataTypes.STRING ) {
919
                    if ( ad.getSize() == 0 ) {
920
                        // Es un string y no tiene un size asignado.
921
                        // Lo ponemos a cero para calcularlo.
922
                        sizes[i] = 0;
923
                    }
924
                }
925
            }
926
            if ( ftype.getDefaultGeometryAttributeName() != null ) {
927
                this.need_calculate_envelope = true;
928
            }
929

    
930
            Locale locale = CSVStoreParameters.getLocale(getCSVParameters());
931
            taskStatus.message("_loading");
932
            int count = 0;
933

    
934
            int count_errors = 0;
935

    
936
            List<String> row = reader.read();
937

    
938
            int skipLines = CSVStoreParameters.getSkipLines(getCSVParameters());
939
            if ( skipLines > 0 ) {
940
                row = reader.skip(skipLines);
941
            }
942

    
943
            while ( row != null ) {
944
                taskStatus.setCurValue(++count);
945
                FeatureProvider feature = this.createFeatureProvider(ftype);
946
                for ( int i = 0; i < row.size(); i++ ) {
947
                    Object rawvalue = row.get(i);
948
                    try {
949
                        Object value = null;
950
                        if ( locale != null && coercion[i] instanceof CoercionWithLocale ) {
951
                            value = ((CoercionWithLocale) (coercion[i])).coerce(rawvalue, locale);
952
                        } else {
953
                            value = coercion[i].coerce(rawvalue);
954
                        }
955
                        feature.set(i, value);
956
                        if ( sizes[i] >= 0 && value != null ) {
957
                            int x = ((String) value).length();
958
                            if ( sizes[i] < x ) {
959
                                sizes[i] = x;
960
                            }
961
                        }
962
                    } catch (RuntimeException ex) {
963
                        if ( !ignore_errors ) {
964
                            throw ex;
965
                        }
966
                        if ( count_errors++ < 10 ) {
967
                            logger.warn("Can't load value of attribute " + i + " in row " + count + ".", ex);
968
                        }
969
                        if ( count_errors == 10 ) {
970
                            logger.info("Too many errors, suppress messages.");
971
                        }
972
                    }
973
                }
974
                this.addFeatureProvider(feature);
975
                row = reader.read();
976
            }
977
            for ( int i = 0; i < ftype.size(); i++ ) {
978
                if ( sizes[i] > 0 ) {
979
                    EditableFeatureAttributeDescriptor efad = ((EditableFeatureAttributeDescriptor) edftype.getAttributeDescriptor(i));
980
                    efad.setSize(sizes[i]);
981
                }
982
            }
983
            // Volvemos a asignar al store el featuretype, ya que puede
984
            // haber cambiado.
985
            ftype = edftype.getNotEditableCopy();
986
            ftypes = new ArrayList<FeatureType>();
987
            ftypes.add(ftype);
988
            store.setFeatureTypes(ftypes, ftype);
989

    
990
            taskStatus.terminate();
991
        } catch(Exception ex) {
992
            int lineno = 0;
993
            if( reader!=null ) {
994
                lineno = reader.getLine();
995
            }
996
            throw new RuntimeException("Problems reading file '"+getFullFileName()+"' near line "+lineno+".", ex);
997

    
998
        } finally {
999
            if ( reader != null ) {
1000
                try {
1001
                    reader.close();
1002
                } catch (Exception ex) {
1003
                    // Do nothing
1004
                }
1005
                reader = null;
1006
            }
1007
            if ( in != null ) {
1008
                try {
1009
                    in.close();
1010
                } catch (Exception ex) {
1011
                    // Do nothing
1012
                }
1013
                in = null;
1014
            }
1015
        }
1016
    }
1017

    
1018
    private int[] automaticDetectionOfTypes() throws IOException {
1019
        boolean automatic_types_detection = CSVStoreParameters.getAutomaticTypesDetection(getCSVParameters());
1020
        if ( !automatic_types_detection ) {
1021
            return null;
1022
        }
1023

    
1024
        final int T_INT = 0;
1025
        final int T_FLOAT = 1;
1026
        final int T_DOUBLE = 2;
1027
        final int T_LONG = 3;
1028
        final int T_URL = 4;
1029
        final int T_DATE = 5;
1030
        boolean possibleDataTypes[][] = null;
1031
        Locale locale = null;
1032
        int[] types = null;
1033

    
1034
        FileReader in = null;
1035
        SimpleReader reader = null;
1036
        String headers[] = null;
1037
        SimpleDateFormat dateFormat = new SimpleDateFormat();
1038

    
1039
        try {
1040

    
1041
            in = new FileReader(this.getCSVParameters().getFile());
1042

    
1043
            reader = getSimpleReader(in);
1044
            headers = reader.getHeader();
1045
            if ( headers == null ) {
1046
                headers = CSVStoreParameters.getHeaders(getCSVParameters());
1047
            }
1048
            types = new int[headers.length];
1049

    
1050
            possibleDataTypes = new boolean[headers.length][6];
1051
            for ( int i = 0; i < possibleDataTypes.length; i++ ) {
1052
                for ( int j = 0; j < 4; j++ ) {
1053
                    possibleDataTypes[i][j] = true;
1054
                }
1055
            }
1056
            locale = CSVStoreParameters.getLocale(getCSVParameters());
1057
            if ( locale == null ) {
1058
                locale = Locale.getDefault();
1059
            }
1060

    
1061
            DataTypesManager typeManager = ToolsLocator.getDataTypesManager();
1062
            CoercionWithLocale toDouble = (CoercionWithLocale) typeManager.getCoercion(DataTypes.DOUBLE);
1063
            CoercionWithLocale toFloat = (CoercionWithLocale) typeManager.getCoercion(DataTypes.FLOAT);
1064
            CoercionWithLocale toDate = (CoercionWithLocale) typeManager.getCoercion(DataTypes.DATE);
1065
            Coercion toInt = typeManager.getCoercion(DataTypes.INT);
1066
            Coercion toLong = typeManager.getCoercion(DataTypes.LONG);
1067

    
1068
            List<String> row = reader.read();
1069

    
1070
            while ( row != null ) {
1071
                for ( int i = 0; i < row.size(); i++ ) {
1072
                    Object rawvalue = row.get(i);
1073
                    Object value = null;
1074
                    if ( possibleDataTypes[i][T_DOUBLE] ) {
1075
                        try {
1076
                            value = toDouble.coerce(rawvalue, locale);
1077
                            possibleDataTypes[i][T_DOUBLE] = true;
1078
                        } catch (Exception ex) {
1079
                            possibleDataTypes[i][T_DOUBLE] = false;
1080
                        }
1081
                    }
1082
                    if ( possibleDataTypes[i][T_FLOAT] ) {
1083
                        try {
1084
                            value = toFloat.coerce(rawvalue, locale);
1085
                            possibleDataTypes[i][T_FLOAT] = true;
1086
                        } catch (Exception ex) {
1087
                            possibleDataTypes[i][T_FLOAT] = false;
1088
                        }
1089
                    }
1090
                    if ( possibleDataTypes[i][T_LONG] ) {
1091
                        try {
1092
                            value = toLong.coerce(rawvalue);
1093
                            possibleDataTypes[i][T_LONG] = true;
1094
                        } catch (Exception ex) {
1095
                            possibleDataTypes[i][T_LONG] = false;
1096
                        }
1097
                    }
1098
                    if ( possibleDataTypes[i][T_INT] ) {
1099
                        try {
1100
                            value = toInt.coerce(rawvalue);
1101
                            possibleDataTypes[i][T_INT] = true;
1102
                        } catch (Exception ex) {
1103
                            possibleDataTypes[i][T_INT] = false;
1104
                        }
1105
                    }
1106
                    if ( possibleDataTypes[i][T_DATE] ) {
1107
                        try {
1108
                            value = toDate.coerce(rawvalue, locale);
1109
                            possibleDataTypes[i][T_DATE] = true;
1110
                        } catch (Exception ex) {
1111
                            possibleDataTypes[i][T_DATE] = false;
1112
                        }
1113
                    }
1114
                    if ( possibleDataTypes[i][T_URL] ) {
1115
                        try {
1116
                            value = new URL((String) rawvalue);
1117
                            possibleDataTypes[i][T_URL] = true;
1118
                        } catch (Exception ex) {
1119
                            possibleDataTypes[i][T_URL] = false;
1120
                        }
1121
                    }
1122
                }
1123
                row = reader.read();
1124
            }
1125
        } catch(Exception ex) {
1126
            int lineno = 0;
1127
            if( reader!=null ) {
1128
                lineno = reader.getLine();
1129
            }
1130
            throw new RuntimeException("Problems reading file '"+getFullFileName()+"' near line "+lineno+".", ex);
1131

    
1132
        } finally {
1133
            if ( reader != null ) {
1134
                try {
1135
                    reader.close();
1136
                } catch (Exception ex) {
1137
                    // Do nothing
1138
                }
1139
                reader = null;
1140
            }
1141
            if ( in != null ) {
1142
                try {
1143
                    in.close();
1144
                } catch (Exception ex) {
1145
                    // Do nothing
1146
                }
1147
                in = null;
1148
            }
1149

    
1150
        }
1151
        for ( int i = 0; i < possibleDataTypes.length; i++ ) {
1152
            if ( possibleDataTypes[i][T_INT] ) {
1153
                types[i] = DataTypes.INT;
1154
                continue;
1155
            }
1156
            if ( possibleDataTypes[i][T_LONG] ) {
1157
                types[i] = DataTypes.LONG;
1158
                continue;
1159
            }
1160
            if ( possibleDataTypes[i][T_DOUBLE] ) {
1161
                types[i] = DataTypes.DOUBLE;
1162
                continue;
1163
            }
1164
            if ( possibleDataTypes[i][T_FLOAT] ) {
1165
                types[i] = DataTypes.FLOAT;
1166
                continue;
1167
            }
1168
            if ( possibleDataTypes[i][T_URL] ) {
1169
                types[i] = DataTypes.URL;
1170
                continue;
1171
            }
1172
            if ( possibleDataTypes[i][T_DATE] ) {
1173
                types[i] = DataTypes.DATE;
1174
                continue;
1175
            }
1176
            types[i] = DataTypes.STRING;
1177
        }
1178
        return types;
1179
    }
1180

    
1181
}