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

History | View | Annotate | Download (45.1 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 modify it under
7
 * the terms of the GNU General Public License as published by the Free Software
8
 * Foundation; either version 3 of the License, or (at your option) any later
9
 * version.
10
 *
11
 * This program is distributed in the hope that it will be useful, but WITHOUT
12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14
 * details.
15
 *
16
 * You should have received a copy of the GNU General Public License along with
17
 * this program; if not, write to the Free Software Foundation, Inc., 51
18
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19
 *
20
 * For any additional information, do not hesitate to contact us at info AT
21
 * gvsig.com, or visit our website www.gvsig.com.
22
 */
23
package org.gvsig.fmap.dal.store.csv;
24

    
25
import java.io.File;
26
import java.io.FileInputStream;
27
import java.io.FileNotFoundException;
28
import java.io.FileReader;
29
import java.io.IOException;
30
import java.io.InputStreamReader;
31
import java.net.URI;
32
import java.net.URL;
33
import java.nio.charset.Charset;
34
import java.util.ArrayList;
35
import java.util.HashMap;
36
import java.util.Iterator;
37
import java.util.List;
38
import java.util.Locale;
39
import java.util.Map;
40

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

    
111
@SuppressWarnings("UseSpecificCatch")
112
public class CSVStoreProvider extends AbstractMemoryStoreProvider implements
113
        ResourceConsumer {
114

    
115
    private static final Logger LOGGER = LoggerFactory.getLogger(CSVStoreProvider.class);
116

    
117
    public static final String NAME = "CSV";
118
    public static final String DESCRIPTION = "CSV file";
119

    
120
    public static final String METADATA_DEFINITION_NAME = NAME;
121

    
122
    private ResourceProvider resource;
123

    
124
    private long counterNewsOIDs = 0;
125
    private Envelope envelope;
126
    private boolean need_calculate_envelope = false;
127
    private final SimpleTaskStatus taskStatus;
128
    private final CSVFeatureWriter writer;
129

    
130
    public CSVStoreProvider(CSVStoreParameters parameters,
131
            DataStoreProviderServices storeServices) throws InitializeException {
132
        super(
133
                parameters,
134
                storeServices,
135
                FileHelper.newMetadataContainer(METADATA_DEFINITION_NAME)
136
        );
137
        this.writer = new CSVFeatureWriter();
138
        TaskStatusManager manager = ToolsLocator.getTaskStatusManager();
139
        this.taskStatus = manager.createDefaultSimpleTaskStatus("CSV");
140

    
141
        counterNewsOIDs = 0;
142

    
143
        File file = getCSVParameters().getFile();
144
        resource = this.createResource(
145
                FileResource.NAME,
146
                new Object[]{file.getAbsolutePath()}
147
        );
148

    
149
        resource.addConsumer(this);
150

    
151
        initializeFeatureTypes();
152
    }
153

    
154
    private CSVStoreParameters getCSVParameters() {
155
        return (CSVStoreParameters) this.getParameters();
156
    }
157

    
158
    @Override
159
    public String getProviderName() {
160
        return NAME;
161
    }
162

    
163
    @Override
164
    public boolean allowWrite() {
165
        return true;
166
    }
167

    
168
    private String getFullFileName() {
169
        // Usar solo para mostrar mensajes en el logger.
170
        String s;
171
        try {
172
            s = getCSVParameters().getFile().getAbsolutePath();
173
        } catch (Exception e2) {
174
            s = "(unknow)";
175
        }
176
        return s;
177
    }
178

    
179
    @Override
180
    public void open() throws OpenException {
181
        if (this.data != null) {
182
            return;
183
        }
184
        this.data = new ArrayList<>();
185
        resource.setData(new HashMap());
186
        counterNewsOIDs = 0;
187
        try {
188
            loadFeatures();
189
        } catch (RuntimeException e) {
190
            LOGGER.debug("Can't load features from CSV '" + getFullFileName() + "'.", e);
191
            throw e;
192
        } catch (Exception e) {
193
            LOGGER.debug("Can't load features from CSV '" + getFullFileName() + "'.", e);
194
            throw new RuntimeException(e);
195
        }
196
    }
197

    
198
    @Override
199
    public DataServerExplorer getExplorer() throws ReadException {
200
        DataManager manager = DALLocator.getDataManager();
201
        FilesystemServerExplorerParameters params;
202
        try {
203
            params = (FilesystemServerExplorerParameters) manager
204
                    .createServerExplorerParameters(FilesystemServerExplorer.NAME);
205
            params.setRoot(this.getCSVParameters().getFile().getParent());
206
            return manager.openServerExplorer(FilesystemServerExplorer.NAME, params);
207
        } catch (DataException e) {
208
            throw new ReadException(this.getProviderName(), e);
209
        } catch (ValidateDataParametersException e) {
210
            throw new ReadException(this.getProviderName(), e);
211
        }
212

    
213
    }
214

    
215
    @Override
216
    public void performChanges(Iterator deleteds, Iterator inserteds, Iterator updateds, Iterator originalFeatureTypesUpdated) throws PerformEditingException {
217

    
218
        try {
219
            this.taskStatus.add();
220
            taskStatus.message("_preparing");
221
            this.getResource().closeRequest();
222
            getResource().execute(new ResourceAction() {
223
                @Override
224
                public Object run() throws Exception {
225
                    FeatureSet features = null;
226
                    DisposableIterator it = null;
227
                    try {
228
                        File file = (File) resource.get();
229

    
230
                        features
231
                                = getStoreServices().getFeatureStore()
232
                                        .getFeatureSet();
233
                        List<FeatureProvider> newdata = new ArrayList<FeatureProvider>();
234
                        FeatureType ftype = getStoreServices().getDefaultFeatureType();
235
                        writer.initialize(getCSVParameters(), file, ftype, getCSVPreferences());
236
                        writer.beginAppend();
237
                        it = features.fastIterator();
238
                        taskStatus.setRangeOfValues(0, 0);
239
                        long counter = 0;
240
                        while (it.hasNext()) {
241
                            taskStatus.setCurValue(counter++);
242
                            FeatureProvider feature = getStoreServices().getFeatureProviderFromFeature(
243
                                    (org.gvsig.fmap.dal.feature.Feature) it.next());
244
                            writer.add(feature);
245
                            if (feature.getOID() == null) {
246
                                LOGGER.warn("feature without OID");
247
                                feature.setOID(createNewOID());
248
                            }
249
                            newdata.add(feature);
250
                        }
251
                        data = newdata;
252
                        if (writer.getEnvelope() != null) {
253
                            envelope = writer.getEnvelope().getGeometry().getEnvelope();
254
                        }
255
                        resource.notifyChanges();
256
                        writer.end();
257
                    } finally {
258
                        if (it != null) {
259
                            it.dispose();
260
                        }
261
                        if (features != null) {
262
                            features.dispose();
263
                        }
264
                    }
265
                    return null;
266
                }
267

    
268
            });
269
            this.taskStatus.terminate();
270
        } catch (Exception e) {
271
            this.taskStatus.abort();
272
            throw new PerformEditingException(getResource().toString(), e);
273
        } finally {
274
            this.taskStatus.remove();
275
        }
276
    }
277

    
278
    private CsvPreference getCSVPreferences() {
279
        CSVReader reader = new CSVReader(getCSVParameters());
280
        return reader.getCSVPreferences();
281
    }
282

    
283
    @Override
284
    public boolean closeResourceRequested(ResourceProvider resource) {
285
        return true;
286
    }
287

    
288
    @Override
289
    public int getOIDType() {
290
        return DataTypes.LONG;
291
    }
292

    
293
    @Override
294
    public boolean supportsAppendMode() {
295
        return true;
296
    }
297

    
298
    @Override
299
    public void append(final FeatureProvider featureProvider) {
300
        //todo
301
        getResource().execute(new ResourceAction() {
302
            @Override
303
            public Object run() throws Exception {
304
                //writer.append(getStoreServices().createFeature(featureProvider));
305
                writer.add(featureProvider);
306
                return null;
307
            }
308
        });
309
    }
310

    
311
    @Override
312
    public void beginAppend() throws DataException {
313
        this.close();
314
        getResource().execute(new ResourceAction() {
315
            public Object run() throws Exception {
316
                writer.initialize(
317
                        getCSVParameters(),
318
                        getCSVParameters().getFile(),
319
                        getFeatureStore().getDefaultFeatureType(),
320
                        getCSVPreferences()
321
                );
322
                writer.beginAppend();
323
                return null;
324
            }
325
        });
326

    
327
    }
328

    
329
    @Override
330
    public void endAppend() {
331
        try {
332
            getResource().execute(new ResourceAction() {
333
                public Object run() throws Exception {
334
                    writer.end();
335
                    resource.notifyChanges(); //resourcesNotifyChanges();
336
                    counterNewsOIDs = -1;
337
                    return null;
338
                }
339
            });
340
            writer.end();
341
        } catch (PerformEditingException ex) {
342
            LOGGER.warn("Not been able to end append '" + this.getFullName() + "'.", ex);
343
        }
344
    }
345

    
346
    public void saveToState(PersistentState state) throws PersistenceException {
347
        throw new NotYetImplemented();
348
    }
349

    
350
    public void loadFromState(PersistentState state) throws PersistenceException {
351
        throw new NotYetImplemented();
352
    }
353

    
354
    @Override
355
    public Object createNewOID() {
356
        return counterNewsOIDs++;
357
    }
358

    
359
    protected void initializeFeatureTypes() throws InitializeException {
360
        try {
361
            this.open();
362
        } catch (OpenException e) {
363
            throw new InitializeException(this.getProviderName(), e);
364
        }
365
    }
366

    
367
    @Override
368
    public Envelope getEnvelope() throws DataException {
369
        this.open();
370
        if (this.envelope != null) {
371
            return this.envelope;
372
        }
373
        if (!this.need_calculate_envelope) {
374
            return null;
375
        }
376
        FeatureStore fs = this.getFeatureStore();
377
        FeatureType ft = fs.getDefaultFeatureType();
378
        FeatureAttributeDescriptor fad = ft.getAttributeDescriptor(ft.getDefaultGeometryAttributeIndex());
379

    
380
        try {
381
            this.envelope = GeometryLocator.getGeometryManager().createEnvelope(fad.getGeomType().getSubType());
382
            fs.accept(new Visitor() {
383
                @Override
384
                public void visit(Object obj) throws VisitCanceledException, BaseException {
385
                    Feature f = (Feature) obj;
386
                    Geometry geom = f.getDefaultGeometry();
387
                    if (geom != null) {
388
                        envelope.add(geom.getEnvelope());
389
                    }
390
                }
391
            });
392
        } catch (BaseException e) {
393
            LOGGER.warn("Can't calculate the envelope of CSV file '" + this.getFullName() + "'.", e);
394
            this.envelope = null;
395
        }
396

    
397
        this.need_calculate_envelope = false;
398
        return this.envelope;
399
    }
400

    
401
    @Override
402
    public Object getDynValue(String name) throws DynFieldNotFoundException {
403
        if (DataStore.METADATA_ENVELOPE.equalsIgnoreCase(name)) {
404
            try {
405
                return this.getEnvelope();
406
            } catch (DataException e) {
407
                return null;
408
            }
409
        } else {
410
            if (DataStore.METADATA_CRS.equalsIgnoreCase(name)) {
411
                IProjection pro = CSVStoreParameters.getCRS(this.getCSVParameters());
412
                if (pro != null) {
413
                    return pro;
414
                }
415
            }
416
        }
417
        return super.getDynValue(name);
418
    }
419

    
420
    @Override
421
    public void resourceChanged(ResourceProvider resource) {
422
        this.getStoreServices().notifyChange(
423
                DataStoreNotification.RESOURCE_CHANGED,
424
                resource);
425
    }
426

    
427
    @Override
428
    public Object getSourceId() {
429
        return this.getCSVParameters().getFile();
430
    }
431

    
432
    @Override
433
    public String getName() {
434
        String name = this.getCSVParameters().getFile().getName();
435
        return FilenameUtils.getBaseName(name);
436
    }
437

    
438
    @Override
439
    public String getFullName() {
440
        return this.getCSVParameters().getFile().getAbsolutePath();
441
    }
442

    
443
    @Override
444
    public ResourceProvider getResource() {
445
        return resource;
446
    }
447

    
448
    private boolean isEmpty(String s) {
449
        if (s == null) {
450
            return true;
451
        }
452
        return s.trim().length() == 0;
453
    }
454

    
455
    private void init(CSVStoreParameters parameters, DataStoreProviderServices storeServices) {
456
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
457
    }
458
    private class FieldTypeParser {
459

    
460
        public String name = null;
461
        public int type = DataTypes.STRING;
462
        public int size = 0;
463
        public int geomType = Geometry.TYPES.GEOMETRY;
464
        public int geomSubtype = Geometry.SUBTYPES.GEOM2D;
465
        public Map<String,String> tags = new HashMap<>();
466
        public Map<String,String> assignments = new HashMap<>();
467

    
468
        private String typename = "string";
469

    
470
        FieldTypeParser() {
471
        }
472

    
473
        public void clear() {
474
            this.name = null;
475
            this.type = DataTypes.STRING;
476
            this.size = 0;
477
            this.tags = new HashMap<>();
478
            this.assignments = new HashMap<>();
479
        }
480

    
481
        public void copyFrom(FieldTypeParser other) {
482
            this.name = other.name;
483
            this.type = other.type;
484
            this.size = other.size;
485
            this.tags = new HashMap<>();
486
            this.tags.putAll(other.tags);
487
            this.assignments = new HashMap<>();
488
            this.assignments.putAll(other.assignments);
489
        }
490

    
491
        private int getType(String value) {
492
            DataTypesManager dataTypesManager = ToolsLocator.getDataTypesManager();
493
            return dataTypesManager.getType(typename);
494
        }
495

    
496
        private String[] split(String value, String separators) {
497
            int firstSeparatorPosition = 1000000;
498
            Character sep = null;
499
            for (char ch : separators.toCharArray()) {
500
                int pos = value.indexOf(ch);
501
                if( pos>0 && pos<firstSeparatorPosition ) {
502
                    sep = ch;
503
                    firstSeparatorPosition = pos;
504
                }
505
            }
506
            if( sep == null ) {
507
                return new String[] { value };
508
            }
509
            return value.split("["+sep+"]");
510
        }
511

    
512
        @SuppressWarnings("UseSpecificCatch")
513
        public boolean parse(String value) {
514
            String[] args;
515
            if ( value.contains("__") ) {
516
                args = value.split("__");
517
            } else {
518
                args = split(value, ":/#@!;-");
519
                if( args.length == 1 ) {
520
                    this.name = value;
521
                    return true;
522
                }
523
            }                        
524
            int n = 0;
525
            this.name = StringUtils.trim(args[n++]);
526
            if( n >= args.length ) {
527
                return true;
528
            }
529
            this.typename = StringUtils.trim(args[n++]);
530
            this.type = this.getType(this.typename);
531
            if ( this.type == DataTypes.INVALID ) {
532
                this.geomType = GeometryUtils.getGeometryType(this.typename);
533
                if( this.geomType==Geometry.TYPES.UNKNOWN )  {
534
                    this.type = DataTypes.STRING;
535
                    LOGGER.info("Type '" + this.typename + "' not valid for attribute '" + value + "' in '"+getProviderName()+"' file '" + getFullFileName() + "'.");
536
                } else {
537
                    this.typename = "GEOMETRY";
538
                    this.type = DataTypes.GEOMETRY;
539
                }
540
            }
541
            this.size = DALLocator.getManager().getDefaultSize(this.type);
542

    
543
            while (n < args.length) {
544
                String option = StringUtils.trim(args[n++].toLowerCase());
545
                switch (option) {
546
                    case "size":
547
                        try {
548
                            this.size = Integer.parseInt(args[n++]);
549
                        } catch (Exception ex) {
550
                            LOGGER.warn("Ignore incorrect field size for field " + value + " in '"+getProviderName()+"' file '" + getFullFileName() + "'.", ex);
551
                        }
552
                        break;
553
                    case "tag": {
554
                            String x = StringUtils.trim(args[n++]);
555
                            int pos = x.indexOf("=");
556
                            if( pos < 0 ) {
557
                                this.tags.put(x, null);
558
                            } else {
559
                                this.tags.put( 
560
                                        StringUtils.trim(StringUtils.substring(x, 0, pos)),
561
                                        StringUtils.trim(StringUtils.substring(x, pos+1))
562
                                );
563
                            }
564
                            break;
565
                        }
566
                    case "set": {
567
                            String x = StringUtils.trim(args[n++]);
568
                            int pos = x.indexOf("=");
569
                            if( pos < 0 ) {
570
                                this.assignments.put(x, null);
571
                            } else {
572
                                this.assignments.put( 
573
                                        StringUtils.trim(StringUtils.substring(x, 0, pos)),
574
                                        StringUtils.trim(StringUtils.substring(x, pos+1))
575
                                );
576
                            }
577
                            break;
578
                        }
579
                    default:
580
                        LOGGER.warn("Illegal argumente '"+option+"' for field '"+this.name+"' in '"+getProviderName()+"' file '" + getFullFileName() + "' ("+value+").");
581
                }
582
            }
583
            return true;
584
        }
585

    
586
    }
587

    
588
    private EditableFeatureType getFeatureType(String headers[], int automaticTypes[]) {
589
        EditableFeatureType fType = getStoreServices().createFeatureType(this.getName());
590
        fType.setHasOID(true);
591

    
592
        FieldTypeParser[] fieldTypes = new FieldTypeParser[headers.length];
593
        //
594
        // Calculamos cuales pueden ser los tipos de datos
595
        //
596
        for (int i = 0; i < fieldTypes.length; i++) {
597
            fieldTypes[i] = new FieldTypeParser();
598
        }
599

    
600
        // Asuminos los tipos pasados por parametro, que se supone
601
        // son los detectados automaticamente.
602
        if (automaticTypes != null) {
603
            for (int i = 0; i < fieldTypes.length && i < automaticTypes.length; i++) {
604
                fieldTypes[i].type = automaticTypes[i];
605
            }
606
        }
607
        // Luego probamos con lo que diga las cabezeras del CVS, sobreescribiendo
608
        // los tipos anteriores en caso de definirse en la cabezara.
609
        for (int i = 0; i < fieldTypes.length; i++) {
610
            if (!fieldTypes[i].parse(headers[i])) {
611
                continue;
612
            }
613

    
614
        }
615

    
616
        // Y por ultimo hacemos caso a lo que se haya especificado en los parametros
617
        // de apertura del CSV, teniendo esto prioridad sobre todo.
618
        String param_types_def = CSVStoreParameters.getRawFieldTypes(this.getParameters());
619
        if (StringUtils.isNotBlank(param_types_def)) {
620
            String sep = CSVStoreParameters.getDelimiter(param_types_def);
621
            if (StringUtils.isNotBlank(sep)) {
622
                String[] param_types = param_types_def.split(sep);
623
                FieldTypeParser parser = new FieldTypeParser();
624
                for (String param_type : param_types) {
625
                    parser.clear();
626
                    parser.parse(param_type);
627
                    for (FieldTypeParser fieldType : fieldTypes) {
628
                        if (StringUtils.equalsIgnoreCase(fieldType.name, parser.name)) {
629
                            fieldType.copyFrom(parser);
630
                            break;
631
                        }
632
                    }
633
                }
634
            }
635
        }
636
        //
637
        // Una vez ya sabemos los tipos de datos rellenamos el feature-type
638
        //
639
        for (FieldTypeParser fieldType : fieldTypes) {
640
            EditableFeatureAttributeDescriptor fad = fType.add(fieldType.name, fieldType.type);
641
            fad.setSize(fieldType.size);
642
            if (fieldType.type == DataTypes.GEOMETRY ) {
643
                fad.setGeometryType(fieldType.geomType, fieldType.geomSubtype);
644
                if( fType.getDefaultGeometryAttributeName() == null ) {
645
                    fType.setDefaultGeometryAttributeName(fieldType.name);
646
                }
647
            }
648
            for (Map.Entry<String, String> entry : fieldType.assignments.entrySet()) {
649
                try {
650
                    switch(entry.getKey().toLowerCase()) {
651
                        case "expression":
652
                            // Los campos calculados los procesamos en una segunda
653
                            // pasada, cuando ya estan definidos el resto de los campos
654
                            // ya que pueden requerir campos que aun no se han definido.
655
                            break;
656
                        default:
657
                            fad.set(entry.getKey(), entry.getValue());
658
                    }
659
                } catch (Exception ex) {
660
                    LOGGER.warn("Can't set property '"+entry.getKey()+"' of '"+fad.getName()+"'.", ex);
661
                }
662
            }
663
            Tags tags = fad.getTags();
664
            for (Map.Entry<String, String> entry : fieldType.tags.entrySet()) {
665
                tags.set(entry.getKey(), entry.getValue());
666
            }
667
        }
668
        // Processamos ahora los campos calculados
669
        for (FieldTypeParser fieldType : fieldTypes) {
670
            EditableFeatureAttributeDescriptor fad = fType.getEditableAttributeDescriptor(fieldType.name);
671
            for (Map.Entry<String, String> entry : fieldType.assignments.entrySet()) {
672
                try {
673
                    switch(entry.getKey().toLowerCase()) {
674
                        case "expression":
675
                            fad.set(entry.getKey(), entry.getValue());
676
                            break;
677
                    }
678
                } catch (Exception ex) {
679
                    LOGGER.warn("Can't set property '"+entry.getKey()+"' in '"+fad.getName()+"' of '"+getFullFileName()+"'.", ex);
680
                }
681
            }
682
        }
683
        String[] pointDimensionNames = CSVStoreParameters.getPointDimensionNames(this.getParameters());
684
        if ( pointDimensionNames != null ) {
685
            PointAttributeEmulator emulator = new PointAttributeEmulator(pointDimensionNames);
686
            EditableFeatureAttributeDescriptor attr = fType.add("the_geom", DataTypes.GEOMETRY, emulator);
687
            GeometryManager geommgr = GeometryLocator.getGeometryManager();
688
            GeometryType gt;
689
            try {
690
                if ( emulator.fieldNames != null && emulator.fieldNames.length <= 2 ) {
691
                        gt = geommgr.getGeometryType(Geometry.TYPES.GEOMETRY, Geometry.SUBTYPES.GEOM2D);
692
                } else {
693
                        gt = geommgr.getGeometryType(Geometry.TYPES.GEOMETRY, Geometry.SUBTYPES.GEOM3D);
694
                }
695
                attr.setGeometryType(gt);
696
            } catch (Exception e) {
697
                LOGGER.warn("Can't set geometry type for the calculated field in '"+getProviderName()+"' file '" + getFullFileName() + "'.", e);
698
            }
699
        }        
700
        
701
        String geometry_column = CSVStoreParameters.getGeometryColumn(this.getParameters());
702
        if (!StringUtils.isEmpty(geometry_column)) {
703
            EditableFeatureAttributeDescriptor attr = (EditableFeatureAttributeDescriptor) fType.get(geometry_column);
704
            if (attr != null && attr.getType() != DataTypes.GEOMETRY) {
705
                attr.setDataType(DataTypes.GEOMETRY);
706
                GeometryManager geommgr = GeometryLocator.getGeometryManager();
707
                GeometryType gt;
708
                try {
709
                    gt = geommgr.getGeometryType(Geometry.TYPES.GEOMETRY, Geometry.SUBTYPES.UNKNOWN);
710
                    attr.setGeometryType(gt);
711
                } catch (Exception e) {
712
                    LOGGER.warn("Can't set geometry type for the calculated field in CSV file '" + getFullFileName() + "'.", e);
713
                }
714
                fType.setDefaultGeometryAttributeName(geometry_column);
715
            }
716
        }
717
        return fType;
718
    }
719

    
720
    static class PointAttributeEmulator implements FeatureAttributeEmulator {
721

    
722
        private static final Logger logger = LoggerFactory.getLogger(ToPointEvaluaror.class);
723

    
724
        private static final int XNAME = 0;
725
        private static final int YNAME = 1;
726
        private static final int ZNAME = 2;
727

    
728
        private final GeometryManager geommgr;
729
        private final String[] fieldNames;
730
        private final Coercion toDouble;
731
        private final DataType dataType;
732
        private int errorcount = 0;
733

    
734
        public PointAttributeEmulator(String[] pointDimensionNames) {
735
            if (pointDimensionNames.length > 2) {
736
                this.fieldNames = new String[3];
737
                this.fieldNames[ZNAME] = pointDimensionNames[2];
738
            } else {
739
                this.fieldNames = new String[2];
740
            }
741
            this.fieldNames[XNAME] = pointDimensionNames[0];
742
            this.fieldNames[YNAME] = pointDimensionNames[1];
743
            this.geommgr = GeometryLocator.getGeometryManager();
744
            DataTypesManager datatypeManager = ToolsLocator.getDataTypesManager();
745

    
746
            this.toDouble = datatypeManager.getCoercion(DataTypes.DOUBLE);
747
            this.dataType = datatypeManager.get(DataTypes.GEOMETRY);
748
        }
749

    
750
        @Override
751
        public Object get(Feature feature) {
752
            try {
753
                Object valueX = feature.get(this.fieldNames[XNAME]);
754
                valueX = toDouble.coerce(valueX);
755
                if (valueX == null) {
756
                    return null;
757
                }
758
                Object valueY = feature.get(this.fieldNames[YNAME]);
759
                valueY = toDouble.coerce(valueY);
760
                if (valueY == null) {
761
                    return null;
762
                }
763
                Object valueZ = null;
764
                if (this.fieldNames.length > 2) {
765
                    valueZ = toDouble.coerce(feature.get(this.fieldNames[ZNAME]));
766
                    if (valueZ == null) {
767
                        return null;
768
                    }
769
                }
770

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

    
788
        public void set(EditableFeature feature, Object value) {
789
            if (value == null) {
790
                return;
791
            }
792
            Point point = null;
793
            if (value instanceof MultiPoint) {
794
                point = (Point) ((MultiPoint) value).getPrimitiveAt(0);
795
            } else {
796
                point = (Point) value;
797
            }
798
            feature.set(this.fieldNames[XNAME], point.getX());
799
            feature.set(this.fieldNames[YNAME], point.getY());
800
            if (this.fieldNames.length > 2) {
801
                feature.set(this.fieldNames[ZNAME], point.getCoordinateAt(2));
802
            }
803
        }
804

    
805
        @Override
806
        public boolean allowSetting() {
807
            return true;
808
        }
809

    
810
        @Override
811
        public String[] getRequiredFieldNames() {
812
            return this.fieldNames;
813
        }
814

    
815
    }
816

    
817
    static class ToPointEvaluaror extends AbstractEvaluator {
818

    
819
        private static final Logger logger = LoggerFactory.getLogger(ToPointEvaluaror.class);
820

    
821
        private GeometryManager geommgr = null;
822
        private String xname = null;
823
        private String yname = null;
824
        private String zname = null;
825
        private Coercion toDouble;
826
        private int errorcount = 0;
827

    
828
        ToPointEvaluaror(String[] pointDimensionNames) {
829
            this.xname = pointDimensionNames[0];
830
            this.yname = pointDimensionNames[1];
831
            if (pointDimensionNames.length > 2) {
832
                this.zname = pointDimensionNames[2];
833
            }
834
            this.geommgr = GeometryLocator.getGeometryManager();
835
            this.toDouble = ToolsLocator.getDataTypesManager().getCoercion(DataTypes.DOUBLE);
836
        }
837

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

    
858
        @Override
859
        public String getName() {
860
            return "ToPointEvaluaror";
861
        }
862

    
863
    }
864

    
865
    private SimpleReader getSimpleReader(InputStreamReader in) {
866
        SimpleReader reader;
867
        if (CSVStoreParameters.getRawFieldsDefinition(getCSVParameters()) != null) {
868
            reader = new FixedLenReader(in, getCSVParameters());
869
        } else {
870
            reader = new CSVReader(in, getCSVParameters());
871
        }
872
        return reader;
873
    }
874

    
875
    private String getFixedHeader(int column) {
876
        char[] header = new char[3];
877

    
878
        String s = String.format("%03d", column);
879
        header[0] = (char) (s.charAt(0) + 17);
880
        header[1] = (char) (s.charAt(1) + 17);
881
        header[2] = (char) (s.charAt(2) + 17);
882
        return String.valueOf(header);
883
    }
884

    
885
    private String[] getFixedHeaders(int count) {
886
        String[] headers = new String[count];
887
        for (int i = 0; i < headers.length; i++) {
888
            headers[i] = getFixedHeader(i);
889
        }
890
        return headers;
891
    }
892

    
893
    private InputStreamReader openFile(File f, String charsetName) throws FileNotFoundException {
894
        Charset charset = Charset.defaultCharset();
895
        FileInputStream fis = new FileInputStream(f);
896
        if (!StringUtils.isEmpty(charsetName)) {
897
            if (Charset.isSupported(charsetName)) {
898
                try {
899
                    charset = Charset.forName(charsetName);
900
                } catch (Throwable th) {
901
                    LOGGER.warn("Can't use charset '" + charsetName + "' for read csv '" + this.getFullFileName() + "'.", th);
902
                }
903
            } else {
904
                LOGGER.warn("charset '" + charsetName + "' not supported for read csv '" + this.getFullFileName() + "'.");
905
            }
906
        }
907
        InputStreamReader isr = new InputStreamReader(fis, charset);
908
        return isr;
909
    }
910

    
911
    private void loadFeatures() {
912
        InputStreamReader in = null;
913
        SimpleReader reader = null;
914
        try {
915
            String headers[] = null;
916
            FeatureStoreProviderServices store = this.getStoreServices();
917

    
918
            boolean ignore_errors = CSVStoreParameters.getIgnoreErrors(getCSVParameters());
919

    
920
            in = openFile(
921
                    this.getCSVParameters().getFile(),
922
                    CSVStoreParameters.getCharset(this.getCSVParameters())
923
            );
924

    
925
            reader = getSimpleReader(in);
926

    
927
            headers = CSVStoreParameters.getHeaders(getCSVParameters());
928
            if (headers == null) {
929
                if (CSVStoreParameters.isFirstLineHeader(getCSVParameters())) {
930
                    headers = reader.getHeader();
931
                    if (headers == null) {
932
                        if (CSVStoreParameters.getIgnoreErrors(getCSVParameters())) {
933
                            headers = getFixedHeaders(reader.getColumnsCount());
934
                        } else {
935
                            String msg = "Can't retrieve header from csv file '"
936
                                    + this.getCSVParameters().getFile()
937
                                            .getAbsolutePath()
938
                                    + "' and not specified in the parameters.";
939
                            LOGGER.warn(msg);
940
                            throw new RuntimeException(msg);
941
                        }
942
                    }
943
                } else {
944
                    headers = getFixedHeaders(reader.getColumnsCount());
945
                }
946
            } else {
947
                if (CSVStoreParameters.isFirstLineHeader(getCSVParameters())) {
948
                    reader.getHeader(); // Skip and ignore the header of file
949
                }
950
            }
951

    
952
            int[] detectedTypes = automaticDetectionOfTypes(headers);
953
            if (detectedTypes != null && detectedTypes.length > headers.length) {
954
                // Se han detectado mas columnas que las que hay en la cabezera,
955
                // a?adimos mas columnas a la cabezera.
956
                String[] headers2 = new String[detectedTypes.length];
957
                for (int i = 0; i < headers2.length; i++) {
958
                    if (i < headers.length) {
959
                        headers2[i] = headers[i];
960
                    } else {
961
                        headers2[i] = getFixedHeader(i);
962
                    }
963
                }
964
                headers = headers2;
965
            }
966
            for (int i = 0; i < headers.length; i++) {
967
                if (StringUtils.isEmpty(headers[i])) {
968
                    headers[i] = getFixedHeader(i);
969
                }
970
            }
971
            // Initialize the feature types
972
            EditableFeatureType edftype = this.getFeatureType(headers, detectedTypes);
973
            FeatureType ftype = edftype.getNotEditableCopy();
974
            List<FeatureType> ftypes = new ArrayList<>();
975
            ftypes.add(ftype);
976
            store.setFeatureTypes(ftypes, ftype);
977

    
978
            Coercion coercion[] = new Coercion[ftype.size()];
979
            int sizes[] = new int[ftype.size()];
980
            for (int i = 0; i < ftype.size(); i++) {
981
                sizes[i] = -1;
982
                FeatureAttributeDescriptor ad = ftype.getAttributeDescriptor(i);
983
                coercion[i] = ad.getDataType().getCoercion();
984
                switch (ad.getDataType().getType()) {
985
                    case DataTypes.INT:
986
                        sizes[i] = 10;
987
                        break;
988
                    case DataTypes.LONG:
989
                        sizes[i] = 20;
990
                        break;
991
                    case DataTypes.STRING:
992
                        if (ad.getSize() == 0) {
993
                            // Es un string y no tiene un size asignado.
994
                            // Lo ponemos a cero para calcularlo.
995
                            sizes[i] = 0;
996
                        }
997
                        break;
998
                    case DataTypes.URL:
999
                    case DataTypes.URI:
1000
                    case DataTypes.FILE:
1001
                        sizes[i] = 0;
1002
                }
1003
            }
1004
            if (ftype.getDefaultGeometryAttributeName() != null) {
1005
                this.need_calculate_envelope = true;
1006
            }
1007

    
1008
            Locale locale = CSVStoreParameters.getLocale(getCSVParameters());
1009
            taskStatus.message("_loading");
1010
            int count = 0;
1011

    
1012
            int count_errors = 0;
1013

    
1014
            List<String> row = reader.read();
1015

    
1016
            int skipLines = CSVStoreParameters.getSkipLines(getCSVParameters());
1017
            if (skipLines > 0) {
1018
                row = reader.skip(skipLines);
1019
            }
1020
            int limit = CSVStoreParameters.getLimit(getCSVParameters());
1021
            while (row != null) {
1022
                taskStatus.setCurValue(++count);
1023
                FeatureProvider feature = this.createFeatureProvider(ftype);
1024
                for (int i = 0; i < row.size(); i++) {
1025
                    Object rawvalue = row.get(i);
1026
                    try {
1027
                        Object value = null;
1028
                        if (locale != null && coercion[i] instanceof CoercionWithLocale) {
1029
                            value = ((CoercionWithLocale) (coercion[i])).coerce(rawvalue, locale);
1030
                        } else {
1031
                            value = coercion[i].coerce(rawvalue);
1032
                        }
1033
                        feature.set(i, value);
1034
                        if (sizes[i] >= 0
1035
                                && (value instanceof String || value instanceof URL
1036
                                || value instanceof URI || value instanceof File)) {
1037
                            int x = value.toString().length();
1038
                            if (sizes[i] < x) {
1039
                                sizes[i] = x;
1040
                            }
1041
                        }
1042
                    } catch (Exception ex) {
1043
                        if (!ignore_errors) {
1044
                            throw ex;
1045
                        }
1046
                        if (count_errors++ < 10) {
1047
                            LOGGER.warn("Can't load value of attribute " + i + " in row " + count + ".", ex);
1048
                        }
1049
                        if (count_errors == 10) {
1050
                            LOGGER.info("Too many errors, suppress messages.");
1051
                        }
1052
                    }
1053
                }
1054
                this.addFeatureProvider(feature);
1055
                if (limit > 0) {
1056
                    if (limit < this.data.size()) {
1057
                        break;
1058
                    }
1059
                }
1060
                row = reader.read();
1061
            }
1062
            for (int i = 0; i < ftype.size(); i++) {
1063
                if (sizes[i] > 0) {
1064
                    EditableFeatureAttributeDescriptor efad = ((EditableFeatureAttributeDescriptor) edftype.getAttributeDescriptor(i));
1065
                    efad.setSize(sizes[i]);
1066
                }
1067
            }
1068
            // Volvemos a asignar al store el featuretype, ya que puede
1069
            // haber cambiado.
1070
            ftype = edftype.getNotEditableCopy();
1071
            ftypes = new ArrayList<>();
1072
            ftypes.add(ftype);
1073
            store.setFeatureTypes(ftypes, ftype);
1074

    
1075
            taskStatus.terminate();
1076
        } catch (Exception ex) {
1077
            int lineno = 0;
1078
            if (reader != null) {
1079
                lineno = reader.getLine();
1080
            }
1081
            throw new RuntimeException("Problems reading file '" + getFullFileName() + "' near line " + lineno + ".", ex);
1082

    
1083
        } finally {
1084
            if (reader != null) {
1085
                try {
1086
                    reader.close();
1087
                } catch (Exception ex) {
1088
                    // Do nothing
1089
                }
1090
                reader = null;
1091
            }
1092
            if (in != null) {
1093
                try {
1094
                    in.close();
1095
                } catch (Exception ex) {
1096
                    // Do nothing
1097
                }
1098
                in = null;
1099
            }
1100
        }
1101
    }
1102

    
1103
    private int[] automaticDetectionOfTypes(String[] headers) throws IOException {
1104
        boolean automatic_types_detection = CSVStoreParameters.getAutomaticTypesDetection(getCSVParameters());
1105
        if (!automatic_types_detection) {
1106
            return null;
1107
        }
1108
        int[] types = null;
1109

    
1110
        FileReader in = null;
1111
        SimpleReader reader = null;
1112

    
1113
        try {
1114
            in = new FileReader(this.getCSVParameters().getFile());
1115
            reader = getSimpleReader(in);
1116
            AutomaticDetectionOfTypes x = new AutomaticDetectionOfTypes(
1117
                    this.getFullFileName()
1118
            );
1119
            types = x.detect(
1120
                    headers.length,
1121
                    reader,
1122
                    CSVStoreParameters.isFirstLineHeader(getCSVParameters()),
1123
                    CSVStoreParameters.getLocale(getCSVParameters())
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
            IOUtils.closeQuietly(reader);
1134
            IOUtils.closeQuietly(in);
1135
        }
1136
        return types;
1137
    }
1138

    
1139
    private boolean isValidLong(String s) {
1140
        if (s == null) {
1141
            return true;
1142
        }
1143
        s = s.trim().toLowerCase();
1144
        if (s.isEmpty()) {
1145
            return true;
1146
        }
1147
        try {
1148
            if (s.startsWith("0x")) {
1149
                Long.valueOf(s.substring(2), 16);
1150
            } else {
1151
                Long.valueOf(s);
1152
            }
1153
            return true;
1154
        } catch (Exception ex) {
1155
            return false;
1156
        }
1157
    }
1158

    
1159
    private boolean isValidInteger(String s) {
1160
        if (s == null) {
1161
            return true;
1162
        }
1163
        s = s.trim().toLowerCase();
1164
        if (s.isEmpty()) {
1165
            return true;
1166
        }
1167
        try {
1168
            if (s.startsWith("0x")) {
1169
                Integer.valueOf(s.substring(2), 16);
1170
            } else {
1171
                Integer.valueOf(s);
1172
            }
1173
            return true;
1174
        } catch (Exception ex) {
1175
            return false;
1176
        }
1177
    }
1178

    
1179
}