Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.fmap.dal / org.gvsig.fmap.dal.impl / src / main / java / org / gvsig / fmap / dal / feature / impl / DefaultFeatureStore.java @ 44023

History | View | Annotate | Download (96.8 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

    
25
package org.gvsig.fmap.dal.feature.impl;
26

    
27
import java.io.File;
28
import org.gvsig.fmap.dal.feature.impl.editing.memory.SpatialManager;
29
import org.gvsig.fmap.dal.feature.impl.editing.memory.FeatureTypeManager;
30
import org.gvsig.fmap.dal.feature.impl.editing.memory.FeatureManager;
31
import org.gvsig.fmap.dal.feature.spi.SQLBuilderBase;
32

    
33
import java.util.ArrayList;
34
import java.util.Collection;
35
import java.util.Collections;
36
import java.util.HashMap;
37
import java.util.HashSet;
38
import java.util.Iterator;
39
import java.util.List;
40
import java.util.Map;
41
import java.util.Map.Entry;
42
import java.util.Set;
43
import java.util.logging.Level;
44
import org.apache.commons.collections4.ListUtils;
45

    
46
import org.apache.commons.io.FilenameUtils;
47
import org.apache.commons.lang3.StringUtils;
48
import org.cresques.cts.IProjection;
49
import org.gvsig.expressionevaluator.Expression;
50

    
51
import org.gvsig.fmap.dal.DALLocator;
52
import org.gvsig.fmap.dal.DataManager;
53
import org.gvsig.fmap.dal.DataQuery;
54
import org.gvsig.fmap.dal.DataServerExplorer;
55
import org.gvsig.fmap.dal.DataSet;
56
import org.gvsig.fmap.dal.DataStore;
57
import org.gvsig.fmap.dal.DataStoreNotification;
58
import org.gvsig.fmap.dal.DataStoreParameters;
59
import org.gvsig.fmap.dal.DataStoreProviderFactory;
60
import org.gvsig.fmap.dal.ExpressionBuilder;
61
import org.gvsig.fmap.dal.exception.CloneException;
62
import org.gvsig.fmap.dal.exception.CloseException;
63
import org.gvsig.fmap.dal.exception.CreateException;
64
import org.gvsig.fmap.dal.exception.DataException;
65
import org.gvsig.fmap.dal.exception.InitializeException;
66
import org.gvsig.fmap.dal.exception.OpenException;
67
import org.gvsig.fmap.dal.exception.ReadException;
68
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
69
import org.gvsig.fmap.dal.exception.WriteException;
70
import org.gvsig.fmap.dal.feature.EditableFeature;
71
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
72
import org.gvsig.fmap.dal.feature.EditableFeatureType;
73
import org.gvsig.fmap.dal.feature.Feature;
74
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
75
import org.gvsig.fmap.dal.feature.FeatureAttributeEmulator;
76
import org.gvsig.fmap.dal.feature.FeatureCache;
77
import org.gvsig.fmap.dal.feature.FeatureIndex;
78
import org.gvsig.fmap.dal.feature.FeatureIndexes;
79
import org.gvsig.fmap.dal.feature.FeatureLocks;
80
import org.gvsig.fmap.dal.feature.FeatureQuery;
81
import org.gvsig.fmap.dal.feature.FeatureReference;
82
import org.gvsig.fmap.dal.feature.FeatureReferenceSelection;
83
import org.gvsig.fmap.dal.feature.FeatureRules;
84
import org.gvsig.fmap.dal.feature.FeatureSelection;
85
import org.gvsig.fmap.dal.feature.FeatureSet;
86
import org.gvsig.fmap.dal.feature.FeatureStore;
87
import org.gvsig.fmap.dal.feature.FeatureStoreNotification;
88
import org.gvsig.fmap.dal.feature.FeatureStoreProviderFactory;
89
import org.gvsig.fmap.dal.feature.FeatureStoreTransforms;
90
import org.gvsig.fmap.dal.feature.FeatureType;
91
import org.gvsig.fmap.dal.feature.NewFeatureStoreParameters;
92
import org.gvsig.fmap.dal.feature.FeatureStoreTimeSupport;
93
import org.gvsig.fmap.dal.feature.FeatureStoreTransform;
94
import org.gvsig.fmap.dal.feature.exception.AlreadyEditingException;
95
import org.gvsig.fmap.dal.feature.exception.ConcurrentDataModificationException;
96
import org.gvsig.fmap.dal.feature.exception.CreateFeatureException;
97
import org.gvsig.fmap.dal.feature.exception.DataExportException;
98
import org.gvsig.fmap.dal.feature.exception.FeatureIndexException;
99
import org.gvsig.fmap.dal.feature.exception.FinishEditingException;
100
import org.gvsig.fmap.dal.feature.exception.GetFeatureTypeException;
101
import org.gvsig.fmap.dal.feature.exception.IllegalFeatureException;
102
import org.gvsig.fmap.dal.feature.exception.IllegalFeatureTypeException;
103
import org.gvsig.fmap.dal.feature.exception.NeedEditingModeException;
104
import org.gvsig.fmap.dal.feature.exception.NoNewFeatureInsertException;
105
import org.gvsig.fmap.dal.feature.exception.NullFeatureTypeException;
106
import org.gvsig.fmap.dal.feature.exception.PerformEditingException;
107
import org.gvsig.fmap.dal.feature.exception.PersistenceCantFindFeatureTypeException;
108
import org.gvsig.fmap.dal.feature.exception.PersistenceStoreAlreadyLoadedException;
109
import org.gvsig.fmap.dal.feature.exception.SelectionNotAllowedException;
110
import org.gvsig.fmap.dal.feature.exception.StoreCancelEditingException;
111
import org.gvsig.fmap.dal.feature.exception.StoreDeleteEditableFeatureException;
112
import org.gvsig.fmap.dal.feature.exception.StoreDeleteFeatureException;
113
import org.gvsig.fmap.dal.feature.exception.StoreEditException;
114
import org.gvsig.fmap.dal.feature.exception.StoreInsertFeatureException;
115
import org.gvsig.fmap.dal.feature.exception.StoreUpdateFeatureException;
116
import org.gvsig.fmap.dal.feature.exception.StoreUpdateFeatureTypeException;
117
import org.gvsig.fmap.dal.feature.exception.ValidateFeaturesException;
118
import org.gvsig.fmap.dal.feature.exception.WriteNotAllowedException;
119
import org.gvsig.fmap.dal.feature.impl.featureset.DefaultFeatureSet;
120
import org.gvsig.fmap.dal.feature.impl.dynobjectutils.DynObjectFeatureFacade;
121
import org.gvsig.fmap.dal.feature.impl.undo.DefaultFeatureCommandsStack;
122
import org.gvsig.fmap.dal.feature.impl.undo.FeatureCommandsStack;
123
import org.gvsig.fmap.dal.feature.paging.FeaturePagingHelper;
124
import org.gvsig.fmap.dal.feature.spi.DefaultFeatureProvider;
125
import org.gvsig.fmap.dal.feature.spi.FeatureProvider;
126
import org.gvsig.fmap.dal.feature.spi.FeatureReferenceProviderServices;
127
import org.gvsig.fmap.dal.feature.spi.FeatureStoreProvider;
128
import org.gvsig.fmap.dal.feature.spi.FeatureStoreProviderServices;
129
import org.gvsig.fmap.dal.feature.spi.FeatureStoreProvider_v2;
130
import org.gvsig.fmap.dal.feature.spi.cache.FeatureCacheProvider;
131
import org.gvsig.fmap.dal.feature.spi.index.FeatureIndexProviderServices;
132
import org.gvsig.fmap.dal.impl.DefaultDataManager;
133
import org.gvsig.fmap.dal.resource.Resource;
134
import org.gvsig.fmap.dal.spi.DataStoreInitializer2;
135
import org.gvsig.fmap.dal.spi.DataStoreProvider;
136
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
137
import org.gvsig.fmap.geom.SpatialIndex;
138
import org.gvsig.fmap.geom.primitive.Envelope;
139
import org.gvsig.metadata.MetadataLocator;
140
import org.gvsig.metadata.MetadataManager;
141
import org.gvsig.metadata.exceptions.MetadataException;
142
import org.gvsig.timesupport.Interval;
143
import org.gvsig.tools.ToolsLocator;
144
import org.gvsig.tools.dispose.DisposableIterator;
145
import org.gvsig.tools.dispose.DisposeUtils;
146
import org.gvsig.tools.dispose.impl.AbstractDisposable;
147
import org.gvsig.tools.dynobject.DelegatedDynObject;
148
import org.gvsig.tools.dynobject.DynClass;
149
import org.gvsig.tools.dynobject.DynObject;
150
import org.gvsig.tools.dynobject.DynObjectManager;
151
import org.gvsig.tools.dynobject.DynObject_v2;
152
import org.gvsig.tools.dynobject.DynStruct;
153
import org.gvsig.tools.dynobject.exception.DynFieldNotFoundException;
154
import org.gvsig.tools.dynobject.exception.DynMethodException;
155
import org.gvsig.tools.exception.BaseException;
156
import org.gvsig.tools.exception.NotYetImplemented;
157
import org.gvsig.tools.identitymanagement.SimpleIdentityManager;
158
import org.gvsig.tools.observer.Observable;
159
import org.gvsig.tools.observer.Observer;
160
import org.gvsig.tools.observer.impl.DelegateWeakReferencingObservable;
161
import org.gvsig.tools.persistence.PersistenceManager;
162
import org.gvsig.tools.persistence.Persistent;
163
import org.gvsig.tools.persistence.PersistentState;
164
import org.gvsig.tools.persistence.exception.PersistenceException;
165
import org.gvsig.tools.undo.RedoException;
166
import org.gvsig.tools.undo.UndoException;
167
import org.gvsig.tools.undo.command.Command;
168
import org.gvsig.tools.util.HasAFile;
169
import org.gvsig.tools.visitor.Visitor;
170

    
171
import org.slf4j.Logger;
172
import org.slf4j.LoggerFactory;
173

    
174
public class DefaultFeatureStore extends AbstractDisposable implements
175
    DataStoreInitializer2, FeatureStoreProviderServices, FeatureStore, Observer {
176

    
177
    private static final Logger LOG = LoggerFactory
178
        .getLogger(DefaultFeatureStore.class);
179

    
180
    private static final String PERSISTENCE_DEFINITION_NAME = "FeatureStore";
181

    
182
    private DataStoreParameters parameters = null;
183
    private FeatureSelection selection;
184
    private FeatureLocks locks;
185

    
186
    private DelegateWeakReferencingObservable delegateObservable =
187
        new DelegateWeakReferencingObservable(this);
188

    
189
    private FeatureCommandsStack commands;
190
    
191
    /*
192
    TODO: Sustituir estos tres manager por un EditingManager
193
    */
194
    private FeatureTypeManager featureTypeManager;
195
    private FeatureManager featureManager;
196
    private SpatialManager spatialManager;
197

    
198
    private FeatureType defaultFeatureType = null;
199
    private List featureTypes = new ArrayList();
200

    
201
    private int mode = MODE_QUERY;
202
    private long versionOfUpdate = 0;
203
    private boolean hasStrongChanges = true;
204
    private boolean hasInserts = true;
205

    
206
    private DefaultDataManager dataManager = null;
207

    
208
    private FeatureStoreProvider provider = null;
209

    
210
    private DefaultFeatureIndexes indexes;
211

    
212
    private DefaultFeatureStoreTransforms transforms;
213

    
214
    DelegatedDynObject metadata;
215

    
216
    private Set metadataChildren;
217

    
218
    private Long featureCount = null;
219

    
220
    private long temporalOid = 0;
221

    
222
    private FeatureCacheProvider cache;
223

    
224
    StateInformation state;
225

    
226
    FeatureStoreTimeSupport timeSupport;
227

    
228

    
229
    private class StateInformation extends HashMap<Object, Object> {
230

    
231
        private static final long serialVersionUID = 4109026189635185666L;
232

    
233
        private boolean broken;
234
        private Throwable breakingsCause;
235

    
236
        @SuppressWarnings("OverridableMethodCallInConstructor")
237
        public StateInformation() {
238
            this.clear();
239
        }
240

    
241
        @Override
242
        public void clear() {
243
            this.broken = false;
244
            this.breakingsCause = null;
245
            super.clear();
246
        }
247

    
248
        public boolean isBroken() {
249
            return this.broken;
250
        }
251

    
252
        public void broken() {
253
            this.broken = true;
254
        }
255

    
256
        public Throwable getBreakingsCause() {
257
            return this.breakingsCause;
258
        }
259

    
260
        public void setBreakingsCause(Throwable cause) {
261
            if( this.breakingsCause==null ) {
262
                this.breakingsCause = cause;
263
            }
264
            this.broken = true;
265
        }
266
    }
267

    
268

    
269

    
270
    /*
271
     * TODO:
272
     *
273
     * - Comprobar que solo se pueden a?adir reglas de validacion sobre un
274
     * EditableFeatureType. - Comprobar que solo se puede hacer un update con un
275
     * featureType al que se le han cambiado las reglas de validacion cuando
276
     * hasStrongChanges=false.
277
     */
278

    
279
    public DefaultFeatureStore() {
280
        this.state = new StateInformation();
281
    }
282

    
283
    @Override
284
    public void intialize(DataManager dataManager,
285
        DataStoreParameters parameters) throws InitializeException {
286

    
287
        DynObjectManager dynManager = ToolsLocator.getDynObjectManager();
288

    
289
        this.metadata = (DelegatedDynObject) dynManager.createDynObject(
290
            FeatureStore.METADATA_DEFINITION_NAME,
291
            MetadataManager.METADATA_NAMESPACE
292
        );
293

    
294
        this.dataManager = (DefaultDataManager) dataManager;
295

    
296
        this.parameters = parameters;
297
        this.transforms = new DefaultFeatureStoreTransforms(this);
298
        try {
299
            indexes = new DefaultFeatureIndexes(this);
300
        } catch (DataException e) {
301
            throw new InitializeException(e);
302
        }
303

    
304
    }
305

    
306
    @Override
307
    public void setProvider(org.gvsig.fmap.dal.DataStoreProvider provider) {
308
        this.provider = (FeatureStoreProvider) provider;
309
        this.delegate((DynObject) provider);
310
        this.metadataChildren = new HashSet();
311
        this.metadataChildren.add(provider);
312
        loadDALFile();
313
    }
314

    
315
    @Override
316
    public DataStoreParameters getParameters() {
317
        return parameters;
318
    }
319

    
320
    public int getMode() {
321
        return this.mode;
322
    }
323

    
324
    @Override
325
    public DataManager getManager() {
326
        return this.dataManager;
327
    }
328

    
329
    @Override
330
    public Iterator getChildren() {
331
        return this.provider.getChilds();
332
    }
333

    
334
    @Override
335
    public FeatureStoreProvider getProvider() {
336
        return this.provider;
337
    }
338

    
339
    public FeatureManager getFeatureManager() {
340
        return this.featureManager;
341
    }
342

    
343
    @Override
344
    public void setFeatureTypes(List types, FeatureType defaultType) {
345
        this.featureTypes = types;
346
        this.defaultFeatureType = defaultType;
347
    }
348

    
349
    public void open() throws OpenException {
350
        if (this.mode != MODE_QUERY) {
351
            // TODO: Se puede hacer un open estando en edicion ?
352
            try {
353
                throw new IllegalStateException();
354
            } catch(Exception ex) {
355
                LOG.warn("Opening a store in editing/append mode ("+this.getFullName()+").",ex);
356
            }
357
        }
358
        this.notifyChange(DataStoreNotification.BEFORE_OPEN);
359
        this.provider.open();
360
        this.notifyChange(DataStoreNotification.AFTER_OPEN);
361
    }
362

    
363
    @Override
364
    public void refresh() throws OpenException, InitializeException {
365
        if (this.mode != MODE_QUERY) {
366
            throw new IllegalStateException();
367
        }
368
        this.notifyChange(FeatureStoreNotification.BEFORE_REFRESH);
369
        if( state.isBroken() ) {
370
            this.load(state);
371
        } else {
372
            this.featureCount = null;
373
            this.provider.refresh();
374
        }
375
        this.notifyChange(FeatureStoreNotification.AFTER_REFRESH);
376
    }
377

    
378
    public void close() throws CloseException {
379
        if (this.mode != MODE_QUERY) {
380
            // TODO: Se puede hacer un close estando en edicion ?
381
            try {
382
                throw new IllegalStateException();
383
            } catch(Exception ex) {
384
                LOG.warn("Clossing a store in editing/append mode ("+this.getFullName()+").",ex);
385
            }
386
        }
387
        this.notifyChange(DataStoreNotification.BEFORE_CLOSE);
388
        this.featureCount = null;
389
        this.provider.close();
390
        this.notifyChange(DataStoreNotification.AFTER_CLOSE);
391
    }
392

    
393
    @Override
394
    protected void doDispose() throws BaseException {
395
        if (this.mode != MODE_QUERY) {
396
            // TODO: Se puede hacer un dispose estando en edicion ?
397
            try {
398
                throw new IllegalStateException();
399
            } catch(Exception ex) {
400
                LOG.warn("Dispossing a store in editing/append mode ("+this.getFullName()+").",ex);
401
            }
402
        }
403
        this.notifyChange(DataStoreNotification.BEFORE_DISPOSE);
404
        this.disposeIndexes();
405
        if( this.provider!=null ) {
406
            this.provider.dispose();
407
        }
408
        if (this.selection != null) {
409
            this.selection.dispose();
410
            this.selection = null;
411
        }
412
        this.commands = null;
413
        this.featureCount = null;
414
        if (this.locks != null) {
415
            // this.locks.dispose();
416
            this.locks = null;
417
        }
418

    
419
        if (this.featureTypeManager != null) {
420
            this.featureTypeManager.dispose();
421
            this.featureTypeManager = null;
422
        }
423

    
424
        this.featureManager = null;
425
        this.spatialManager = null;
426

    
427
        this.parameters = null;
428
        this.notifyChange(DataStoreNotification.AFTER_DISPOSE);
429
        if (delegateObservable != null) {
430
            this.delegateObservable.deleteObservers();
431
            this.delegateObservable = null;
432
        }
433
    }
434

    
435
    @Override
436
    public boolean allowWrite() {
437
        SimpleIdentityManager identityManager = ToolsLocator.getIdentityManager();
438
        if( ! identityManager.getCurrentIdentity().isAuthorized(DataManager.WRITE_STORE_AUTHORIZATION,this.getParameters(), this.getName()) ) {
439
            return false;
440
        }
441
        return this.provider.allowWrite();
442
    }
443

    
444
    @Override
445
    public boolean canWriteGeometry(int geometryType) throws DataException {
446
        return this.provider.canWriteGeometry(geometryType, 0);
447
    }
448

    
449
    @Override
450
    public DataServerExplorer getExplorer() throws ReadException,
451
        ValidateDataParametersException {
452
        if( this.state.isBroken() ) {
453
            try {
454
                return this.provider.getExplorer();
455
            } catch(Throwable th) {
456
                return null;
457
            }
458
        } else {
459
            return this.provider.getExplorer();
460
        }
461
    }
462

    
463
    /*
464
     * public Metadata getMetadata() throws MetadataNotFoundException {
465
     * // TODO:
466
     * // Si el provider devuelbe null habria que ver de construir aqui
467
     * // los metadatos basicos, como el Envelope y el SRS.
468
     *
469
     * // TODO: Estando en edicion el Envelope deberia de
470
     * // actualizarse usando el spatialManager
471
     * return this.provider.getMetadata();
472
     * }
473
     */
474

    
475
    @Override
476
    public Envelope getEnvelope() throws DataException {
477
        if (this.mode == MODE_FULLEDIT) {
478
                // Just in case another thread tries to write in the store
479
                synchronized (this) {
480
                        return this.spatialManager.getEnvelope();
481
                        }
482
        }
483
        if (hasDynValue(DataStore.METADATA_ENVELOPE)){
484
            return (Envelope)getDynValue(DataStore.METADATA_ENVELOPE);
485
        }
486
        return this.provider.getEnvelope();
487
    }
488

    
489
    /**
490
     * @throws org.gvsig.fmap.dal.exception.DataException
491
     * @deprecated use getDefaultFeatureType().getDefaultSRS()
492
     */
493
    @Override
494
    public IProjection getSRSDefaultGeometry() throws DataException {
495
        return this.getDefaultFeatureType().getDefaultSRS();
496
    }
497

    
498
    @Override
499
    public FeatureSelection createDefaultFeatureSelection()
500
        throws DataException {
501
        return new DefaultFeatureSelection(this);
502
    }
503

    
504
    @Override
505
    public FeatureProvider createDefaultFeatureProvider(FeatureType type)
506
        throws DataException {
507
        if (type.hasOID()) {
508
            return new DefaultFeatureProvider(type,
509
                this.provider.createNewOID());
510
        }
511
        return new DefaultFeatureProvider(type);
512
    }
513

    
514
    @Override
515
    public void saveToState(PersistentState state) throws PersistenceException {
516
        /*if (this.mode != FeatureStore.MODE_QUERY) {
517
            throw new PersistenceException(new IllegalStateException(
518
                this.getName()));
519
        }*/
520
        state.set("dataStoreName", this.getName());
521
        state.set("parameters", this.parameters);
522
        state.set("selection", this.selection);
523
        state.set("transforms", this.transforms);
524
        // TODO locks persistence
525
        // state.set("locks", this.locks);
526
        // TODO indexes persistence
527
        // state.set("indexes", this.indexes);
528
        Map evaluatedAttr = new HashMap(1);
529
        Iterator iterType = featureTypes.iterator();
530
        Iterator iterAttr;
531
        FeatureType type;
532
        DefaultFeatureAttributeDescriptor attr;
533
        List attrs;
534
        while (iterType.hasNext()) {
535
            type = (FeatureType) iterType.next();
536
            attrs = new ArrayList();
537
            iterAttr = type.iterator();
538
            while (iterAttr.hasNext()) {
539
                attr = (DefaultFeatureAttributeDescriptor) iterAttr.next();
540
                if ((attr.getEvaluator() != null)
541
                    && (attr.getEvaluator() instanceof Persistent)) {
542
                    attrs.add(attr);
543
                }
544
            }
545
            if (!attrs.isEmpty()) {
546
                evaluatedAttr.put(type.getId(), attrs);
547
            }
548

    
549
        }
550

    
551
        if (evaluatedAttr.isEmpty()) {
552
            evaluatedAttr = null;
553
        }
554

    
555
        state.set("evaluatedAttributes", evaluatedAttr);
556
        state.set("defaultFeatureTypeId", defaultFeatureType.getId());
557

    
558
    }
559

    
560
    @Override
561
    public void loadFromState(final PersistentState persistentState)
562
        throws PersistenceException {
563
        if (this.provider != null) {
564
            throw new PersistenceStoreAlreadyLoadedException(this.getName());
565
        }
566
        if (this.getManager() == null) {
567
            this.dataManager = (DefaultDataManager) DALLocator.getDataManager();
568
        }
569
        state.clear();
570
        try {
571
            state.put("parameters", persistentState.get("parameters"));
572
        } catch(Throwable th) {
573
            state.setBreakingsCause(th);
574
        }
575
        try {
576
            state.put("selection", persistentState.get("selection"));
577
        } catch(Throwable th) {
578
            state.setBreakingsCause(th);
579
        }
580
        try {
581
            state.put("transforms",  persistentState.get("transforms"));
582
        } catch(Throwable th) {
583
            state.setBreakingsCause(th);
584
        }
585
        try {
586
            state.put("evaluatedAttributes",  persistentState.get("evaluatedAttributes"));
587
        } catch(Throwable th) {
588
            state.setBreakingsCause(th);
589
        }
590
        try {
591
            state.put("defaultFeatureTypeId", persistentState.getString("defaultFeatureTypeId"));
592
        } catch(Throwable th) {
593
            state.setBreakingsCause(th);
594
        }
595
        load(state);
596
    }
597

    
598
    private void load(StateInformation state) {
599
        this.featureTypes = new ArrayList();
600
        this.defaultFeatureType = null;
601
        this.featureCount = null;
602

    
603
        DataStoreParameters params = (DataStoreParameters) state.get("parameters");
604
        try {
605
            intialize(dataManager, params);
606
        } catch(Throwable th) {
607
            state.setBreakingsCause(th);
608
        }
609

    
610
        try {
611
            DataStoreProvider prov = dataManager.createProvider(
612
                getStoreProviderServices(),
613
                params
614
            );
615
            setProvider(prov);
616
        } catch(Throwable th) {
617
            state.setBreakingsCause(th);
618
        }
619

    
620
        try {
621
            selection = (FeatureSelection) state.get("selection");
622
        } catch(Throwable th) {
623
            state.setBreakingsCause(th);
624
        }
625

    
626
        try {
627
            this.transforms = (DefaultFeatureStoreTransforms) state.get("transforms");
628
            this.transforms.setFeatureStore(this);
629
            for( FeatureStoreTransform transform : this.transforms ) {
630
                try {
631
                    transform.setUp();
632
                } catch(Throwable th) {
633
                    state.setBreakingsCause(th);
634
                }
635
            }
636
        } catch(Throwable th) {
637
            state.setBreakingsCause(th);
638
        }
639

    
640
        try {
641
            Map evaluatedAttributes = (Map) state.get("evaluatedAttributes");
642
            if ((evaluatedAttributes != null) && !evaluatedAttributes.isEmpty()) {
643
                    Iterator iterEntries = evaluatedAttributes.entrySet().iterator();
644
                    while (iterEntries.hasNext()) {
645
                            Entry entry = (Entry) iterEntries.next();
646
                            List attrs = (List) entry.getValue();
647
                            if (attrs.isEmpty()) {
648
                                    continue;
649
                            }
650
                            int fTypePos = -1;
651
                            DefaultFeatureType type = null;
652
                            for (int i = 0; i < featureTypes.size(); i++) {
653
                                    type = (DefaultFeatureType) featureTypes.get(i);
654
                                    if (type.getId().equals(entry.getKey())) {
655
                                            fTypePos = i;
656
                                            break;
657
                                    }
658
                            }
659
                            if (type == null) {
660
                                    throw new PersistenceCantFindFeatureTypeException(
661
                                            getName(), (String) entry.getKey());
662
                            }
663
                            DefaultEditableFeatureType eType = (DefaultEditableFeatureType) type.getEditable();
664
                            Iterator<FeatureAttributeDescriptor> iterAttr = attrs.iterator();
665
                            while (iterAttr.hasNext()) {
666
                                    FeatureAttributeDescriptor attr = iterAttr.next();
667
                                    eType.addLike(attr);
668
                            }
669
                            featureTypes.set(fTypePos, eType.getNotEditableCopy());
670

    
671
                    }
672

    
673
            }
674
        } catch(Throwable th) {
675
            state.setBreakingsCause(th);
676
        }
677

    
678

    
679
        try {
680
            String defaultFeatureTypeId = (String) state.get("defaultFeatureTypeId");
681
            FeatureType ftype;
682

    
683
            if (defaultFeatureType == null ||
684
                    defaultFeatureType.getId() == null ||
685
                    !defaultFeatureType.getId().equals(defaultFeatureTypeId)) {
686

    
687
                    ftype = getFeatureType(defaultFeatureTypeId);
688
                    if (ftype == null) {
689
                            /*
690
                             * Un error en el m?todo de PostgreSQL getName(), hace que
691
                             * el nombre del featureType sea valor retornado por el getProviderName()
692
                             * De momento se pone este parche para apa?arlo y poder mantener compatibilidad
693
                             * con proyectos antiguos (2.1 y 2.2)
694
                             */
695
                            ftype = getFeatureType(getName());
696
                            if(ftype == null ) {
697
                                    throw new RuntimeException("Can't locate feature type");
698
                            }
699
                    }
700
                    defaultFeatureType = ftype;
701
            }
702
        } catch(Throwable th) {
703
            state.setBreakingsCause(th);
704
        }
705

    
706
        LOG.info("load() broken:{}, {}, {}.",
707
                new Object[] { state.isBroken(), this.getProviderName(), params }
708
        );
709
    }
710

    
711
        public DataStoreProviderServices getStoreProviderServices() {
712
                return this;
713
        }
714

    
715
    public static void registerPersistenceDefinition() {
716
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
717
        if (manager.getDefinition(PERSISTENCE_DEFINITION_NAME) == null) {
718
            DynStruct definition =
719
                manager.addDefinition(DefaultFeatureStore.class,
720
                    PERSISTENCE_DEFINITION_NAME, PERSISTENCE_DEFINITION_NAME
721
                        + " Persistent definition", null, null);
722
            definition.addDynFieldString("dataStoreName").setMandatory(true)
723
                .setPersistent(true);
724

    
725
            definition.addDynFieldObject("parameters")
726
                .setClassOfValue(DynObject.class).setMandatory(true)
727
                .setPersistent(true);
728

    
729
            definition.addDynFieldObject("selection")
730
                .setClassOfValue(FeatureSelection.class).setMandatory(false)
731
                .setPersistent(true);
732

    
733
            definition.addDynFieldObject("transforms")
734
                .setClassOfValue(DefaultFeatureStoreTransforms.class)
735
                .setMandatory(true).setPersistent(true);
736

    
737
            definition.addDynFieldMap("evaluatedAttributes")
738
                .setClassOfItems(List.class) // List<DefaultFeatureAttributeDescriptor>
739
                .setMandatory(false).setPersistent(true);
740

    
741
            definition.addDynFieldString("defaultFeatureTypeId")
742
                .setMandatory(true).setPersistent(true);
743
        }
744
    }
745

    
746
    public static void registerMetadataDefinition() throws MetadataException {
747
        MetadataManager manager = MetadataLocator.getMetadataManager();
748
        if (manager.getDefinition(FeatureStore.METADATA_DEFINITION_NAME) == null) {
749
            DynStruct metadataDefinition =
750
                manager.addDefinition(FeatureStore.METADATA_DEFINITION_NAME, null);
751
            metadataDefinition.extend(manager
752
                .getDefinition(DataStore.METADATA_DEFINITION_NAME));
753
        }
754
    }
755

    
756
    //
757
    // ====================================================================
758
    // Gestion de la seleccion
759
    //
760

    
761
    @Override
762
    public void setSelection(DataSet selection) throws DataException {
763
        this.setSelection((FeatureSet) selection);
764
    }
765

    
766
    @Override
767
    public DataSet createSelection() throws DataException {
768
        return createFeatureSelection();
769
    }
770

    
771
    @Override
772
    public DataSet getSelection() throws DataException {
773
        return this.getFeatureSelection();
774
    }
775

    
776
    @Override
777
    public void setSelection(FeatureSet selection) throws DataException {
778
        setSelection(selection, true);
779
    }
780

    
781
    public void setSelection(FeatureSet selection, boolean undoable)
782
        throws DataException {
783
        if (selection == null) {
784
            if (undoable) {
785
                throw new SelectionNotAllowedException(getName());
786
            }
787

    
788
        } else {
789
            if (selection.equals(this.selection)) {
790
                return;
791
            }
792
            if (!selection.isFromStore(this)) {
793
                throw new SelectionNotAllowedException(getName());
794
            }
795
        }
796

    
797
        if (this.selection != null) {
798
            this.selection.deleteObserver(this);
799
        }
800
        if (selection == null) {
801
            if (this.selection != null) {
802
                this.selection.dispose();
803
            }
804
            this.selection = null;
805
            return;
806
        }
807
        if (selection instanceof FeatureSelection) {
808
            if (undoable && isEditing()) {
809
                commands.selectionSet(this, this.selection,
810
                    (FeatureSelection) selection);
811
            }
812
            if (this.selection != null) {
813
                this.selection.dispose();
814
            }
815
            this.selection = (FeatureSelection) selection;
816
        } else {
817
            if (undoable && isEditing()) {
818
                commands.startComplex("_selectionSet");
819
            }
820
            if (selection instanceof DefaultFeatureSelection) {
821
                DefaultFeatureSelection defSelection =
822
                    (DefaultFeatureSelection) selection;
823
                defSelection.deselectAll(undoable);
824
                defSelection.select(selection, undoable);
825
            } else {
826
                this.selection.deselectAll();
827
                this.selection.select(selection);
828
            }
829
            if (undoable && isEditing()) {
830
                commands.endComplex();
831
            }
832
        }
833
        this.selection.addObserver(this);
834

    
835
        this.notifyChange(DataStoreNotification.SELECTION_CHANGE);
836
    }
837

    
838
    @Override
839
    public FeatureSelection createFeatureSelection() throws DataException {
840
        return this.provider.createFeatureSelection();
841
    }
842

    
843
    @Override
844
    public FeatureSelection getFeatureSelection() throws DataException {
845
        if (selection == null) {
846
            this.selection = createFeatureSelection();
847
            this.selection.addObserver(this);
848
        }
849
        return selection;
850
    }
851

    
852
    //
853
    // ====================================================================
854
    // Gestion de notificaciones
855
    //
856

    
857
    @Override
858
    public void notifyChange(FeatureStoreNotification storeNotification) {
859
        try {
860
            delegateObservable.notifyObservers(storeNotification);
861
        } catch (Throwable ex) {
862
            LOG.warn("Problems notifying changes in the store '"+this.getName()+" ("+storeNotification.getType()+").",ex);
863
        }
864
    }
865

    
866
    @Override
867
    public void notifyChange(String notification) {
868
        if (delegateObservable != null) {
869
            notifyChange(new DefaultFeatureStoreNotification(this, notification));
870
        }
871

    
872
    }
873

    
874
    @Override
875
    public void notifyChange(String notification, FeatureProvider data) {
876
        Feature f = null;
877
        try {
878
            f = createFeature(data);
879
        } catch (Throwable ex) {
880
            LOG.warn("Problems creating a feature to notifying changes in the store '"+this.getName()+" ("+notification+").",ex);
881
        }
882
        notifyChange(notification, f);
883
    }
884

    
885
    public void notifyChange(String notification, Feature feature) {
886
        notifyChange(new DefaultFeatureStoreNotification(this, notification,
887
            feature));
888
    }
889

    
890
    public void notifyChange(String notification, Command command) {
891
        notifyChange(new DefaultFeatureStoreNotification(this, notification,
892
            command));
893
    }
894

    
895
    public void notifyChange(String notification, EditableFeatureType type) {
896
        notifyChange(new DefaultFeatureStoreNotification(this, notification,
897
            type));
898
    }
899

    
900
    @Override
901
    public void notifyChange(String notification, Resource resource) {
902
        notifyChange(new DefaultFeatureStoreNotification(this,
903
            DataStoreNotification.RESOURCE_CHANGED));
904
    }
905

    
906
    //
907
    // ====================================================================
908
    // Gestion de bloqueos
909
    //
910

    
911
    @Override
912
    public boolean isLocksSupported() {
913
        return this.provider.isLocksSupported();
914
    }
915

    
916
    @Override
917
    public FeatureLocks getLocks() throws DataException {
918
        if (!this.provider.isLocksSupported()) {
919
            LOG.warn("Locks not supported");
920
            return null;
921
        }
922
        if (locks == null) {
923
            this.locks = this.provider.createFeatureLocks();
924
        }
925
        return locks;
926
    }
927

    
928
    //
929
    // ====================================================================
930
    // Interface Observable
931
    //
932

    
933
    @Override
934
    public void disableNotifications() {
935
        this.delegateObservable.disableNotifications();
936

    
937
    }
938

    
939
    @Override
940
    public void enableNotifications() {
941
        this.delegateObservable.enableNotifications();
942
    }
943

    
944
    @Override
945
    public void beginComplexNotification() {
946
        this.delegateObservable.beginComplexNotification();
947

    
948
    }
949

    
950
    @Override
951
    public void endComplexNotification() {
952
        this.delegateObservable.endComplexNotification();
953

    
954
    }
955

    
956
    @Override
957
    public void addObserver(Observer observer) {
958
        if (delegateObservable != null) {
959
            this.delegateObservable.addObserver(observer);
960
        }
961
    }
962

    
963
    @Override
964
    public void deleteObserver(Observer observer) {
965
        if (delegateObservable != null) {
966
            this.delegateObservable.deleteObserver(observer);
967
        }
968
    }
969

    
970
    @Override
971
    public void deleteObservers() {
972
        this.delegateObservable.deleteObservers();
973

    
974
    }
975

    
976
    //
977
    // ====================================================================
978
    // Interface Observer
979
    //
980
    // Usado para observar:
981
    // - su seleccion
982
    // - sus bloqueos
983
    // - sus recursos
984
    //
985

    
986
    @Override
987
    public void update(Observable observable, Object notification) {
988
        if (observable instanceof FeatureSet) {
989
            if (observable == this.selection) {
990
                this.notifyChange(DataStoreNotification.SELECTION_CHANGE);
991
            } else if (observable == this.locks) {
992
                this.notifyChange(FeatureStoreNotification.LOCKS_CHANGE);
993
            }
994

    
995
        } else if (observable instanceof FeatureStoreProvider) {
996
            if (observable == this.provider) {
997

    
998
            }
999
        } else if (observable instanceof FeatureReferenceSelection) {
1000
            if(notification instanceof String){
1001
                    this.notifyChange((String)notification);
1002
            }
1003
        }
1004
    }
1005

    
1006
    //
1007
    // ====================================================================
1008
    // Edicion
1009
    //
1010

    
1011
    private void newVersionOfUpdate() {
1012
        this.versionOfUpdate++;
1013
    }
1014

    
1015
    private long currentVersionOfUpdate() {
1016
        return this.versionOfUpdate;
1017
    }
1018

    
1019
    private void checkInEditingMode() throws NeedEditingModeException {
1020
        if (mode != MODE_FULLEDIT) {
1021
            throw new NeedEditingModeException(this.getName());
1022
        }
1023
    }
1024

    
1025
    private void checkNotInAppendMode() throws IllegalStateException {
1026
        if (mode == MODE_APPEND) {
1027
                        throw new IllegalStateException("Error: store "
1028
                                        + this.getFullName() + " is in append mode");
1029
        }
1030
    }
1031

    
1032
    private void checkIsOwnFeature(Feature feature)
1033
        throws IllegalFeatureException {
1034
        if (((DefaultFeature) feature).getStore() != this) {
1035
            throw new IllegalFeatureException(this.getName());
1036
        }
1037
        // FIXME: fixFeatureType no vale para el checkIsOwnFeature
1038
        // fixFeatureType((DefaultFeatureType) feature.getType());
1039
    }
1040

    
1041
    private void exitEditingMode() {
1042
        if (commands != null) {
1043
            commands.clear();
1044
            commands = null;
1045
        }
1046

    
1047
        if (featureTypeManager != null) {
1048
            featureTypeManager.dispose();
1049
            featureTypeManager = null;
1050

    
1051
        }
1052

    
1053
        // TODO implementar un dispose para estos dos
1054
        featureManager = null;
1055
        spatialManager = null;
1056

    
1057
        featureCount = null;
1058

    
1059
        mode = MODE_QUERY;
1060
        hasStrongChanges = true; // Lo deja a true por si las moscas
1061
        hasInserts = true;
1062
    }
1063

    
1064
    @Override
1065
    synchronized public void edit() throws DataException {
1066
        edit(MODE_FULLEDIT);
1067
    }
1068

    
1069
    @Override
1070
    synchronized public void edit(int mode) throws DataException {
1071
        LOG.debug("Starting editing in mode: {}", mode);
1072
        try {
1073
            if (this.mode != MODE_QUERY) {
1074
                throw new AlreadyEditingException(this.getName());
1075
            }
1076
            if (!this.provider.supportsAppendMode()) {
1077
                mode = MODE_FULLEDIT;
1078
            }
1079
            switch (mode) {
1080
            case MODE_QUERY:
1081
                throw new IllegalStateException(this.getName());
1082

    
1083
            case MODE_FULLEDIT:
1084
                if (!this.transforms.isEmpty()) {
1085
                    throw new IllegalStateException(this.getName());
1086
                }
1087
                notifyChange(FeatureStoreNotification.BEFORE_STARTEDITING);
1088
                invalidateIndexes();
1089
                featureManager = new FeatureManager();
1090
                featureTypeManager = new FeatureTypeManager(this);
1091
                spatialManager = new SpatialManager(this, provider.getEnvelope());
1092

    
1093
                commands = new DefaultFeatureCommandsStack(
1094
                        this, featureManager,
1095
                        spatialManager, featureTypeManager);
1096
                this.mode = MODE_FULLEDIT;
1097
                hasStrongChanges = false;
1098
                hasInserts = false;
1099
                notifyChange(FeatureStoreNotification.AFTER_STARTEDITING);
1100
                break;
1101
            case MODE_APPEND:
1102
                if (!this.transforms.isEmpty()) {
1103
                    throw new IllegalStateException(this.getName());
1104
                }
1105
                notifyChange(FeatureStoreNotification.BEFORE_STARTEDITING);
1106
                invalidateIndexes();
1107
                this.provider.beginAppend();
1108
                this.mode = MODE_APPEND;
1109
                hasInserts = false;
1110
                notifyChange(FeatureStoreNotification.AFTER_STARTEDITING);
1111
                break;
1112
            }
1113
        } catch (Exception e) {
1114
            throw new StoreEditException(e, this.getName());
1115
        }
1116
    }
1117

    
1118
    private void invalidateIndexes() {
1119
        setIndexesValidStatus(false);
1120
    }
1121

    
1122
    private void setIndexesValidStatus(boolean valid) {
1123
        FeatureIndexes theIndexes = getIndexes();
1124
        LOG.debug("Setting the store indexes to valid status {}: {}", (valid
1125
            ? Boolean.TRUE : Boolean.FALSE), theIndexes);
1126
        for (Iterator iterator = theIndexes.iterator(); iterator.hasNext();) {
1127
            FeatureIndex index = (FeatureIndex) iterator.next();
1128
            if (index instanceof FeatureIndexProviderServices) {
1129
                FeatureIndexProviderServices indexServices =
1130
                    (FeatureIndexProviderServices) index;
1131
                indexServices.setValid(valid);
1132
            }
1133
        }
1134
    }
1135

    
1136
    private void updateIndexes() throws FeatureIndexException {
1137
        FeatureIndexes theIndexes = getIndexes();
1138
        LOG.debug("Refilling indexes: {}", theIndexes);
1139
        for (Iterator iterator = theIndexes.iterator(); iterator.hasNext();) {
1140
            FeatureIndex index = (FeatureIndex) iterator.next();
1141
            if (index instanceof FeatureIndexProviderServices) {
1142
                FeatureIndexProviderServices indexServices =
1143
                    (FeatureIndexProviderServices) index;
1144
                indexServices.fill(true, null);
1145
            }
1146
        }
1147
    }
1148

    
1149
    private void waitForIndexes() {
1150
        FeatureIndexes theIndexes = getIndexes();
1151
        LOG.debug("Waiting for indexes to finish filling: {}", theIndexes);
1152
        for (Iterator iterator = theIndexes.iterator(); iterator.hasNext();) {
1153
            FeatureIndex index = (FeatureIndex) iterator.next();
1154
            if (index instanceof FeatureIndexProviderServices) {
1155
                FeatureIndexProviderServices indexServices =
1156
                    (FeatureIndexProviderServices) index;
1157
                indexServices.waitForIndex();
1158
            }
1159
        }
1160
    }
1161

    
1162
    private void disposeIndexes() {
1163
        FeatureIndexes theIndexes = getIndexes();
1164
        LOG.debug("Disposing indexes: {}", theIndexes);
1165
        if( theIndexes==null ) {
1166
            return;
1167
        }
1168
        for (Iterator iterator = theIndexes.iterator(); iterator.hasNext();) {
1169
            FeatureIndex index = (FeatureIndex) iterator.next();
1170
            if (index instanceof FeatureIndexProviderServices) {
1171
                FeatureIndexProviderServices indexServices =
1172
                    (FeatureIndexProviderServices) index;
1173
                indexServices.dispose();
1174
            }
1175
        }
1176
    }
1177

    
1178
    @Override
1179
    public boolean isEditing() {
1180
        return mode == MODE_FULLEDIT;
1181
    }
1182

    
1183
    @Override
1184
    public boolean isAppending() {
1185
        return mode == MODE_APPEND;
1186
    }
1187

    
1188
    @Override
1189
    synchronized public void update(EditableFeatureType type)
1190
        throws DataException {
1191
        try {
1192
            if (type == null) {
1193
                throw new NullFeatureTypeException(getName());
1194
            }
1195
            boolean typehasStrongChanges = ((DefaultEditableFeatureType) type).hasStrongChanges();
1196
            if (typehasStrongChanges) {
1197
                checkInEditingMode();
1198
            }  else if(this.isAppending()) {
1199
                throw new NeedEditingModeException(this.getName());
1200
            }
1201
            // FIXME: Comprobar que es un featureType aceptable.
1202
            notifyChange(FeatureStoreNotification.BEFORE_UPDATE_TYPE, type);
1203
            newVersionOfUpdate();
1204
            
1205
            if (typehasStrongChanges) { 
1206
                FeatureType oldt = type.getSource().getCopy();
1207
                FeatureType newt = type.getCopy();
1208
                commands.update(newt, oldt);
1209
                hasStrongChanges = true;
1210
            } else {
1211
                boolean ok = this.featureTypes.remove(this.defaultFeatureType);
1212
                this.defaultFeatureType = type.getNotEditableCopy();
1213
                if (ok) {
1214
                    this.featureTypes.add(this.defaultFeatureType);
1215
                }
1216
            }
1217
            notifyChange(FeatureStoreNotification.AFTER_UPDATE_TYPE, type);
1218
        } catch (Exception e) {
1219
            throw new StoreUpdateFeatureTypeException(e, this.getName());
1220
        }
1221
    }
1222

    
1223
    @Override
1224
    public void delete(Feature feature) throws DataException {
1225
        this.commands.delete(feature);
1226
    }
1227

    
1228
    synchronized public void doDelete(Feature feature) throws DataException {
1229
        try {
1230
            checkInEditingMode();
1231
            checkIsOwnFeature(feature);
1232
            if (feature instanceof EditableFeature) {
1233
                throw new StoreDeleteEditableFeatureException(getName());
1234
            }
1235
            notifyChange(FeatureStoreNotification.BEFORE_DELETE, feature);
1236

    
1237
            //Update the featureManager and the spatialManager
1238
            featureManager.delete(feature.getReference());
1239
            spatialManager.deleteFeature(feature);
1240

    
1241
            newVersionOfUpdate();
1242
            hasStrongChanges = true;
1243
            notifyChange(FeatureStoreNotification.AFTER_DELETE, feature);
1244
        } catch (Exception e) {
1245
            throw new StoreDeleteFeatureException(e, this.getName());
1246
        }
1247
    }
1248

    
1249
    private static EditableFeature lastChangedFeature = null;
1250

    
1251
    @Override
1252
    public synchronized void insert(EditableFeature feature)
1253
        throws DataException {
1254
        LOG.debug("In editing mode {}, insert feature: {}", mode, feature);
1255
        try {
1256
            switch (mode) {
1257
            case MODE_QUERY:
1258
                throw new NeedEditingModeException(this.getName());
1259

    
1260
            case MODE_APPEND:
1261
                checkIsOwnFeature(feature);
1262
                if (feature.getSource() != null) {
1263
                    throw new NoNewFeatureInsertException(this.getName());
1264
                }
1265
                this.featureCount = null;
1266
                notifyChange(FeatureStoreNotification.BEFORE_INSERT, feature);
1267
                feature.validate(Feature.UPDATE);
1268
                provider.append(((DefaultEditableFeature) feature).getData());
1269
                hasStrongChanges = true;
1270
                hasInserts = true;
1271
                notifyChange(FeatureStoreNotification.AFTER_INSERT, feature);
1272
                break;
1273

    
1274
            case MODE_FULLEDIT:
1275
                if (feature.getSource() != null) {
1276
                    throw new NoNewFeatureInsertException(this.getName());
1277
                }
1278
                commands.insert(feature);
1279
            }
1280
        } catch (Exception e) {
1281
            throw new StoreInsertFeatureException(e, this.getName());
1282
        }
1283
    }
1284

    
1285
    synchronized public void doInsert(EditableFeature feature)
1286
        throws DataException {
1287
        checkIsOwnFeature(feature);
1288

    
1289
        waitForIndexes();
1290

    
1291
        notifyChange(FeatureStoreNotification.BEFORE_INSERT, feature);
1292
        newVersionOfUpdate();
1293
        if ((lastChangedFeature == null)
1294
            || (lastChangedFeature.getSource() != feature.getSource())) {
1295
            lastChangedFeature = feature;
1296
            feature.validate(Feature.UPDATE);
1297
            lastChangedFeature = null;
1298
        }
1299
        //Update the featureManager and the spatialManager
1300
        ((DefaultEditableFeature) feature).setInserted(true);
1301
        DefaultFeature newFeature = (DefaultFeature) feature.getNotEditableCopy();
1302

    
1303

    
1304
        featureManager.add(newFeature);
1305
        spatialManager.insertFeature(newFeature);
1306

    
1307
        hasStrongChanges = true;
1308
        hasInserts = true;
1309
        notifyChange(FeatureStoreNotification.AFTER_INSERT, feature);
1310
    }
1311

    
1312
    @Override
1313
    public void update(EditableFeature feature)
1314
    throws DataException {
1315
        if ((feature).getSource() == null) {
1316
            insert(feature);
1317
            return;
1318
        }
1319
        commands.update(feature, feature.getSource());
1320
    }
1321

    
1322
    synchronized public void doUpdate(EditableFeature feature, Feature oldFeature)
1323
        throws DataException {
1324
        try {
1325
            checkInEditingMode();
1326
            checkIsOwnFeature(feature);
1327
            notifyChange(FeatureStoreNotification.BEFORE_UPDATE, feature);
1328
            newVersionOfUpdate();
1329
            if ((lastChangedFeature == null)
1330
                || (lastChangedFeature.getSource() != feature.getSource())) {
1331
                lastChangedFeature = feature;
1332
                feature.validate(Feature.UPDATE);
1333
                lastChangedFeature = null;
1334
            }
1335

    
1336
            //Update the featureManager and the spatialManager
1337
            Feature newf = feature.getNotEditableCopy();
1338
            featureManager.update(newf, oldFeature);
1339
            spatialManager.updateFeature(newf, oldFeature);
1340

    
1341
            hasStrongChanges = true;
1342
            notifyChange(FeatureStoreNotification.AFTER_UPDATE, feature);
1343
        } catch (Exception e) {
1344
            throw new StoreUpdateFeatureException(e, this.getName());
1345
        }
1346
    }
1347

    
1348
    @Override
1349
    synchronized public void redo() throws RedoException {
1350
        Command redo = commands.getNextRedoCommand();
1351
        try {
1352
            checkInEditingMode();
1353
        } catch (NeedEditingModeException ex) {
1354
            throw new RedoException(redo, ex);
1355
        }
1356
        notifyChange(FeatureStoreNotification.BEFORE_REDO, redo);
1357
        newVersionOfUpdate();
1358
        commands.redo();
1359
        hasStrongChanges = true;
1360
        notifyChange(FeatureStoreNotification.AFTER_REDO, redo);
1361
    }
1362

    
1363
    @Override
1364
    synchronized public void undo() throws UndoException {
1365
        Command undo = commands.getNextUndoCommand();
1366
        try {
1367
            checkInEditingMode();
1368
        } catch (NeedEditingModeException ex) {
1369
            throw new UndoException(undo, ex);
1370
        }
1371
        notifyChange(FeatureStoreNotification.BEFORE_UNDO, undo);
1372
        newVersionOfUpdate();
1373
        commands.undo();
1374
        hasStrongChanges = true;
1375
        notifyChange(FeatureStoreNotification.AFTER_UNDO, undo);
1376
    }
1377

    
1378
    @Override
1379
    public List getRedoInfos() {
1380
        if (isEditing() && (commands != null)) {
1381
            return commands.getRedoInfos();
1382
        } else {
1383
            return null;
1384
        }
1385
    }
1386

    
1387
    @Override
1388
    public List getUndoInfos() {
1389
        if (isEditing() && (commands != null)) {
1390
            return commands.getUndoInfos();
1391
        } else {
1392
            return null;
1393
        }
1394
    }
1395

    
1396
    public synchronized FeatureCommandsStack getCommandsStack()
1397
        throws DataException {
1398
        checkInEditingMode();
1399
        return commands;
1400
    }
1401

    
1402
    @Override
1403
    synchronized public void cancelEditing() throws DataException {
1404
        if( spatialManager!=null ) {
1405
            spatialManager.cancelModifies();
1406
        }
1407
        try {
1408
            switch (mode) {
1409
            case MODE_QUERY:
1410
                throw new NeedEditingModeException(this.getName());
1411

    
1412
            case MODE_APPEND:
1413
                notifyChange(FeatureStoreNotification.BEFORE_CANCELEDITING);
1414
                provider.abortAppend();
1415
                exitEditingMode();
1416
                ((FeatureSelection) this.getSelection()).deselectAll();
1417
                updateIndexes();
1418
                notifyChange(FeatureStoreNotification.AFTER_CANCELEDITING);   
1419

    
1420
            case MODE_FULLEDIT:
1421
                boolean clearSelection = this.hasStrongChanges;
1422
                if (this.selection instanceof FeatureReferenceSelection) {
1423
                    clearSelection = this.hasInserts;
1424
                }
1425
                notifyChange(FeatureStoreNotification.BEFORE_CANCELEDITING);
1426
                exitEditingMode();
1427
                if (clearSelection) {
1428
                    ((FeatureSelection) this.getSelection()).deselectAll();
1429
                }
1430
                updateIndexes();
1431
                notifyChange(FeatureStoreNotification.AFTER_CANCELEDITING);   
1432
            }
1433
        } catch (Exception e) {
1434
            throw new StoreCancelEditingException(e, this.getName());
1435
        }
1436
    }
1437

    
1438
    @Override
1439
    synchronized public void finishEditing() throws DataException {
1440
        LOG.debug("finish editing of mode: {}", mode);
1441
        try {
1442

    
1443
            /*
1444
             * Selection needs to be cleared when editing stops
1445
             * to prevent conflicts with selection remaining from
1446
             * editing mode.
1447
             */
1448
//            ((FeatureSelection) this.getSelection()).deselectAll();
1449
            Map<String,List<FeatureAttributeDescriptor>> computedFields = this.getComputedFields();
1450
            switch (mode) {
1451
            case MODE_QUERY:
1452
                throw new NeedEditingModeException(this.getName());
1453

    
1454
            case MODE_APPEND:
1455
                if( selection!=null ) {
1456
                    selection = null;
1457
                }
1458
                notifyChange(FeatureStoreNotification.BEFORE_FINISHEDITING);
1459
                provider.endAppend();
1460
                exitEditingMode();
1461
                this.updateComputedFields(computedFields);
1462
                saveDALFile();
1463
                updateIndexes();
1464
                notifyChange(FeatureStoreNotification.AFTER_FINISHEDITING);
1465
                break;
1466

    
1467
            case MODE_FULLEDIT:
1468
                if (hasStrongChanges && !this.allowWrite()) {
1469
                    throw new WriteNotAllowedException(getName());
1470
                }
1471
                if(featureManager.isSelectionCompromised() && selection!=null ) {
1472
                    selection = null;
1473
                }
1474
                notifyChange(FeatureStoreNotification.BEFORE_FINISHEDITING);
1475
                if (hasStrongChanges) {
1476
                    validateFeatures(Feature.FINISH_EDITING);
1477

    
1478
                    /*
1479
                     * This will throw a PerformEditingExceptionif the provider
1480
                     * does not accept the changes (for example, an invalid field name)
1481
                     */
1482
                    provider.performChanges(featureManager.getDeleted(),
1483
                        featureManager.getInserted(),
1484
                        featureManager.getUpdated(),
1485
                        removeCalculatedAttributes(featureTypeManager.getFeatureTypesChanged()).iterator());
1486
                    
1487
                }  
1488
                exitEditingMode();
1489
                this.updateComputedFields(computedFields);
1490
                saveDALFile();
1491
                updateIndexes();
1492
                notifyChange(FeatureStoreNotification.AFTER_FINISHEDITING);
1493
                break;
1494
            }
1495
        } catch (PerformEditingException pee) {
1496
            throw new WriteException(provider.getSourceId().toString(), pee);
1497
        } catch (Exception e) {
1498
            throw new FinishEditingException(e);
1499
        }
1500
    }
1501
    private Map<String,List<FeatureAttributeDescriptor>> getComputedFields() throws DataException {
1502
        Map<String,List<FeatureAttributeDescriptor>> r = new HashMap<>();
1503
        
1504
        List<FeatureType> theTypes = new ArrayList<>();
1505
        theTypes.addAll(this.getFeatureTypes());
1506
        theTypes.add(this.getDefaultFeatureType());
1507
        for( int n=0; n<theTypes.size(); n++ ) {
1508
            FeatureType type = theTypes.get(n);
1509
                for (FeatureAttributeDescriptor attrdesc : type) {
1510
                    FeatureAttributeEmulator emulator = attrdesc.getFeatureAttributeEmulator();
1511
                    if( emulator!= null) {
1512
                        List<FeatureAttributeDescriptor> l = r.get(type.getId());
1513
                        if (l==null) {
1514
                            l = new ArrayList<>();
1515
                            r.put(type.getId(), l);
1516
                        }
1517
                        l.add(attrdesc);
1518
                    }
1519
            }
1520
        }
1521
        return r;
1522
    }
1523
    private void updateComputedFields(Map<String,List<FeatureAttributeDescriptor>> computedFields) throws DataException {
1524

    
1525
        List<FeatureType> theTypes = new ArrayList<>();
1526
        theTypes.addAll(this.getFeatureTypes());
1527
        theTypes.add(this.getDefaultFeatureType());
1528
        for( int n=0; n<theTypes.size(); n++ ) {
1529
            DefaultFeatureType type = (DefaultFeatureType) theTypes.get(n);
1530
            List<FeatureAttributeDescriptor> x = computedFields.get(type.getId());
1531
            if(x!=null && !x.isEmpty()) {
1532
                for (FeatureAttributeDescriptor attrdesc : x) {
1533
                    if (type.get(attrdesc.getName())==null) {
1534
                        type.add(attrdesc);
1535
                    }
1536
                }
1537
            }
1538
        }
1539
        
1540
    }
1541
    private List<FeatureStoreProvider.FeatureTypeChanged> removeCalculatedAttributes(List<FeatureStoreProvider.FeatureTypeChanged> ftypes) {
1542
        // FIXME: Falta por implementar
1543
//        for (FeatureStoreProvider.FeatureTypeChanged ftype : ftypes) {
1544
//            EditableFeatureType target = (EditableFeatureType) ftype.getTarget();
1545
//            for (FeatureAttributeDescriptor attributeDescriptor : ftype.getSource().getAttributeDescriptors()) {
1546
//                if (attributeDescriptor.isComputed()) {
1547
//                    target.remove(attributeDescriptor.getName());
1548
//                }
1549
//            }
1550
//        }
1551
        return ftypes;
1552
    }
1553
    
1554

    
1555
    @SuppressWarnings("UseSpecificCatch")
1556
    private void saveDALFile() {       
1557
        try {
1558
            DataServerExplorer explorer = this.getExplorer();
1559
            if( explorer == null ) {
1560
                return;
1561
            }
1562
            File f = explorer.getResourcePath(this, "dal");
1563
            if( f == null ) {
1564
                return;
1565
            }
1566
            DALFile dalFile = DALFile.getDALFile();
1567
            dalFile.setStore(this);
1568
            if( !dalFile.isEmpty() ) {
1569
                dalFile.write(f);
1570
            }
1571
        } catch (Exception ex) {
1572
            LOG.warn("Can't save DAL File", ex);
1573
        }
1574
    }
1575
    
1576
    @SuppressWarnings("UseSpecificCatch")
1577
    private void loadDALFile() {
1578
        try {
1579
            DataServerExplorer explorer = this.getExplorer();
1580
            if( explorer == null ) {
1581
                return;
1582
            }
1583
            File f = explorer.getResourcePath(this, "dal");
1584
            if( f == null || !f.exists() ) {
1585
                return;
1586
            }
1587
            DALFile dalFile = DALFile.getDALFile(f);
1588
            if( !dalFile.isEmpty() ) {
1589
                dalFile.updateStore(this);
1590
            }
1591
        } catch (Exception ex) {
1592
            LOG.warn("Can't load DAL File", ex);
1593
        }
1594
    }
1595
    
1596
    /**
1597
     * Save changes in the provider without leaving the edit mode.
1598
     * Do not call observers to communicate a change of ediding mode.
1599
     * The operation's history is eliminated to prevent inconsistencies
1600
     * in the data.
1601
     *
1602
     * @throws DataException
1603
     */
1604
    @Override
1605
    synchronized public void commitChanges() throws DataException {
1606
      LOG.debug("commitChanges of mode: {}", mode);
1607
      if( !canCommitChanges() ) {
1608
              throw new WriteNotAllowedException(getName());
1609
      }
1610
      try {
1611
        switch (mode) {
1612
        case MODE_QUERY:
1613
          throw new NeedEditingModeException(this.getName());
1614

    
1615
        case MODE_APPEND:
1616
          this.provider.endAppend();
1617
          exitEditingMode();
1618
          invalidateIndexes();
1619
          this.provider.beginAppend();
1620
          hasInserts = false;
1621
          break;
1622

    
1623
        case MODE_FULLEDIT:
1624
          if (hasStrongChanges && !this.allowWrite()) {
1625
            throw new WriteNotAllowedException(getName());
1626
          }
1627
          if (hasStrongChanges) {
1628
            validateFeatures(Feature.FINISH_EDITING);
1629
            provider.performChanges(featureManager.getDeleted(),
1630
              featureManager.getInserted(),
1631
              featureManager.getUpdated(),
1632
              removeCalculatedAttributes(featureTypeManager.getFeatureTypesChanged()).iterator());
1633
          }
1634
          invalidateIndexes();
1635
          featureManager = new FeatureManager();
1636
          featureTypeManager = new FeatureTypeManager(this);
1637
          spatialManager = new SpatialManager(this, provider.getEnvelope());
1638

    
1639
          commands =
1640
            new DefaultFeatureCommandsStack(this, featureManager,
1641
              spatialManager, featureTypeManager);
1642
          featureCount = null;
1643
          hasStrongChanges = false;
1644
          hasInserts = false;
1645
          break;
1646
        }
1647
      } catch (Exception e) {
1648
        throw new FinishEditingException(e);
1649
      }
1650
    }
1651

    
1652
    @Override
1653
    synchronized public boolean canCommitChanges() throws DataException {
1654
        if ( !this.allowWrite()) {
1655
                return false;
1656
        }
1657
            switch (mode) {
1658
            default:
1659
        case MODE_QUERY:
1660
                return false;
1661

    
1662
        case MODE_APPEND:
1663
                return true;
1664

    
1665
        case MODE_FULLEDIT:
1666
            List types = this.getFeatureTypes();
1667
            for( int i=0; i<types.size(); i++ ) {
1668
                    Object type = types.get(i);
1669
                    if( type instanceof DefaultEditableFeatureType ) {
1670
                            if( ((DefaultEditableFeatureType)type).hasStrongChanges() ) {
1671
                                    return false;
1672
                            }
1673
                    }
1674
            }
1675
            return true;
1676
            }
1677
    }
1678

    
1679
    @Override
1680
    public void beginEditingGroup(String description)
1681
        throws NeedEditingModeException {
1682
        checkInEditingMode();
1683
        commands.startComplex(description);
1684
    }
1685

    
1686
    @Override
1687
    public void endEditingGroup() throws NeedEditingModeException {
1688
        checkInEditingMode();
1689
        commands.endComplex();
1690
    }
1691

    
1692
    @Override
1693
    public boolean isAppendModeSupported() {
1694
        return this.provider.supportsAppendMode();
1695
    }
1696

    
1697
    @Override
1698
    public void export(DataServerExplorer explorer, String provider,
1699
        NewFeatureStoreParameters params) throws DataException {
1700

    
1701
        if (this.getFeatureTypes().size() != 1) {
1702
            throw new NotYetImplemented(
1703
                "export whith more than one type not yet implemented");
1704
        }
1705
        FeatureSelection featureSelection = (FeatureSelection) getSelection();
1706
        FeatureStore target = null;
1707
        FeatureSet features = null;
1708
        DisposableIterator iterator = null;
1709
        try {
1710
            FeatureType type = this.getDefaultFeatureType();
1711
            if ((params.getDefaultFeatureType() == null)
1712
                || (params.getDefaultFeatureType().size() == 0)) {
1713
                params.setDefaultFeatureType(type.getEditable());
1714

    
1715
            }
1716
            explorer.add(provider, params, true);
1717

    
1718
            DataManager manager = DALLocator.getDataManager();
1719
            target = (FeatureStore) manager.openStore(provider, params);
1720
            FeatureType targetType = target.getDefaultFeatureType();
1721

    
1722
            target.edit(MODE_APPEND);
1723
            FeatureAttributeDescriptor[] pkattrs = type.getPrimaryKey();
1724
            if (featureSelection.getSize() > 0) {
1725
                features = this.getFeatureSelection();
1726
            } else {
1727
                if ((pkattrs != null) && (pkattrs.length > 0)) {
1728
                    FeatureQuery query = createFeatureQuery();
1729
                    for (FeatureAttributeDescriptor pkattr : pkattrs) {
1730
                        query.getOrder().add(pkattr.getName(), true);
1731
                    }
1732
                    features = this.getFeatureSet(query);
1733
                } else {
1734
                    features = this.getFeatureSet();
1735
                }
1736
            }
1737
            iterator = features.fastIterator();
1738
            while (iterator.hasNext()) {
1739
                DefaultFeature feature = (DefaultFeature) iterator.next();
1740
                target.insert(target.createNewFeature(targetType, feature));
1741
            }
1742
            target.finishEditing();
1743
            target.dispose();
1744
        } catch (Exception e) {
1745
            throw new DataExportException(e, params.toString());
1746
        } finally {
1747
            dispose(iterator);
1748
            dispose(features);
1749
            dispose(target);
1750
        }
1751
    }
1752

    
1753
    //
1754
    // ====================================================================
1755
    // Obtencion de datos
1756
    // getDataCollection, getFeatureCollection
1757
    //
1758

    
1759
    @Override
1760
    public DataSet getDataSet() throws DataException {
1761
        checkNotInAppendMode();
1762
        FeatureQuery query =
1763
            new DefaultFeatureQuery(this.getDefaultFeatureType());
1764
        return new DefaultFeatureSet(this, query);
1765
    }
1766

    
1767
    @Override
1768
    public DataSet getDataSet(DataQuery dataQuery) throws DataException {
1769
        checkNotInAppendMode();
1770
        return new DefaultFeatureSet(this, (FeatureQuery) dataQuery);
1771
    }
1772

    
1773
    @Override
1774
    public void getDataSet(Observer observer) throws DataException {
1775
        checkNotInAppendMode();
1776
        this.getFeatureSet(null, observer);
1777
    }
1778

    
1779
    @Override
1780
    public void getDataSet(DataQuery dataQuery, Observer observer)
1781
        throws DataException {
1782
        checkNotInAppendMode();
1783
        this.getFeatureSet((FeatureQuery) dataQuery, observer);
1784
    }
1785

    
1786
    @Override
1787
    public FeatureSet getFeatureSet() throws DataException {
1788
        return this.getFeatureSet((FeatureQuery)null);
1789
    }
1790

    
1791
    @Override
1792
    public FeatureSet getFeatureSet(FeatureQuery featureQuery)
1793
        throws DataException {
1794
        checkNotInAppendMode();
1795
        if( featureQuery==null ) {
1796
            featureQuery = new DefaultFeatureQuery(this.getDefaultFeatureType());
1797
        }
1798
        return new DefaultFeatureSet(this, featureQuery);
1799
    }
1800

    
1801
    @Override
1802
    public FeatureSet getFeatureSet(String filter) throws DataException {
1803
        return this.getFeatureSet(filter, null, true);
1804
    }
1805

    
1806
    @Override
1807
    public FeatureSet getFeatureSet(String filter, String sortBy) throws DataException {
1808
        return this.getFeatureSet(filter, sortBy, true);
1809
    }
1810

    
1811
    @Override
1812
    public FeatureSet getFeatureSet(Expression filter) throws DataException {
1813
        return this.getFeatureSet(filter, null, true);
1814
    }
1815
    
1816
    @Override
1817
    public FeatureSet getFeatureSet(Expression filter, String sortBy) throws DataException {
1818
        return this.getFeatureSet(filter, sortBy, true);
1819
    }
1820
    
1821
    @Override
1822
    public FeatureSet getFeatureSet(Expression filter, String sortBy, boolean asc) throws DataException {
1823
        FeatureQuery query = this.createFeatureQuery();
1824
        if( filter!=null ) {
1825
            query.setFilter(filter);
1826
        }
1827
        if( !StringUtils.isEmpty(sortBy) ) {
1828
            query.getOrder().add(sortBy, asc);
1829
        }
1830
        return this.getFeatureSet(query);
1831
    }
1832
    
1833
    @Override
1834
    public FeatureSet getFeatureSet(String filter, String sortBy, boolean asc) throws DataException {
1835
        FeatureQuery query = this.createFeatureQuery();
1836
        if( !StringUtils.isEmpty(filter) ) {
1837
            query.setFilter(filter);
1838
        }
1839
        if( !StringUtils.isEmpty(sortBy) ) {
1840
            query.getOrder().add(sortBy, asc);
1841
        }
1842
        return this.getFeatureSet(query);
1843
    }
1844
    
1845
    @Override
1846
    public List<Feature> getFeatures(String filter)  {
1847
        return this.getFeatures(filter, null, true);
1848
    }
1849

    
1850
    @Override
1851
    public List<Feature> getFeatures(String filter, String sortBy)  {
1852
        return this.getFeatures(filter, sortBy, true);
1853
    }
1854

    
1855
    @Override
1856
    public List<Feature> getFeatures(String filter, String sortBy, boolean asc)  {
1857
        FeatureQuery query = this.createFeatureQuery();
1858
        if( !StringUtils.isEmpty(filter) ) {
1859
            query.setFilter(filter);
1860
        }
1861
        if( !StringUtils.isEmpty(sortBy) ) {
1862
            query.getOrder().add(sortBy, asc);
1863
        }
1864
        return this.getFeatures(query, 100);
1865
    }
1866
    
1867
    @Override
1868
    public List<Feature> getFeatures(Expression filter)  {
1869
        return this.getFeatures(filter, null, true);
1870
    }
1871

    
1872
    @Override
1873
    public List<Feature> getFeatures(Expression filter, String sortBy)  {
1874
        return this.getFeatures(filter, sortBy, true);
1875
    }
1876

    
1877
    @Override
1878
    public List<Feature> getFeatures(Expression filter, String sortBy, boolean asc)  {
1879
        FeatureQuery query = this.createFeatureQuery();
1880
        if( filter!=null ) {
1881
            query.setFilter(filter);
1882
        }
1883
        if( !StringUtils.isEmpty(sortBy) ) {
1884
            query.getOrder().add(sortBy, asc);
1885
        }
1886
        return this.getFeatures(query, 100);
1887
    }
1888
    
1889
    @Override
1890
    public List<Feature> getFeatures(FeatureQuery query)  {
1891
        return this.getFeatures(query, 100);
1892
    }
1893
    
1894
    @Override
1895
    public List<Feature> getFeatures(FeatureQuery query, int pageSize)  {
1896
        try {
1897
            FeaturePagingHelper pager = this.dataManager.createFeaturePagingHelper(this, query, pageSize);
1898
            return pager.asList();
1899
        } catch (BaseException ex) {
1900
            throw new RuntimeException("Can't create the list of features.", ex);
1901
        }
1902
    }
1903

    
1904
    @Override
1905
    public List<Feature> getFeatures() {
1906
        return this.getFeatures(null, 500);
1907
    }
1908

    
1909
    @Override
1910
    public Feature findFirst(String filter) throws DataException {
1911
        return this.findFirst(filter, null, true);
1912
    }
1913

    
1914
    @Override
1915
    public Feature findFirst(String filter, String sortBy) throws DataException {
1916
        return this.findFirst(filter, sortBy, true);
1917
    }
1918

    
1919
    @Override
1920
    public Feature findFirst(String filter, String sortBy, boolean asc) throws DataException {
1921
        FeatureSet set = this.getFeatureSet(filter, sortBy, asc);
1922
        if( set==null || set.isEmpty() ) {
1923
            return null;
1924
        }
1925
        DisposableIterator it = set.iterator();
1926
        Feature f = (Feature) it.next();
1927
        it.dispose();
1928
        return f;
1929
    }
1930
    
1931
    @Override
1932
    public Feature findFirst(Expression filter) throws DataException {
1933
        return this.findFirst(filter, null, true);
1934
    }
1935

    
1936
    @Override
1937
    public Feature findFirst(Expression filter, String sortBy) throws DataException {
1938
        return this.findFirst(filter, sortBy, true);
1939
    }
1940

    
1941
    @Override
1942
    public Feature findFirst(Expression filter, String sortBy, boolean asc) throws DataException {
1943
        FeatureSet set = this.getFeatureSet(filter, sortBy, asc);
1944
        if( set==null || set.isEmpty() ) {
1945
            return null;
1946
        }
1947
        DisposableIterator it = set.iterator();
1948
        Feature f = (Feature) it.next();
1949
        it.dispose();
1950
        return f;
1951
    }
1952
    
1953
    @Override
1954
    public void accept(Visitor visitor) throws BaseException {
1955
        FeatureSet set = getFeatureSet();
1956
        try {
1957
            set.accept(visitor);
1958
        } finally {
1959
            set.dispose();
1960
        }
1961
    }
1962

    
1963
    @Override
1964
    public void accept(Visitor visitor, DataQuery dataQuery)
1965
        throws BaseException {
1966
        FeatureSet set = getFeatureSet((FeatureQuery) dataQuery);
1967
        try {
1968
            set.accept(visitor);
1969
        } finally {
1970
            set.dispose();
1971
        }
1972
    }
1973

    
1974
    public FeatureType getFeatureType(FeatureQuery featureQuery)
1975
        throws DataException {
1976
        DefaultFeatureType fType =
1977
            (DefaultFeatureType) this.getFeatureType(featureQuery
1978
                .getFeatureTypeId());
1979
        if( featureQuery.hasAttributeNames() || 
1980
            featureQuery.hasConstantsAttributeNames() ||
1981
            fType.hasRequiredFields()    
1982
            ) {
1983
            return fType.getSubtype(featureQuery.getAttributeNames(), featureQuery.getConstantsAttributeNames() );
1984
        }
1985
        return fType;
1986
    }
1987

    
1988
    @Override
1989
    public void getFeatureSet(Observer observer) throws DataException {
1990
        checkNotInAppendMode();
1991
        this.getFeatureSet(null, observer);
1992
    }
1993

    
1994
    @Override
1995
    public void getFeatureSet(FeatureQuery query, Observer observer)
1996
        throws DataException {
1997
        class LoadInBackGround implements Runnable {
1998

    
1999
            private final FeatureStore store;
2000
            private final FeatureQuery query;
2001
            private final Observer observer;
2002

    
2003
            public LoadInBackGround(FeatureStore store, FeatureQuery query,
2004
                Observer observer) {
2005
                this.store = store;
2006
                this.query = query;
2007
                this.observer = observer;
2008
            }
2009

    
2010
            void notify(FeatureStoreNotification theNotification) {
2011
                observer.update(store, theNotification);
2012
            }
2013

    
2014
            @Override
2015
            public void run() {
2016
                FeatureSet set = null;
2017
                try {
2018
                    set = store.getFeatureSet(query);
2019
                    notify(new DefaultFeatureStoreNotification(store,
2020
                        FeatureStoreNotification.LOAD_FINISHED, set));
2021
                } catch (Exception e) {
2022
                    notify(new DefaultFeatureStoreNotification(store,
2023
                        FeatureStoreNotification.LOAD_FINISHED, e));
2024
                } finally {
2025
                    dispose(set);
2026
                }
2027
            }
2028
        }
2029

    
2030
        checkNotInAppendMode();
2031
        if (query == null) {
2032
            query = new DefaultFeatureQuery(this.getDefaultFeatureType());
2033
        }
2034
        LoadInBackGround task = new LoadInBackGround(this, query, observer);
2035
        Thread thread = new Thread(task, "Load Feature Set in background");
2036
        thread.start();
2037
    }
2038

    
2039
    @Override
2040
    public Feature getFeatureByReference(FeatureReference reference)
2041
        throws DataException {
2042
        checkNotInAppendMode();
2043
        DefaultFeatureReference ref = (DefaultFeatureReference) reference;
2044
        FeatureType featureType;
2045
        if (ref.getFeatureTypeId() == null) {
2046
            featureType = this.getDefaultFeatureType();
2047
        } else {
2048
            featureType = this.getFeatureType(ref.getFeatureTypeId());
2049
        }
2050
        return this.getFeatureByReference(reference, featureType);
2051
    }
2052

    
2053
    @Override
2054
    public Feature getFeatureByReference(FeatureReference reference,
2055
        FeatureType featureType) throws DataException {
2056
        checkNotInAppendMode();
2057
        featureType = fixFeatureType((DefaultFeatureType) featureType);
2058
        if (this.mode == MODE_FULLEDIT) {
2059
            Feature f = featureManager.get(reference, this, featureType);
2060
            if (f != null) {
2061
                return f;
2062
            }
2063
        }
2064

    
2065
        FeatureType sourceFeatureType = featureType;
2066
        if (!this.transforms.isEmpty()) {
2067
            sourceFeatureType = this.transforms.getSourceFeatureTypeFrom(featureType);
2068
        }
2069
        // TODO comprobar que el id es de este store
2070

    
2071
        DefaultFeature feature =
2072
            new DefaultFeature(this,
2073
                this.provider.getFeatureProviderByReference(
2074
                    (FeatureReferenceProviderServices) reference, sourceFeatureType));
2075

    
2076
        if (!this.transforms.isEmpty()) {
2077
            return this.transforms.applyTransform(feature, featureType);
2078
        }
2079
        return feature;
2080
    }
2081

    
2082
    //
2083
    // ====================================================================
2084
    // Gestion de features
2085
    //
2086

    
2087
    private FeatureType fixFeatureType(DefaultFeatureType type)
2088
        throws DataException {
2089
        FeatureType original = this.getDefaultFeatureType();
2090

    
2091
        if ((type == null) || type.equals(original)) {
2092
            return original;
2093
        } else {
2094
            if (!type.isSubtypeOf(original)) {
2095
                Iterator iter = this.getFeatureTypes().iterator();
2096
                FeatureType tmpType;
2097
                boolean found = false;
2098
                while (iter.hasNext()) {
2099
                    tmpType = (FeatureType) iter.next();
2100
                    if (type.equals(tmpType)) {
2101
                        return type;
2102

    
2103
                    } else
2104
                        if (type.isSubtypeOf(tmpType)) {
2105
                            found = true;
2106
                            original = tmpType;
2107
                            break;
2108
                        }
2109

    
2110
                }
2111
                if (!found) {
2112
                    throw new IllegalFeatureTypeException(getName());
2113
                }
2114
            }
2115
        }
2116

    
2117
        // Checks that type has all fields of pk
2118
        // else add the missing attributes at the end.
2119
        if (!original.hasOID()) {
2120
            // Gets original pk attributes
2121
            DefaultEditableFeatureType edOriginal =
2122
                (DefaultEditableFeatureType) original.getEditable();
2123
            FeatureAttributeDescriptor orgAttr;
2124
            Iterator edOriginalIter = edOriginal.iterator();
2125
            while (edOriginalIter.hasNext()) {
2126
                orgAttr = (FeatureAttributeDescriptor) edOriginalIter.next();
2127
                if (!orgAttr.isPrimaryKey()) {
2128
                    edOriginalIter.remove();
2129
                }
2130
            }
2131

    
2132
            // Checks if all pk attributes are in type
2133
            Iterator typeIterator;
2134
            edOriginalIter = edOriginal.iterator();
2135
            FeatureAttributeDescriptor attr;
2136
            while (edOriginalIter.hasNext()) {
2137
                orgAttr = (FeatureAttributeDescriptor) edOriginalIter.next();
2138
                typeIterator = type.iterator();
2139
                while (typeIterator.hasNext()) {
2140
                    attr = (FeatureAttributeDescriptor) typeIterator.next();
2141
                    if (attr.getName().equals(orgAttr.getName())) {
2142
                        edOriginalIter.remove();
2143
                        break;
2144
                    }
2145
                }
2146
            }
2147

    
2148
            // add missing pk attributes if any
2149
            if (edOriginal.size() > 0) {
2150
                boolean isEditable = type instanceof DefaultEditableFeatureType;
2151
                DefaultEditableFeatureType edType =
2152
                    (DefaultEditableFeatureType) original.getEditable();
2153
                edType.clear();
2154
                edType.addAll(type);
2155
                edType.addAll(edOriginal);
2156
                if (!isEditable) {
2157
                    type = (DefaultFeatureType) edType.getNotEditableCopy();
2158
                }
2159
            }
2160

    
2161
        }
2162

    
2163
        return type;
2164
    }
2165

    
2166
    @Override
2167
    public void validateFeatures(int mode) throws DataException {
2168
        FeatureSet collection = null;
2169
        DisposableIterator iter = null;
2170
        try {
2171
            FeatureRules rules = this.getDefaultFeatureType().getRules();
2172
            if( rules==null || rules.isEmpty() ) {
2173
                return;
2174
            }
2175
            checkNotInAppendMode();
2176
            collection = this.getFeatureSet();
2177
            iter = collection.fastIterator();
2178
            long previousVersionOfUpdate = currentVersionOfUpdate();
2179
            while (iter.hasNext()) {
2180
                ((DefaultFeature) iter.next()).validate(mode);
2181
                if (previousVersionOfUpdate != currentVersionOfUpdate()) {
2182
                    throw new ConcurrentDataModificationException(getName());
2183
                }
2184
            }
2185
        } catch (Exception e) {
2186
            throw new ValidateFeaturesException(e, getName());
2187
        } finally {
2188
            DisposeUtils.disposeQuietly(iter);
2189
            DisposeUtils.disposeQuietly(collection);
2190
        }
2191
    }
2192

    
2193
    @Override
2194
    public FeatureType getDefaultFeatureType() throws DataException {
2195
        try {
2196

    
2197
            if (isEditing()) {
2198
                FeatureType auxFeatureType =
2199
                    featureTypeManager.getType(defaultFeatureType.getId());
2200
                if (auxFeatureType != null) {
2201
                    return avoidEditable(auxFeatureType);
2202
                }
2203
            }
2204
            FeatureType type = this.transforms.getDefaultFeatureType();
2205
                if (type != null) {
2206
                return avoidEditable(type);
2207
                }
2208

    
2209
            return avoidEditable(defaultFeatureType);
2210

    
2211
        } catch (Exception e) {
2212
            throw new GetFeatureTypeException(e, getName());
2213
        }
2214
    }
2215

    
2216
    private FeatureType avoidEditable(FeatureType ft) {
2217
        if (ft instanceof EditableFeatureType) {
2218
            return ((EditableFeatureType) ft).getNotEditableCopy();
2219
        } else {
2220
            return ft;
2221
        }
2222
    }
2223

    
2224
    @Override
2225
    public FeatureType getFeatureType(String featureTypeId)
2226
        throws DataException {
2227
        if (featureTypeId == null) {
2228
            return this.getDefaultFeatureType();
2229
        }
2230
        try {
2231
            if (isEditing()) {
2232
                FeatureType auxFeatureType =
2233
                    featureTypeManager.getType(featureTypeId);
2234
                if (auxFeatureType != null) {
2235
                    return auxFeatureType;
2236
                }
2237
            }
2238
            FeatureType type = this.transforms.getFeatureType(featureTypeId);
2239
            if (type != null) {
2240
                return type;
2241
            }
2242
            Iterator iter = this.featureTypes.iterator();
2243
            while (iter.hasNext()) {
2244
                type = (FeatureType) iter.next();
2245
                if (type.getId().equals(featureTypeId)) {
2246
                    return type;
2247
                }
2248
            }
2249
            return null;
2250
        } catch (Exception e) {
2251
            throw new GetFeatureTypeException(e, getName());
2252
        }
2253
    }
2254

    
2255
    public FeatureType getProviderDefaultFeatureType() {
2256
        return defaultFeatureType;
2257
    }
2258

    
2259
    @Override
2260
    public List getFeatureTypes() throws DataException {
2261
        try {
2262
            List types;
2263
            if (isEditing()) {
2264
                types = new ArrayList();
2265
                Iterator it = featureTypes.iterator();
2266
                while (it.hasNext()) {
2267
                    FeatureType type = (FeatureType) it.next();
2268
                    FeatureType typeaux =
2269
                        featureTypeManager.getType(type.getId());
2270
                    if (typeaux != null) {
2271
                        types.add(typeaux);
2272
                    } else {
2273
                        types.add(type);
2274
                    }
2275
                }
2276
                it = featureTypeManager.newsIterator();
2277
                while (it.hasNext()) {
2278
                    FeatureType type = (FeatureType) it.next();
2279
                    types.add(type);
2280
                }
2281
            } else {
2282
                types = this.transforms.getFeatureTypes();
2283
                if (types == null) {
2284
                    types = featureTypes;
2285
                }
2286
            }
2287
            return Collections.unmodifiableList(types);
2288
        } catch (Exception e) {
2289
            throw new GetFeatureTypeException(e, getName());
2290
        }
2291
    }
2292

    
2293
    public List getProviderFeatureTypes() throws DataException {
2294
        return Collections.unmodifiableList(this.featureTypes);
2295
    }
2296

    
2297
    @Override
2298
    public Feature createFeature(FeatureProvider data) throws DataException {
2299
        DefaultFeature feature = new DefaultFeature(this, data);
2300
        return feature;
2301
    }
2302

    
2303
    public Feature createFeature(FeatureProvider data, FeatureType type)
2304
        throws DataException {
2305
        // FIXME: falta por implementar
2306
        // Comprobar si es un subtipo del feature de data
2307
        // y construir un feature usando el subtipo.
2308
        // Probablemente requiera generar una copia del data.
2309
        throw new NotYetImplemented();
2310
    }
2311

    
2312
    @Override
2313
    public EditableFeature createNewFeature(FeatureType type,
2314
        Feature defaultValues) throws DataException {
2315
        try {
2316
            FeatureProvider data = createNewFeatureProvider(type);
2317
            DefaultEditableFeature feature =
2318
                new DefaultEditableFeature(this, data);
2319
            feature.initializeValues(defaultValues);
2320
            data.setNew(true);
2321

    
2322
            return feature;
2323
        } catch (Exception e) {
2324
            throw new CreateFeatureException(e, getName());
2325
        }
2326
    }
2327

    
2328
    private FeatureProvider createNewFeatureProvider(FeatureType type)
2329
        throws DataException {
2330
        type = this.fixFeatureType((DefaultFeatureType) type);
2331
        FeatureProvider data = this.provider.createFeatureProvider(type);
2332
        data.setNew(true);
2333
        if (type.hasOID() && (data.getOID() == null)) {
2334
            data.setOID(this.provider.createNewOID());
2335
        } else {
2336
            data.setOID(this.getTemporalOID());
2337
        }
2338
        return data;
2339

    
2340
    }
2341

    
2342
    @Override
2343
    public EditableFeature createNewFeature(FeatureType type,
2344
        boolean defaultValues) throws DataException {
2345
        try {
2346
            FeatureProvider data = createNewFeatureProvider(type);
2347
            DefaultEditableFeature feature =
2348
                new DefaultEditableFeature(this, data);
2349
            if (defaultValues) {
2350
                feature.initializeValues();
2351
            }
2352
            return feature;
2353
        } catch (Exception e) {
2354
            throw new CreateFeatureException(e, getName());
2355
        }
2356
    }
2357

    
2358
    @Override
2359
    public EditableFeature createNewFeature(boolean defaultValues)
2360
        throws DataException {
2361
        return this.createNewFeature(this.getDefaultFeatureType(),
2362
            defaultValues);
2363
    }
2364

    
2365
    @Override
2366
    public EditableFeature createNewFeature() throws DataException {
2367
        return this.createNewFeature(this.getDefaultFeatureType(), true);
2368
    }
2369

    
2370
    @Override
2371
    public EditableFeature createNewFeature(Feature defaultValues) throws DataException {
2372
        FeatureType ft = this.getDefaultFeatureType();
2373
        EditableFeature f = this.createNewFeature(ft, false);
2374
                for( FeatureAttributeDescriptor desc : ft ) {
2375
                        try {
2376
                                f.set(desc.getName(), defaultValues.get(desc.getName()));
2377
                        } catch(Throwable th) {
2378
                                // Ignore
2379
                        }
2380
                }
2381
        return f;
2382
    }
2383

    
2384
    @Override
2385
    public EditableFeatureType createFeatureType() {
2386
        EditableFeatureType ftype = new DefaultEditableFeatureType(this);
2387
        return ftype;
2388
    }
2389

    
2390
    @Override
2391
    public EditableFeatureType createFeatureType(String id) {
2392
        DefaultEditableFeatureType ftype = new DefaultEditableFeatureType(this, id);
2393
        return ftype;
2394
    }
2395

    
2396
    //
2397
    // ====================================================================
2398
    // Index related methods
2399
    //
2400

    
2401
    @Override
2402
    public FeatureIndexes getIndexes() {
2403
        return this.indexes;
2404
    }
2405

    
2406
    @Override
2407
    public FeatureIndex createIndex(FeatureType featureType,
2408
        String attributeName, String indexName) throws DataException {
2409
        return createIndex(null, featureType, attributeName, indexName);
2410
    }
2411

    
2412
    @Override
2413
    public FeatureIndex createIndex(String indexTypeName,
2414
        FeatureType featureType, String attributeName, String indexName)
2415
        throws DataException {
2416

    
2417
        return createIndex(indexTypeName, featureType, attributeName,
2418
            indexName, false, null);
2419
    }
2420

    
2421
    @Override
2422
    public FeatureIndex createIndex(FeatureType featureType,
2423
        String attributeName, String indexName, Observer observer)
2424
        throws DataException {
2425
        return createIndex(null, featureType, attributeName, indexName,
2426
            observer);
2427
    }
2428

    
2429
    @Override
2430
    public FeatureIndex createIndex(String indexTypeName,
2431
        FeatureType featureType, String attributeName, String indexName,
2432
        final Observer observer) throws DataException {
2433

    
2434
        return createIndex(indexTypeName, featureType, attributeName,
2435
            indexName, true, observer);
2436
    }
2437

    
2438
    private FeatureIndex createIndex(String indexTypeName,
2439
        FeatureType featureType, String attributeName, String indexName,
2440
        boolean background, final Observer observer) throws DataException {
2441

    
2442
        checkNotInAppendMode();
2443
        FeatureIndexProviderServices index;
2444
        index = dataManager.createFeatureIndexProvider(indexTypeName, this,
2445
                featureType, indexName,
2446
                featureType.getAttributeDescriptor(attributeName));
2447

    
2448
        try {
2449
            index.fill(background, observer);
2450
        } catch (FeatureIndexException e) {
2451
            throw new InitializeException(index.getName(), e);
2452
        }
2453

    
2454
        ((DefaultFeatureIndexes) getIndexes()).addIndex(index);
2455
        return index;
2456
    }
2457

    
2458
    //
2459
    // ====================================================================
2460
    // Transforms related methods
2461
    //
2462

    
2463
    @Override
2464
    public FeatureStoreTransforms getTransforms() {
2465
        return this.transforms;
2466
    }
2467

    
2468
    @Override
2469
    public FeatureQuery createFeatureQuery() {
2470
        return new DefaultFeatureQuery();
2471
    }
2472

    
2473
    @Override
2474
    public DataQuery createQuery() {
2475
        return createFeatureQuery();
2476
    }
2477

    
2478
    //
2479
    // ====================================================================
2480
    // UndoRedo related methods
2481
    //
2482

    
2483
    @Override
2484
    public boolean canRedo() {
2485
        return commands.canRedo();
2486
    }
2487

    
2488
    @Override
2489
    public boolean canUndo() {
2490
        return commands.canUndo();
2491
    }
2492

    
2493
    @Override
2494
    public void redo(int num) throws RedoException {
2495
        for (int i = 0; i < num; i++) {
2496
            redo();
2497
        }
2498
    }
2499

    
2500
    @Override
2501
    public void undo(int num) throws UndoException {
2502
        for (int i = 0; i < num; i++) {
2503
            undo();
2504
        }
2505
    }
2506

    
2507
    //
2508
    // ====================================================================
2509
    // Metadata related methods
2510
    //
2511

    
2512
    @Override
2513
    public Object getMetadataID() {
2514
        return this.provider.getSourceId();
2515
    }
2516

    
2517
    @Override
2518
    public void delegate(DynObject dynObject) {
2519
        this.metadata.delegate(dynObject);
2520
    }
2521

    
2522
    @Override
2523
    public DynClass getDynClass() {
2524
        return this.metadata.getDynClass();
2525
    }
2526

    
2527
    @Override
2528
        public Object getDynValue(String name) throws DynFieldNotFoundException {
2529
                if( this.transforms.hasDynValue(name) ) {
2530
                        return this.transforms.getDynValue(name);
2531
                }
2532
                if (this.metadata.hasDynValue(name)) {
2533
                        return this.metadata.getDynValue(name);
2534
                }
2535
                if (METADATA_PROVIDER.equalsIgnoreCase(name)) {
2536
                        return this.provider.getProviderName();
2537
                } else if (METADATA_CONTAINERNAME.equalsIgnoreCase(name)) {
2538
                        return this.provider.getSourceId();
2539
                } else if (METADATA_FEATURETYPE.equalsIgnoreCase(name)) {
2540
                        try {
2541
                                return this.getDefaultFeatureType();
2542
                        } catch (DataException e) {
2543
                                return null;
2544
                        }
2545
                }
2546
                return this.metadata.getDynValue(name);
2547
        }
2548

    
2549
    @Override
2550
    public boolean hasDynValue(String name) {
2551
                if( this.transforms.hasDynValue(name) ) {
2552
                        return true;
2553
                }
2554
        return this.metadata.hasDynValue(name);
2555
    }
2556

    
2557
    @Override
2558
    public boolean hasDynMethod(String name) {
2559
        return ((DynObject_v2)this.metadata).hasDynMethod(name);
2560
    }
2561

    
2562
    @Override
2563
    public void implement(DynClass dynClass) {
2564
        this.metadata.implement(dynClass);
2565
    }
2566

    
2567
    @Override
2568
    public Object invokeDynMethod(String name, Object[] args)
2569
        throws DynMethodException {
2570
        return this.metadata.invokeDynMethod(this, name, args);
2571
    }
2572

    
2573
    @Override
2574
    public Object invokeDynMethod(int code, Object[] args)
2575
        throws DynMethodException {
2576
        return this.metadata.invokeDynMethod(this, code, args);
2577
    }
2578

    
2579
    @Override
2580
    public void setDynValue(String name, Object value)
2581
        throws DynFieldNotFoundException {
2582
                if( this.transforms.hasDynValue(name) ) {
2583
                        this.transforms.setDynValue(name, value);
2584
                        return;
2585
                }
2586
        this.metadata.setDynValue(name, value);
2587

    
2588
    }
2589

    
2590
    /*
2591
     * (non-Javadoc)
2592
     *
2593
     * @see org.gvsig.metadata.Metadata#getMetadataChildren()
2594
     */
2595
    @Override
2596
    public Set getMetadataChildren() {
2597
        return this.metadataChildren;
2598
    }
2599

    
2600
    /*
2601
     * (non-Javadoc)
2602
     *
2603
     * @see org.gvsig.metadata.Metadata#getMetadataName()
2604
     */
2605
    @Override
2606
    public String getMetadataName() {
2607
        return this.provider.getProviderName();
2608
    }
2609

    
2610
    public FeatureTypeManager getFeatureTypeManager() {
2611
        return this.featureTypeManager;
2612
    }
2613

    
2614
    @Override
2615
    public long getFeatureCount() throws DataException {
2616
        if (featureCount == null) {
2617
            featureCount = this.provider.getFeatureCount();
2618
        }
2619
        if (this.isEditing()) {
2620
            if(this.isAppending()) {
2621
                try{
2622
                    throw new IllegalStateException();
2623
                } catch(IllegalStateException e) {
2624
                    LOG.info("Call DefaultFeatureStore.getFeatureCount editing in mode APPEND",e);
2625
                }
2626
                return -1;
2627
            } else {
2628
                return featureCount
2629
                    + this.featureManager.getDeltaSize();
2630
            }
2631
        }
2632
        return featureCount;
2633
    }
2634

    
2635
    private Long getTemporalOID() {
2636
        return this.temporalOid++;
2637
    }
2638

    
2639
    @Override
2640
    public FeatureType getProviderFeatureType(String featureTypeId) {
2641
        if (featureTypeId == null) {
2642
            return this.defaultFeatureType;
2643
        }
2644
        FeatureType type;
2645
        Iterator iter = this.featureTypes.iterator();
2646
        while (iter.hasNext()) {
2647
            type = (FeatureType) iter.next();
2648
            if (type.getId().equals(featureTypeId)) {
2649
                return type;
2650
            }
2651
        }
2652
        return null;
2653
    }
2654

    
2655
    @Override
2656
    public FeatureProvider getFeatureProviderFromFeature(Feature feature) {
2657
        return ((DefaultFeature) feature).getData();
2658
    }
2659

    
2660
    @Override
2661
    public DataStore getStore() {
2662
        return this;
2663
    }
2664

    
2665
    @Override
2666
    public FeatureStore getFeatureStore() {
2667
        return this;
2668
    }
2669

    
2670
    @Override
2671
    public void createCache(String name, DynObject parameters)
2672
        throws DataException {
2673
        cache = dataManager.createFeatureCacheProvider(name, parameters);
2674
        if (cache == null) {
2675
            throw new CreateException("FeaureCacheProvider", null);
2676
        }
2677
        cache.apply(this, provider);
2678
        provider = cache;
2679

    
2680
        featureCount = null;
2681
    }
2682

    
2683
    @Override
2684
    public FeatureCache getCache() {
2685
        return cache;
2686
    }
2687

    
2688
    @Override
2689
    public void clear() {
2690
        if (metadata != null) {
2691
            metadata.clear();
2692
        }
2693
    }
2694

    
2695
    @Override
2696
    public String getName() {
2697
        if( this.provider != null ) {
2698
            return this.provider.getName();
2699
        }
2700
        if( this.parameters instanceof HasAFile ) {
2701
            return FilenameUtils.getName(((HasAFile)this.parameters).getFile().getName());
2702
        }
2703
        return "unknow";
2704
    }
2705

    
2706
    @Override
2707
    public String getFullName() {
2708
        try {
2709
            if( this.provider!=null ) {
2710
                return this.provider.getFullName();
2711
            }
2712
            if( this.parameters instanceof HasAFile ) {
2713
                return (((HasAFile)this.parameters).getFile().getAbsolutePath());
2714
            }
2715
            return null;
2716
        } catch(Throwable th) {
2717
            return null;
2718
        }
2719
    }
2720

    
2721
    @Override
2722
    public String getProviderName() {
2723
        if( this.provider!=null ) {
2724
            return this.provider.getProviderName();
2725
        }
2726
        if( this.parameters != null ) {
2727
            return this.parameters.getDataStoreName();
2728
        }
2729
        return null;
2730

    
2731
    }
2732

    
2733
    @Override
2734
    public boolean isKnownEnvelope() {
2735
        return this.provider.isKnownEnvelope();
2736
    }
2737

    
2738
    @Override
2739
    public boolean hasRetrievedFeaturesLimit() {
2740
        return this.provider.hasRetrievedFeaturesLimit();
2741
    }
2742

    
2743
    @Override
2744
    public int getRetrievedFeaturesLimit() {
2745
        return this.provider.getRetrievedFeaturesLimit();
2746
    }
2747

    
2748
    @Override
2749
    public Interval getInterval() {
2750
        if( this.timeSupport!=null ) {
2751
            return this.timeSupport.getInterval();
2752
        }
2753
        return this.provider.getInterval();
2754
    }
2755

    
2756
    @Override
2757
    public Collection getTimes() {
2758
        if( this.timeSupport!=null ) {
2759
            return this.timeSupport.getTimes();
2760
        }
2761
        return this.provider.getTimes();
2762
    }
2763

    
2764
    @Override
2765
    public Collection getTimes(Interval interval) {
2766
        if( this.timeSupport!=null ) {
2767
            return this.timeSupport.getTimes(interval);
2768
        }
2769
        return this.provider.getTimes(interval);
2770
    }
2771

    
2772
    public void setTimeSupport(FeatureStoreTimeSupport timeSupport) {
2773
        if( this.isEditing() ) {
2774
            throw new RuntimeException("Can't add time support over attribute '"+timeSupport.getAttributeName()+"' while store is editing.");
2775
        }
2776
        if( !this.transforms.isEmpty() ) {
2777
            throw new RuntimeException("Can't add time support over attribute '"+timeSupport.getAttributeName()+"' if has transforms.");
2778
        }
2779
        FeatureType ft = this.defaultFeatureType;
2780
        FeatureAttributeDescriptor attr = ft.getAttributeDescriptor(timeSupport.getRequiredFieldNames()[0]);
2781
        if( attr == null ) {
2782
            throw new RuntimeException("Can't add time support over attribute '"+timeSupport.getAttributeName()+"', this attribute don't exists.");
2783
        }
2784
        EditableFeatureType eft = ft.getEditable();
2785
        attr = eft.getAttributeDescriptor(timeSupport.getAttributeName());
2786
        if( attr != null ) {
2787
            if( !(attr.getFeatureAttributeEmulator() instanceof FeatureStoreTimeSupport) ) {
2788
                throw new RuntimeException("Can't add time support, attribute '"+timeSupport.getAttributeName()+"'already exists.");
2789
            }
2790
            eft.remove(attr.getName());
2791
        }
2792
        EditableFeatureAttributeDescriptor attrTime = eft.add(
2793
            timeSupport.getAttributeName(), 
2794
            timeSupport.getDataType()
2795
        );
2796
        attrTime.setIsTime(true);
2797
        attrTime.setFeatureAttributeEmulator(timeSupport);
2798
        eft.setDefaultTimeAttributeName(timeSupport.getAttributeName());
2799
        this.defaultFeatureType = eft.getNotEditableCopy();
2800
        
2801
        this.timeSupport = timeSupport;
2802
    }
2803

    
2804
    @Override
2805
    @SuppressWarnings("CloneDoesntCallSuperClone")
2806
    public Object clone() throws CloneNotSupportedException {
2807

    
2808
        DataStoreParameters dsp = getParameters();
2809

    
2810
        DefaultFeatureStore cloned_store = null;
2811

    
2812
        try {
2813
            cloned_store = (DefaultFeatureStore) DALLocator.getDataManager().
2814
                openStore(this.getProviderName(), dsp);
2815
            if (transforms != null) {
2816
                cloned_store.transforms = (DefaultFeatureStoreTransforms) transforms.clone();
2817
                cloned_store.transforms.setStoreForClone(cloned_store);
2818
            }
2819
        } catch (Exception e) {
2820
            throw new CloneException(e);
2821
        }
2822
        return cloned_store;
2823

    
2824
    }
2825

    
2826
    @Override
2827
    public Feature getFeature(DynObject dynobject) {
2828
        if (dynobject instanceof DynObjectFeatureFacade){
2829
            Feature f = ((DynObjectFeatureFacade)dynobject).getFeature();
2830
            return f;
2831
        }
2832
        return null;
2833
    }
2834

    
2835
    @Override
2836
    public Iterator iterator() {
2837
        try {
2838
            return this.getFeatureSet().fastIterator();
2839
        } catch (DataException ex) {
2840
            throw new RuntimeException(ex);
2841
        }
2842
    }
2843

    
2844
    @Override
2845
    public ExpressionBuilder createExpressionBuilder() {
2846
        if( this.provider instanceof FeatureStoreProvider_v2 ) {
2847
            return ((FeatureStoreProvider_v2)this.provider).createExpression();
2848
        }
2849
        return new SQLBuilderBase();
2850
    }
2851

    
2852
    @Override
2853
    public ExpressionBuilder createExpression() {
2854
        return createExpressionBuilder();
2855
    }
2856

    
2857
    public FeatureSet features() throws DataException {
2858
        // This is to avoid jython to create a property with this name
2859
        // to access method getFeatures.
2860
        return this.getFeatureSet();
2861
    }
2862

    
2863
    @Override
2864
    public DataStoreProviderFactory getProviderFactory() {
2865
        DataStoreProviderFactory factory = dataManager.getStoreProviderFactory(parameters.getDataStoreName());
2866
        return factory;
2867
    }
2868

    
2869
    @Override
2870
    public void useCache(String providerName, DynObject parameters) throws DataException {
2871
        throw new UnsupportedOperationException();
2872
    }
2873

    
2874
    @Override
2875
    public boolean isBroken() {
2876
        return this.state.isBroken();
2877
    }
2878

    
2879
    @Override
2880
    public Throwable getBreakingsCause() {
2881
            return this.state.getBreakingsCause();
2882
    }
2883

    
2884
    @Override
2885
    public SpatialIndex wrapSpatialIndex(SpatialIndex index) {
2886
      FeatureStoreProviderFactory factory = (FeatureStoreProviderFactory) this.getProviderFactory();
2887
      if( !factory.supportNumericOID() ) {
2888
          return null;
2889
      }
2890
      SpatialIndex wrappedIndex = new WrappedSpatialIndex(index, this);
2891
      return wrappedIndex;
2892
  }
2893

    
2894
    @Override
2895
    public FeatureReference getFeatureReference(String code) {
2896
        FeatureReference featureReference = new DefaultFeatureReference(this, code);
2897
        return featureReference;
2898
    }
2899
}