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

History | View | Annotate | Download (144 KB)

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

    
26
import java.util.ArrayList;
27
import java.util.Collection;
28
import java.util.Collections;
29
import java.util.HashMap;
30
import java.util.HashSet;
31
import java.util.Iterator;
32
import java.util.List;
33
import java.util.Map;
34
import java.util.Map.Entry;
35
import java.util.Objects;
36
import java.util.Set;
37
import java.util.UUID;
38
import javax.json.JsonObject;
39
import org.apache.commons.io.FilenameUtils;
40
import org.apache.commons.io.IOUtils;
41
import org.apache.commons.lang3.StringUtils;
42
import org.apache.commons.lang3.builder.ToStringBuilder;
43
import org.apache.commons.lang3.mutable.MutableObject;
44
import org.cresques.cts.IProjection;
45
import org.gvsig.expressionevaluator.Expression;
46
import org.gvsig.expressionevaluator.ExpressionBuilder;
47
import org.gvsig.expressionevaluator.ExpressionUtils;
48
import org.gvsig.expressionevaluator.GeometryExpressionUtils;
49
import org.gvsig.fmap.dal.BaseStoresRepository;
50
import org.gvsig.fmap.dal.DALLocator;
51
import org.gvsig.fmap.dal.DataManager;
52
import static org.gvsig.fmap.dal.DataManager.DAL_STORE_ENVELOPE;
53
import static org.gvsig.fmap.dal.DataManager.DAL_USE_LARGE_SELECTION;
54
import org.gvsig.fmap.dal.DataQuery;
55
import org.gvsig.fmap.dal.DataServerExplorer;
56
import org.gvsig.fmap.dal.DataSet;
57
import org.gvsig.fmap.dal.DataStore;
58
import org.gvsig.fmap.dal.DataStoreNotification;
59
import org.gvsig.fmap.dal.DataStoreParameters;
60
import org.gvsig.fmap.dal.DataStoreProviderFactory;
61
import org.gvsig.fmap.dal.DataTransaction;
62
import org.gvsig.fmap.dal.DataTypes;
63
import org.gvsig.fmap.dal.DatabaseWorkspaceManager;
64
import org.gvsig.fmap.dal.StoresRepository;
65
import org.gvsig.fmap.dal.SupportTransactions;
66
import org.gvsig.fmap.dal.exception.CloneException;
67
import org.gvsig.fmap.dal.exception.CloseException;
68
import org.gvsig.fmap.dal.exception.CreateException;
69
import org.gvsig.fmap.dal.exception.DataException;
70
import org.gvsig.fmap.dal.exception.DataRuntimeException;
71
import org.gvsig.fmap.dal.exception.InitializeException;
72
import org.gvsig.fmap.dal.exception.OpenException;
73
import org.gvsig.fmap.dal.exception.ReadException;
74
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
75
import org.gvsig.fmap.dal.exception.WriteException;
76
import org.gvsig.fmap.dal.feature.DisposableFeatureSetIterable;
77
import org.gvsig.fmap.dal.feature.EditableFeature;
78
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
79
import org.gvsig.fmap.dal.feature.EditableFeatureType;
80
import org.gvsig.fmap.dal.feature.Feature;
81
import static org.gvsig.fmap.dal.feature.Feature.CHECK_BASIC;
82
import static org.gvsig.fmap.dal.feature.Feature.CHECK_REQUIREDS;
83
import static org.gvsig.fmap.dal.feature.Feature.CHECK_RULES_AT_EDITING;
84
import static org.gvsig.fmap.dal.feature.Feature.CHECK_RULES_AT_FINISH;
85
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
86
import org.gvsig.fmap.dal.feature.FeatureAttributeEmulator;
87
import org.gvsig.fmap.dal.feature.FeatureCache;
88
import org.gvsig.fmap.dal.feature.FeatureIndex;
89
import org.gvsig.fmap.dal.feature.FeatureIndexes;
90
import org.gvsig.fmap.dal.feature.FeatureLocks;
91
import org.gvsig.fmap.dal.feature.FeatureQuery;
92
import org.gvsig.fmap.dal.feature.FeatureReference;
93
import org.gvsig.fmap.dal.feature.FeatureReferenceSelection;
94
import org.gvsig.fmap.dal.feature.FeatureSelection;
95
import org.gvsig.fmap.dal.feature.FeatureSet;
96
import org.gvsig.fmap.dal.feature.FeatureStore;
97
import org.gvsig.fmap.dal.feature.FeatureStoreNotification;
98
import org.gvsig.fmap.dal.feature.FeatureStoreProviderFactory;
99
import org.gvsig.fmap.dal.feature.FeatureStoreTimeSupport;
100
import org.gvsig.fmap.dal.feature.FeatureStoreTransform;
101
import org.gvsig.fmap.dal.feature.FeatureStoreTransforms;
102
import org.gvsig.fmap.dal.feature.FeatureType;
103
import org.gvsig.fmap.dal.feature.FeatureType.FeatureTypeChanged;
104
import org.gvsig.fmap.dal.feature.NewFeatureStoreParameters;
105
import org.gvsig.fmap.dal.feature.exception.AlreadyEditingException;
106
import org.gvsig.fmap.dal.feature.exception.CreateFeatureException;
107
import org.gvsig.fmap.dal.feature.exception.DataExportException;
108
import org.gvsig.fmap.dal.feature.exception.FeatureIndexException;
109
import org.gvsig.fmap.dal.feature.exception.FinishEditingException;
110
import org.gvsig.fmap.dal.feature.exception.GetFeatureTypeException;
111
import org.gvsig.fmap.dal.feature.exception.IllegalFeatureException;
112
import org.gvsig.fmap.dal.feature.exception.IllegalFeatureTypeException;
113
import org.gvsig.fmap.dal.feature.exception.NeedEditingModeException;
114
import org.gvsig.fmap.dal.feature.exception.NoNewFeatureInsertException;
115
import org.gvsig.fmap.dal.feature.exception.NullFeatureTypeException;
116
import org.gvsig.fmap.dal.feature.exception.PerformEditingException;
117
import org.gvsig.fmap.dal.feature.exception.PersistenceCantFindFeatureTypeException;
118
import org.gvsig.fmap.dal.feature.exception.PersistenceStoreAlreadyLoadedException;
119
import org.gvsig.fmap.dal.feature.exception.SelectionNotAllowedException;
120
import org.gvsig.fmap.dal.feature.exception.StoreCancelEditingException;
121
import org.gvsig.fmap.dal.feature.exception.StoreDeleteEditableFeatureException;
122
import org.gvsig.fmap.dal.feature.exception.StoreDeleteFeatureException;
123
import org.gvsig.fmap.dal.feature.exception.StoreEditException;
124
import org.gvsig.fmap.dal.feature.exception.StoreInsertFeatureException;
125
import org.gvsig.fmap.dal.feature.exception.StoreUpdateFeatureException;
126
import org.gvsig.fmap.dal.feature.exception.StoreUpdateFeatureTypeException;
127
import org.gvsig.fmap.dal.feature.exception.ValidateFeaturesException;
128
import org.gvsig.fmap.dal.feature.exception.WriteNotAllowedException;
129
import org.gvsig.fmap.dal.feature.impl.dynobjectutils.DynObjectFeatureFacade;
130
import org.gvsig.fmap.dal.feature.impl.editing.memory.FeatureManager;
131
import org.gvsig.fmap.dal.feature.impl.editing.memory.FeatureTypeManager;
132
import org.gvsig.fmap.dal.feature.impl.editing.memory.SpatialManager;
133
import org.gvsig.fmap.dal.feature.impl.featurereference.FeatureReferenceFactory;
134
import org.gvsig.fmap.dal.feature.impl.featurereference.FeatureReferenceIteratorToFeatureIterator;
135
import org.gvsig.fmap.dal.feature.impl.featureset.DefaultFeatureSet;
136
import org.gvsig.fmap.dal.feature.impl.undo.DefaultFeatureCommandsStack;
137
import org.gvsig.fmap.dal.feature.impl.undo.FeatureCommandsStack;
138
import org.gvsig.fmap.dal.feature.paging.FeaturePagingHelper;
139
import org.gvsig.fmap.dal.feature.spi.DefaultFeatureProvider;
140
import org.gvsig.fmap.dal.feature.spi.FeatureProvider;
141
import org.gvsig.fmap.dal.feature.spi.FeatureReferenceProviderServices;
142
import org.gvsig.fmap.dal.feature.spi.FeatureStoreProvider;
143
import org.gvsig.fmap.dal.feature.spi.FeatureStoreProviderServices;
144
import org.gvsig.fmap.dal.feature.spi.cache.FeatureCacheProvider;
145
import org.gvsig.fmap.dal.feature.spi.index.FeatureIndexProviderServices;
146
import org.gvsig.fmap.dal.impl.DefaultDataManager;
147
import org.gvsig.fmap.dal.resource.Resource;
148
import org.gvsig.fmap.dal.spi.AbstractDataStore;
149
import org.gvsig.fmap.dal.spi.DataStoreInitializer2;
150
import org.gvsig.fmap.dal.spi.DataStoreProvider;
151
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
152
import org.gvsig.fmap.dal.spi.DataTransactionServices;
153
import org.gvsig.fmap.geom.Geometry;
154
import org.gvsig.fmap.geom.GeometryUtils;
155
import org.gvsig.fmap.geom.SpatialIndex;
156
import org.gvsig.fmap.geom.primitive.Envelope;
157
import org.gvsig.metadata.MetadataLocator;
158
import org.gvsig.metadata.MetadataManager;
159
import org.gvsig.metadata.exceptions.MetadataException;
160
import org.gvsig.timesupport.Interval;
161
import org.gvsig.tools.ToolsLocator;
162
import org.gvsig.tools.dispose.DisposableIterator;
163
import org.gvsig.tools.dispose.DisposeUtils;
164
import org.gvsig.tools.dynobject.DelegatedDynObject;
165
import org.gvsig.tools.dynobject.DynClass;
166
import org.gvsig.tools.dynobject.DynObject;
167
import org.gvsig.tools.dynobject.DynObjectManager;
168
import org.gvsig.tools.dynobject.DynObject_v2;
169
import org.gvsig.tools.dynobject.DynStruct;
170
import org.gvsig.tools.dynobject.Tags;
171
import org.gvsig.tools.dynobject.exception.DynFieldNotFoundException;
172
import org.gvsig.tools.dynobject.exception.DynMethodException;
173
import org.gvsig.tools.exception.BaseException;
174
import org.gvsig.tools.exception.NotYetImplemented;
175
import org.gvsig.tools.identitymanagement.SimpleIdentityManager;
176
import org.gvsig.tools.observer.BaseNotification;
177
import org.gvsig.tools.observer.Observable;
178
import org.gvsig.tools.observer.Observer;
179
import org.gvsig.tools.observer.impl.DelegateWeakReferencingObservable;
180
import org.gvsig.tools.persistence.PersistenceManager;
181
import org.gvsig.tools.persistence.Persistent;
182
import org.gvsig.tools.persistence.PersistentState;
183
import org.gvsig.tools.persistence.exception.PersistenceException;
184
import org.gvsig.tools.resourcesstorage.ResourcesStorage;
185
import org.gvsig.tools.undo.RedoException;
186
import org.gvsig.tools.undo.UndoException;
187
import org.gvsig.tools.undo.command.Command;
188
import org.gvsig.tools.util.CachedValue;
189
import org.gvsig.tools.util.ChainedIterator;
190
import org.gvsig.tools.util.GetItemWithSizeIsEmptyAndIterator64;
191
import org.gvsig.tools.util.HasAFile;
192
import org.gvsig.tools.util.PropertiesSupportHelper;
193
import org.gvsig.tools.util.UnmodifiableBasicMap;
194
import org.gvsig.tools.visitor.VisitCanceledException;
195
import org.gvsig.tools.visitor.Visitor;
196

    
197
@SuppressWarnings("UseSpecificCatch")
198
public class DefaultFeatureStore extends AbstractDataStore implements
199
        DataStoreInitializer2, FeatureStoreProviderServices, FeatureStore,
200
        SupportTransactions, Observer {
201

    
202
    public static long sample_feature_cache_timeout_ms = 15000;
203
    
204
    private static final String PERSISTENCE_DEFINITION_NAME = "FeatureStore";
205

    
206
    private DataStoreParameters parameters = null;
207
    private FeatureSelection selection;
208
    private FeatureLocks locks;
209

    
210
    private DelegateWeakReferencingObservable delegateObservable
211
            = new DelegateWeakReferencingObservable(this);
212

    
213
    private FeatureCommandsStack commands;
214

    
215
    /*
216
    TODO: Sustituir estos tres manager por un EditingManager
217
     */
218
    private FeatureTypeManager featureTypeManager;
219
    private FeatureManager featureManager;
220
    private SpatialManager spatialManager;
221

    
222
    private FeatureType defaultFeatureType = null;
223
    private List<FeatureType> featureTypes = new ArrayList<>();
224

    
225
    private int mode = MODE_QUERY;
226
    private int lastMode = MODE_QUERY;
227
    
228
    private long versionOfUpdate = 0;
229
    private boolean hasStrongChanges = true;
230

    
231
    private DefaultDataManager dataManager = null;
232

    
233
    private FeatureStoreProvider provider = null;
234

    
235
    private DefaultFeatureIndexes indexes;
236

    
237
    private DefaultFeatureStoreTransforms transforms;
238

    
239
    /*friend*/ DelegatedDynObject metadata;
240

    
241
    private Set metadataChildren;
242

    
243
    private Long featureCount = null;
244

    
245
    private long temporalOid = 0;
246

    
247
    private FeatureCacheProvider cache;
248

    
249
    private final StateInformation state;
250

    
251
    private FeatureStoreTimeSupport timeSupport;
252

    
253
    private PropertiesSupportHelper propertiesSupportHelper;
254
    private DataTransaction transaction;
255

    
256
    private String editingSessionCode;
257
    private String lastEditingSessionCode;
258
    
259
    private CachedValue<Feature> sampleFeatureCache;
260
    
261
    private final Observer transactionObserver;
262
    private String fullNameForTraces;
263

    
264
    private class StateInformation extends HashMap<Object, Object> {
265

    
266
        private static final long serialVersionUID = 4109026189635185666L;
267

    
268
        private boolean broken;
269
        private Throwable breakingsCause;
270

    
271
        @SuppressWarnings("OverridableMethodCallInConstructor")
272
        public StateInformation() {
273
            this.clear();
274
        }
275

    
276
        @Override
277
        public void clear() {
278
            this.broken = false;
279
            this.breakingsCause = null;
280
            super.clear();
281
        }
282

    
283
        public boolean isBroken() {
284
            return this.broken;
285
        }
286

    
287
        public void broken() {
288
            this.broken = true;
289
        }
290

    
291
        public Throwable getBreakingsCause() {
292
            return this.breakingsCause;
293
        }
294

    
295
        public void setBreakingsCause(Throwable cause) {
296
            if (this.breakingsCause == null) {
297
                this.breakingsCause = cause;
298
            }
299
            this.broken = true;
300
        }
301
    }
302

    
303
    /*
304
     * TODO:
305
     *
306
     * - Comprobar que solo se pueden a?adir reglas de validacion sobre un
307
     * EditableFeatureType. - Comprobar que solo se puede hacer un update con un
308
     * featureType al que se le han cambiado las reglas de validacion cuando
309
     * hasStrongChanges=false.
310
     */
311
    public DefaultFeatureStore() {
312
        this.state = new StateInformation();
313
        this.sampleFeatureCache = null;
314
        this.transactionObserver = (Observable o, Object o1) -> {
315
            if( o1 instanceof BaseNotification && (
316
                    ((BaseNotification)o1).isOfType("ROLLBACK") ||
317
                    ((BaseNotification)o1).isOfType("COMMIT")
318
                    ) ) {
319
                featureCount = null;
320
            }
321
        };
322
    }
323

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

    
329
    @Override
330
    public void intialize(DataManager dataManager,
331
            DataStoreParameters parameters) throws InitializeException {
332

    
333
        DynObjectManager dynManager = ToolsLocator.getDynObjectManager();
334

    
335
        this.metadata = (DelegatedDynObject) dynManager.createDynObject(
336
                FeatureStore.METADATA_DEFINITION_NAME,
337
                MetadataManager.METADATA_NAMESPACE
338
        );
339

    
340
        this.dataManager = (DefaultDataManager) dataManager;
341

    
342
        this.parameters = parameters;
343
        this.transforms = new DefaultFeatureStoreTransforms(this);
344
        try {
345
            indexes = new DefaultFeatureIndexes(this);
346
        } catch (DataException e) {
347
            throw new InitializeException(e);
348
        }
349

    
350
    }
351

    
352
    @Override
353
    public void setProvider(org.gvsig.fmap.dal.DataStoreProvider provider) {
354
        this.provider = (FeatureStoreProvider) provider;
355
        this.delegate((DynObject) provider);
356
        this.metadataChildren = new HashSet();
357
        this.metadataChildren.add(provider);
358
        if (!this.ignoreDALResource) {
359
            loadDALFile();
360

    
361
            // Habria que crear un metodo en el proveedor para que de prioidad
362
            // a los parametros frente a lo que se a leido en el fichero dal
363
            // DataStoreProvider arreglalo segun los parametros del usuario
364
            // fixFeatureTypeFromParameters
365
            this.provider.fixFeatureTypeFromParameters();
366
            try {
367
                if (defaultFeatureType != null) {
368
                    FeatureAttributeDescriptor attrGeom = defaultFeatureType.getDefaultGeometryAttribute();
369
                    if (attrGeom != null) {
370
                        DefaultFeatureAttributeDescriptor gattr = (DefaultFeatureAttributeDescriptor) attrGeom;
371
                        IProjection srs = (IProjection) this.getDynValue(METADATA_CRS);
372
                        if (srs != null && srs != gattr.getSRS()) {
373
                            gattr.setSRSForced(srs);
374
                        }
375
                    }
376
                }
377
            } catch (Throwable th) {
378
                LOGGER.warn("Can't patch DAL file", th);
379
            }
380
        }
381
    }
382

    
383
    @Override
384
    public DataStoreParameters getParameters() {
385
        if (this.parameters == null) {
386
            LOGGER.warn("Store parameters are null ("+this.getFullNameForTraces()+")");
387
        }
388
        return parameters;
389
    }
390

    
391
    @Override
392
    public int getMode() {
393
        return this.mode;
394
    }
395

    
396
    @Override
397
    public DataManager getManager() {
398
        return this.dataManager;
399
    }
400

    
401
    @Override
402
    public UnmodifiableBasicMap<String, DataStore> getChildren() {
403
        UnmodifiableBasicMap<String, DataStore> children = this.provider.getChildren();
404
        if (children == null) {
405
            return UnmodifiableBasicMap.EMPTY_UNMODIFIABLEBASICMAP;
406
        }
407
        return children;
408
    }
409

    
410
    @Override
411
    public FeatureStoreProvider getProvider() {
412
        return this.provider;
413
    }
414

    
415
    public FeatureManager getFeatureManager() {
416
        return this.featureManager;
417
    }
418

    
419
    @Override
420
    public void setFeatureTypes(List types, FeatureType defaultType) {
421
        this.featureTypes = types;
422
        this.defaultFeatureType = defaultType;
423
    }
424

    
425
    public void open() throws OpenException {
426
        if (this.mode != MODE_QUERY) {
427
            // TODO: Se puede hacer un open estando en edicion ?
428
            try {
429
                throw new IllegalStateException();
430
            } catch (Exception ex) {
431
                LOGGER.warn("Opening a store in editing/append mode (" + this.getFullName() + ").", ex);
432
            }
433
        }
434
        if (this.notifyChange(DataStoreNotification.BEFORE_OPEN).isCanceled()) {
435
            return;
436
        }
437
        this.provider.open();
438
        this.notifyChange(DataStoreNotification.AFTER_OPEN);
439
    }
440

    
441
    @Override
442
    public void refresh() throws OpenException, InitializeException {
443
        if (this.mode != MODE_QUERY) {
444
            throw new IllegalStateException();
445
        }
446
        if (this.notifyChange(FeatureStoreNotification.BEFORE_REFRESH).isCanceled()) {
447
            return;
448
        }
449
        if (state.isBroken()) {
450
            this.load(state);
451
        } else {
452
            this.featureCount = null;
453
            this.provider.refresh();
454
        }
455
        this.resourcesStorage = null;
456
        loadDALFile();
457
        this.provider.fixFeatureTypeFromParameters();
458

    
459
        this.notifyChange(FeatureStoreNotification.AFTER_REFRESH);
460
    }
461

    
462
    public void close() throws CloseException {
463
        if (this.mode != MODE_QUERY) {
464
            // TODO: Se puede hacer un close estando en edicion ?
465
            try {
466
                throw new IllegalStateException();
467
            } catch (Exception ex) {
468
                LOGGER.warn("Clossing a store in editing/append mode (" + this.getFullName() + ").", ex);
469
            }
470
        }
471
        if (this.notifyChange(DataStoreNotification.BEFORE_CLOSE).isCanceled()) {
472
            return;
473
        }
474
        this.featureCount = null;
475
        this.provider.close();
476
        this.notifyChange(DataStoreNotification.AFTER_CLOSE);
477
    }
478

    
479
    @Override
480
    protected void doDispose() throws BaseException {
481
        if (this.mode != MODE_QUERY) {
482
            // TODO: Se puede hacer un dispose estando en edicion ?
483
            try {
484
                throw new IllegalStateException();
485
            } catch (Exception ex) {
486
                LOGGER.warn("Dispossing a store in editing/append mode (" + this.getFullName() + ").", ex);
487
            }
488
        }
489
        if (this.notifyChange(DataStoreNotification.BEFORE_DISPOSE).isCanceled()) {
490
            return;
491
        }
492
        this.getFullName(); // to update fullnamefortraces
493
        this.disposeIndexes();
494
        if (this.provider != null) {
495
            this.provider.dispose();
496
        }
497
        if (this.selection != null) {
498
            this.selection.dispose();
499
            this.selection = null;
500
        }
501
        this.commands = null;
502
        this.featureCount = null;
503
        if (this.locks != null) {
504
            // this.locks.dispose();
505
            this.locks = null;
506
        }
507

    
508
        if (this.featureTypeManager != null) {
509
            this.featureTypeManager.dispose();
510
            this.featureTypeManager = null;
511
        }
512

    
513
        this.featureManager = null;
514
        this.spatialManager = null;
515

    
516
        this.parameters = null;
517
        this.notifyChange(DataStoreNotification.AFTER_DISPOSE);
518
        if (delegateObservable != null) {
519
            this.delegateObservable.deleteObservers();
520
            this.delegateObservable = null;
521
        }
522
        DisposeUtils.disposeQuietly(this.resourcesStorage);
523
        if( this.transaction!=null ) {
524
            this.transaction.remove(this);
525
            this.transaction = null;
526
        }
527
    }
528

    
529
    @Override
530
    public boolean allowWrite() {
531
        SimpleIdentityManager identityManager = ToolsLocator.getIdentityManager();
532
        if (!identityManager.getCurrentIdentity().isAuthorized(DataManager.WRITE_STORE_AUTHORIZATION, this.getParameters(), this.getName())) {
533
            return false;
534
        }
535
        return this.provider.allowWrite();
536
    }
537

    
538
    @Override
539
    public boolean canWriteGeometry(int geometryType) throws DataException {
540
        return this.provider.canWriteGeometry(geometryType, 0);
541
    }
542

    
543
    @Override
544
    public DataServerExplorer getExplorer() throws ReadException,
545
            ValidateDataParametersException {
546
        if (this.state.isBroken()) {
547
            try {
548
                return this.provider.getExplorer();
549
            } catch (Throwable th) {
550
                return null;
551
            }
552
        } else {
553
            return this.provider.getExplorer();
554
        }
555
    }
556

    
557
    /*
558
     * public Metadata getMetadata() throws MetadataNotFoundException {
559
     * // TODO:
560
     * // Si el provider devuelbe null habria que ver de construir aqui
561
     * // los metadatos basicos, como el Envelope y el SRS.
562
     *
563
     * // TODO: Estando en edicion el Envelope deberia de
564
     * // actualizarse usando el spatialManager
565
     * return this.provider.getMetadata();
566
     * }
567
     */
568
    @Override
569
    public Envelope getEnvelope() throws DataException {
570
        if (this.mode == MODE_FULLEDIT) {
571
            // Just in case another thread tries to write in the store
572
            synchronized (this) {
573
                return this.spatialManager.getEnvelope();
574
            }
575
        }
576
        try {
577
            FeatureType featureType = this.getDefaultFeatureTypeQuietly();
578
            if( featureType!=null ) {
579
                Tags tags = featureType.getTags();
580
                if( tags.has(DAL_STORE_ENVELOPE) ) {
581
                    String geom_s = tags.getString(DAL_STORE_ENVELOPE,null);
582
                    if( StringUtils.isNotBlank(geom_s) ) {
583
                        Geometry geom = GeometryUtils.createFrom(geom_s);
584
                        if( geom!=null ) {
585
                            return geom.getEnvelope();
586
                        }
587
                    }
588
                }
589
            }
590
        } catch(Throwable th) {
591
            LOGGER.debug("Can't retrieve envelope from featrure type tag '"+DAL_STORE_ENVELOPE+"'.", th);
592
        }
593
        
594
        if (hasDynValue(DataStore.METADATA_ENVELOPE)) {
595
            return (Envelope) getDynValue(DataStore.METADATA_ENVELOPE);
596
        }
597
        Envelope envelope = this.provider.getEnvelope();
598
        if (envelope != null) {
599
            return envelope;
600
        }
601
        FeatureAttributeDescriptor attrdesc = this.getDefaultFeatureType().getDefaultGeometryAttribute();
602
        if (attrdesc == null || (!attrdesc.isComputed() && this.getTransforms().isEmpty())) {
603
            return null;
604
        }
605
        final int index = attrdesc.getIndex();
606
        final MutableObject<Envelope> envelopeValue = new MutableObject<>();
607
        try {
608
            this.accept((Object obj) -> {
609
                Feature f = (Feature) obj;
610
                Geometry g = (Geometry) f.get(index);
611
                if (g == null) {
612
                    return;
613
                }
614
                if (envelopeValue.getValue() == null) {
615
                    envelopeValue.setValue(g.getEnvelope());
616
                } else {
617
                    envelopeValue.getValue().add(g);
618
                }
619
            });
620
        } catch (Throwable th) {
621
            LOGGER.warn("Can't calculate envelope", th);
622
            return null;
623
        }
624
        return envelopeValue.getValue();
625
    }
626

    
627
    /**
628
     * @throws org.gvsig.fmap.dal.exception.DataException
629
     * @deprecated use getDefaultFeatureType().getDefaultSRS()
630
     */
631
    @Override
632
    public IProjection getSRSDefaultGeometry() throws DataException {
633
        return this.getDefaultFeatureType().getDefaultSRS();
634
    }
635

    
636
    @Override
637
    public FeatureSelection createDefaultFeatureSelection()
638
            throws DataException {
639
        return new DefaultFeatureSelection(this);
640
    }
641

    
642
    @Override
643
    public FeatureProvider createDefaultFeatureProvider(FeatureType type)
644
            throws DataException {
645
        if (type.hasOID()) {
646
            return new DefaultFeatureProvider(type,
647
                    this.provider.createNewOID());
648
        }
649
        return new DefaultFeatureProvider(type);
650
    }
651

    
652
    @Override
653
    public void saveToState(PersistentState state) throws PersistenceException {
654
        /*if (this.mode != FeatureStore.MODE_QUERY) {
655
            throw new PersistenceException(new IllegalStateException(
656
                this.getName()));
657
        }*/
658
        state.set("dataStoreName", this.getName());
659
        state.set("parameters", this.parameters);
660
        state.set("selection", this.selection);
661
        state.set("transforms", this.transforms);
662
        // TODO locks persistence
663
        // state.set("locks", this.locks);
664
        // TODO indexes persistence
665
        // state.set("indexes", this.indexes);
666
        Map evaluatedAttr = new HashMap(1);
667
        Iterator iterType = featureTypes.iterator();
668
        Iterator iterAttr;
669
        FeatureType type;
670
        DefaultFeatureAttributeDescriptor attr;
671
        List attrs;
672
        while (iterType.hasNext()) {
673
            type = (FeatureType) iterType.next();
674
            attrs = new ArrayList();
675
            iterAttr = type.iterator();
676
            while (iterAttr.hasNext()) {
677
                attr = (DefaultFeatureAttributeDescriptor) iterAttr.next();
678
                if ((attr.getEvaluator() != null)
679
                        && (attr.getEvaluator() instanceof Persistent)) {
680
                    attrs.add(attr);
681
                }
682
            }
683
            if (!attrs.isEmpty()) {
684
                evaluatedAttr.put(type.getId(), attrs);
685
            }
686

    
687
        }
688

    
689
        if (evaluatedAttr.isEmpty()) {
690
            evaluatedAttr = null;
691
        }
692

    
693
        state.set("evaluatedAttributes", evaluatedAttr);
694
        state.set("defaultFeatureTypeId", defaultFeatureType.getId());
695

    
696
    }
697

    
698
    @Override
699
    public void loadFromState(final PersistentState persistentState)
700
            throws PersistenceException {
701
        if (this.provider != null) {
702
            throw new PersistenceStoreAlreadyLoadedException(this.getName());
703
        }
704
        if (this.getManager() == null) {
705
            this.dataManager = (DefaultDataManager) DALLocator.getDataManager();
706
        }
707
        state.clear();
708
        try {
709
            state.put("parameters", persistentState.get("parameters"));
710
        } catch (Throwable th) {
711
            state.setBreakingsCause(th);
712
        }
713
        try {
714
            state.put("selection", persistentState.get("selection"));
715
        } catch (Throwable th) {
716
            state.setBreakingsCause(th);
717
        }
718
        try {
719
            state.put("transforms", persistentState.get("transforms"));
720
        } catch (Throwable th) {
721
            state.setBreakingsCause(th);
722
        }
723
        try {
724
            state.put("evaluatedAttributes", persistentState.get("evaluatedAttributes"));
725
        } catch (Throwable th) {
726
            state.setBreakingsCause(th);
727
        }
728
        try {
729
            state.put("defaultFeatureTypeId", persistentState.getString("defaultFeatureTypeId"));
730
        } catch (Throwable th) {
731
            state.setBreakingsCause(th);
732
        }
733
        load(state);
734
        ((DefaultDataManager) this.getDataManager()).addObservers(this);
735
    }
736

    
737
    private void load(StateInformation state) {
738
        this.featureTypes = new ArrayList();
739
        this.defaultFeatureType = null;
740
        this.featureCount = null;
741

    
742
        DataStoreParameters params = (DataStoreParameters) state.get("parameters");
743
        try {
744
            intialize(dataManager, params);
745
        } catch (Throwable th) {
746
            state.setBreakingsCause(th);
747
        }
748

    
749
        try {
750
            DataStoreProvider prov = dataManager.createProvider(
751
                    getStoreProviderServices(),
752
                    params
753
            );
754
            setProvider(prov);
755
        } catch (Throwable th) {
756
            LOGGER.warn("Can't load store from state.", th);
757
            state.setBreakingsCause(th);
758
        }
759
        try {
760
            selection = (FeatureSelection) state.get("selection");
761
        } catch (Throwable th) {
762
            state.setBreakingsCause(th);
763
        }
764

    
765
        try {
766
            this.transforms = (DefaultFeatureStoreTransforms) state.get("transforms");
767
            this.transforms.setFeatureStore(this);
768
            for (FeatureStoreTransform transform : this.transforms) {
769
                try {
770
                    transform.setUp();
771
                } catch (Throwable th) {
772
                    state.setBreakingsCause(th);
773
                }
774
            }
775
        } catch (Throwable th) {
776
            state.setBreakingsCause(th);
777
        }
778

    
779
        try {
780
            Map evaluatedAttributes = (Map) state.get("evaluatedAttributes");
781
            if ((evaluatedAttributes != null) && !evaluatedAttributes.isEmpty()) {
782
                Iterator iterEntries = evaluatedAttributes.entrySet().iterator();
783
                while (iterEntries.hasNext()) {
784
                    Entry entry = (Entry) iterEntries.next();
785
                    List attrs = (List) entry.getValue();
786
                    if (attrs.isEmpty()) {
787
                        continue;
788
                    }
789
                    int fTypePos = -1;
790
                    DefaultFeatureType type = null;
791
                    for (int i = 0; i < featureTypes.size(); i++) {
792
                        type = (DefaultFeatureType) featureTypes.get(i);
793
                        if (type.getId().equals(entry.getKey())) {
794
                            fTypePos = i;
795
                            break;
796
                        }
797
                    }
798
                    if (type == null) {
799
                        throw new PersistenceCantFindFeatureTypeException(
800
                                getName(), (String) entry.getKey());
801
                    }
802
                    DefaultEditableFeatureType eType = (DefaultEditableFeatureType) type.getEditable();
803
                    Iterator<FeatureAttributeDescriptor> iterAttr = attrs.iterator();
804
                    while (iterAttr.hasNext()) {
805
                        FeatureAttributeDescriptor attr = iterAttr.next();
806
                        eType.addLike(attr);
807
                    }
808
                    featureTypes.set(fTypePos, eType.getNotEditableCopy());
809

    
810
                }
811

    
812
            }
813
        } catch (Throwable th) {
814
            state.setBreakingsCause(th);
815
        }
816

    
817
        try {
818
            String defaultFeatureTypeId = (String) state.get("defaultFeatureTypeId");
819
            FeatureType ftype;
820

    
821
            if (defaultFeatureType == null
822
                    || defaultFeatureType.getId() == null
823
                    || !defaultFeatureType.getId().equals(defaultFeatureTypeId)) {
824

    
825
                ftype = getFeatureType(defaultFeatureTypeId);
826
                if (ftype == null) {
827
                    /*
828
                             * Un error en el m?todo de PostgreSQL getName(), hace que
829
                             * el nombre del featureType sea valor retornado por el getProviderName()
830
                             * De momento se pone este parche para apa?arlo y poder mantener compatibilidad
831
                             * con proyectos antiguos (2.1 y 2.2)
832
                     */
833
                    ftype = getFeatureType(getName());
834
                    if (ftype == null) {
835
                        throw new RuntimeException("Can't locate feature type");
836
                    }
837
                }
838
                defaultFeatureType = ftype;
839
            }
840
        } catch (Throwable th) {
841
            state.setBreakingsCause(th);
842
        }
843

    
844
        LOGGER.debug("load() broken:{}, {}, {}.",
845
                new Object[]{state.isBroken(), this.getProviderName(), params.toString((Object... args) -> StringUtils.equalsIgnoreCase((CharSequence) args[0], "password")?"******":args[1])}
846
        );
847
    }
848

    
849
    public DataStoreProviderServices getStoreProviderServices() {
850
        return this;
851
    }
852

    
853
    public static void selfRegister(List<Exception> exs) {
854
        registerPersistenceDefinition();
855
        try {
856
            registerMetadataDefinition();
857
        } catch (MetadataException e) {
858
            exs.add(e);
859
        }
860
        try {
861
            DynObjectManager dynObjectManager = ToolsLocator.getDynObjectManager();
862
            dynObjectManager.registerTag(
863
                    DAL_USE_LARGE_SELECTION,
864
                    "Indicates whether the store should use a memory-based or a disk-based selection."
865
            ).setType(DataTypes.BOOLEAN);
866
            dynObjectManager.registerTag(
867
                    DAL_STORE_ENVELOPE,
868
                    "If specified, this geometry will be used to calculate the store envelope."
869
            ).setType(DataTypes.STRING);
870
        } catch (Exception e) {
871
            exs.add(e);
872
        }
873
    }
874

    
875
    private static void registerPersistenceDefinition() {
876
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
877
        if (manager.getDefinition(PERSISTENCE_DEFINITION_NAME) == null) {
878
            DynStruct definition
879
                    = manager.addDefinition(DefaultFeatureStore.class,
880
                            PERSISTENCE_DEFINITION_NAME, PERSISTENCE_DEFINITION_NAME
881
                            + " Persistent definition", null, null);
882
            definition.addDynFieldString("dataStoreName").setMandatory(true)
883
                    .setPersistent(true);
884

    
885
            definition.addDynFieldObject("parameters")
886
                    .setClassOfValue(DynObject.class).setMandatory(true)
887
                    .setPersistent(true);
888

    
889
            definition.addDynFieldObject("selection")
890
                    .setClassOfValue(FeatureSelection.class).setMandatory(false)
891
                    .setPersistent(true);
892

    
893
            definition.addDynFieldObject("transforms")
894
                    .setClassOfValue(DefaultFeatureStoreTransforms.class)
895
                    .setMandatory(true).setPersistent(true);
896

    
897
            definition.addDynFieldMap("evaluatedAttributes")
898
                    .setClassOfItems(List.class) // List<DefaultFeatureAttributeDescriptor>
899
                    .setMandatory(false).setPersistent(true);
900

    
901
            definition.addDynFieldString("defaultFeatureTypeId")
902
                    .setMandatory(true).setPersistent(true);
903
        }
904
    }
905

    
906
    private static void registerMetadataDefinition() throws MetadataException {
907
        MetadataManager manager = MetadataLocator.getMetadataManager();
908
        if (manager.getDefinition(FeatureStore.METADATA_DEFINITION_NAME) == null) {
909
            DynStruct metadataDefinition
910
                    = manager.addDefinition(FeatureStore.METADATA_DEFINITION_NAME, null);
911
            metadataDefinition.extend(manager
912
                    .getDefinition(DataStore.METADATA_DEFINITION_NAME));
913
        }
914
    }
915

    
916
    //
917
    // ====================================================================
918
    // Gestion de la seleccion
919
    //
920
    @Override
921
    public void setSelection(DataSet selection) throws DataException {
922
        this.setSelection((FeatureSet) selection);
923
    }
924

    
925
    @Override
926
    public DataSet createSelection() throws DataException {
927
        return createFeatureSelection();
928
    }
929

    
930
    @Override
931
    public DataSet getSelection() throws DataException {
932
        return this.getFeatureSelection();
933
    }
934

    
935
    @Override
936
    public void setSelection(FeatureSet selection) throws DataException {
937
        setSelection(selection, true);
938
    }
939

    
940
    public void setSelection(FeatureSet selection, boolean undoable)
941
            throws DataException {
942
        if (selection == null) {
943
            if (undoable) {
944
                throw new SelectionNotAllowedException(getName());
945
            }
946

    
947
        } else {
948
            if (selection.equals(this.selection)) {
949
                return;
950
            }
951
            if (!selection.isFromStore(this)) {
952
                throw new SelectionNotAllowedException(getName());
953
            }
954
        }
955

    
956
        if (this.selection != null) {
957
            this.selection.deleteObserver(this);
958
        }
959
        if (selection == null) {
960
            if (this.selection != null) {
961
                this.selection.dispose();
962
            }
963
            this.selection = null;
964
            return;
965
        }
966
        if (selection instanceof FeatureSelection) {
967
            if (undoable && isEditing()) {
968
                commands.selectionSet(this, this.selection,
969
                        (FeatureSelection) selection);
970
            }
971
            if (this.selection != null) {
972
                this.selection.dispose();
973
            }
974
            this.selection = (FeatureSelection) selection;
975
        } else {
976
            if (undoable && isEditing()) {
977
                commands.startComplex("_selectionSet");
978
            }
979
//            if (selection instanceof DefaultFeatureSelection) {
980
//                // FIXME: Estas lineas parece que no tienen sentido.
981
//                DefaultFeatureSelection defSelection = (DefaultFeatureSelection) selection;
982
//                defSelection.deselectAll(undoable);
983
//                defSelection.select(selection, undoable);
984
//            } else {
985
                if( this.selection == null ) {
986
                    this.selection = createDefaultFeatureSelection();
987
                }
988
                this.selection.deselectAll();
989
                this.selection.select(selection);
990
//            }
991
            if (undoable && isEditing()) {
992
                commands.endComplex();
993
            }
994
        }
995
        this.getFeatureSelection().addObserver(this);
996

    
997
        this.notifyChange(DataStoreNotification.SELECTION_CHANGE);
998
    }
999

    
1000
    @Override
1001
    public FeatureSelection createFeatureSelection() throws DataException {
1002
        FeatureType featureType = this.getDefaultFeatureTypeQuietly();
1003
        if( featureType!=null ) {
1004
            Tags tags = featureType.getTags();
1005
            if( tags.has(DataManager.DAL_USE_LARGE_SELECTION) ) {
1006
                boolean useLargeSelection = tags.getBoolean(DataManager.DAL_USE_LARGE_SELECTION,true);
1007
                if( useLargeSelection ) {
1008
                    return createLargeFeatureSelection();
1009
                }
1010
                return this.provider.createFeatureSelection();
1011
            }
1012
        }
1013
        long maxSize = dataManager.getMaxSizeForSmallFeatureSelection();
1014
        if (this.provider.getFeatureCount() > maxSize) {
1015
            return createLargeFeatureSelection();
1016
        }
1017
        return this.provider.createFeatureSelection();
1018
    }
1019

    
1020
    @Override
1021
    public FeatureSelection createLargeFeatureSelection() throws DataException {
1022
        return new LargeFeatureSelection(this);
1023

    
1024
    }
1025

    
1026
    @Override
1027
    public FeatureSelection createMemoryFeatureSelection() throws DataException {
1028
        return this.provider.createFeatureSelection();
1029
    }
1030

    
1031
    @Override
1032
    public FeatureSelection getFeatureSelection() throws DataException {
1033
        if (selection == null) {
1034
            this.selection = createFeatureSelection();
1035
            this.selection.addObserver(this);
1036
        }
1037
        return selection;
1038
    }
1039

    
1040
    @Override
1041
    public FeatureSelection getFeatureSelectionQuietly() {
1042
        try {
1043
            return this.getFeatureSelection();
1044
        } catch (DataException ex) {
1045
            return FeatureSelection.EMTPY_FEATURE_SELECTION;
1046
        }
1047
    }
1048
    
1049
    
1050

    
1051
    @Override
1052
    public boolean isFeatureSelectionEmpty() {
1053
        if( selection == null ) {
1054
            return true;
1055
        }
1056
        return selection.isEmpty();
1057
    }
1058
    
1059
    //
1060
    // ====================================================================
1061
    // Gestion de notificaciones
1062
    //
1063
    @Override
1064
    public FeatureStoreNotification notifyChange(FeatureStoreNotification storeNotification) {
1065
        if (delegateObservable != null) {
1066
            try {
1067
                delegateObservable.notifyObservers(storeNotification);
1068
            } catch (Throwable ex) {
1069
                LOGGER.warn("Problems notifying changes in the store '" + this.getName() + " (" + storeNotification.getType() + ").", ex);
1070
            }
1071
        }
1072
        return storeNotification;
1073
    }
1074

    
1075
    @Override
1076
    public FeatureStoreNotification notifyChange(String notification) {
1077
        return notifyChange(
1078
                new DefaultFeatureStoreNotification(
1079
                        this, notification, 
1080
                        this.editingSessionCode==null?this.lastEditingSessionCode:this.editingSessionCode,
1081
                        this.mode == FeatureStore.MODE_QUERY?this.lastMode:this.mode
1082
                )
1083
        );
1084
    }
1085

    
1086
    public FeatureStoreNotification notifyChange(String notification, String editingSessionCode) {
1087
        return notifyChange(new DefaultFeatureStoreNotification(this, notification, editingSessionCode));
1088
    }
1089

    
1090
    public FeatureStoreNotification notifyChange(String notification, String editingSessionCode, int editMode) {
1091
        return notifyChange(new DefaultFeatureStoreNotification(this, notification, editingSessionCode, editMode));
1092
    }
1093

    
1094
    public FeatureStoreNotification notifyChange(String notification,
1095
//            String editingSessionCode,
1096
            Iterator<FeatureReference> deleteds,
1097
            Iterator<EditableFeature> inserteds,
1098
            Iterator<EditableFeature> updateds,
1099
            Iterator<FeatureTypeChanged> featureTypesChanged,
1100
            boolean isSelectionCompromised) {
1101
        return notifyChange(
1102
                new DefaultFeatureStoreNotification(
1103
                        this, notification, 
1104
                        this.editingSessionCode==null?this.lastEditingSessionCode:this.editingSessionCode,
1105
                        this.mode == FeatureStore.MODE_QUERY?this.lastMode:this.mode,
1106
                        deleteds, inserteds, updateds, featureTypesChanged, isSelectionCompromised
1107
                )
1108
        );
1109
    }
1110

    
1111
    @Override
1112
    public FeatureStoreNotification notifyChange(String notification, FeatureProvider data) {
1113
        Feature f = null;
1114
        if (data != null) {
1115
            try {
1116
                f = createFeature(data);
1117
            } catch (Throwable ex) {
1118
                LOGGER.warn("Problems creating a feature to notifying changes in the store '" + this.getName() + " (" + notification + ").", ex);
1119
            }
1120
        }
1121
        return notifyChange(notification, f);
1122
    }
1123

    
1124
    public FeatureStoreNotification notifyChange(String notification, Feature feature) {
1125
        return notifyChange(
1126
                new DefaultFeatureStoreNotification(
1127
                        this, notification, 
1128
                        this.editingSessionCode==null?this.lastEditingSessionCode:this.editingSessionCode,
1129
                        this.mode == FeatureStore.MODE_QUERY?this.lastMode:this.mode,
1130
                        feature
1131
                )
1132
        );
1133
    }
1134

    
1135
    public FeatureStoreNotification notifyChange(String notification, Expression expression) {
1136
        return notifyChange(
1137
                new DefaultFeatureStoreNotification(
1138
                        this, notification, 
1139
                        this.editingSessionCode==null?this.lastEditingSessionCode:this.editingSessionCode,
1140
                        this.mode == FeatureStore.MODE_QUERY?this.lastMode:this.mode,
1141
                        expression
1142
                )
1143
        );
1144
    }
1145

    
1146
    public FeatureStoreNotification notifyChange(String notification, Command command) {
1147
        return notifyChange(
1148
                new DefaultFeatureStoreNotification(
1149
                        this, notification, 
1150
                        this.editingSessionCode==null?this.lastEditingSessionCode:this.editingSessionCode,
1151
                        this.mode == FeatureStore.MODE_QUERY?this.lastMode:this.mode,
1152
                        command
1153
                )
1154
        );
1155
    }
1156

    
1157
    public FeatureStoreNotification notifyChange(String notification, EditableFeatureType type) {
1158
        return notifyChange(
1159
                new DefaultFeatureStoreNotification(
1160
                        this, notification, 
1161
                        this.editingSessionCode==null?this.lastEditingSessionCode:this.editingSessionCode,
1162
                        this.mode == FeatureStore.MODE_QUERY?this.lastMode:this.mode,
1163
                        type
1164
                )
1165
        );
1166
    }
1167

    
1168
    @Override
1169
    public FeatureStoreNotification notifyChange(String notification, Resource resource) {
1170
        return notifyChange(
1171
                new DefaultFeatureStoreNotification(
1172
                        this, DataStoreNotification.RESOURCE_CHANGED
1173
                )
1174
        );
1175
    }
1176

    
1177
    //
1178
    // ====================================================================
1179
    // Gestion de bloqueos
1180
    //
1181
    @Override
1182
    public boolean isLocksSupported() {
1183
        return this.provider.isLocksSupported();
1184
    }
1185

    
1186
    @Override
1187
    public FeatureLocks getLocks() throws DataException {
1188
        if (!this.provider.isLocksSupported()) {
1189
            LOGGER.warn("Locks not supported");
1190
            return null;
1191
        }
1192
        if (locks == null) {
1193
            this.locks = this.provider.createFeatureLocks();
1194
        }
1195
        return locks;
1196
    }
1197

    
1198
    //
1199
    // ====================================================================
1200
    // Interface Observable
1201
    //
1202
    @Override
1203
    public void disableNotifications() {
1204
        this.delegateObservable.disableNotifications();
1205

    
1206
    }
1207

    
1208
    @Override
1209
    public void enableNotifications() {
1210
        this.delegateObservable.enableNotifications();
1211
    }
1212

    
1213
    @Override
1214
    public void beginComplexNotification() {
1215
        this.delegateObservable.beginComplexNotification();
1216

    
1217
    }
1218

    
1219
    @Override
1220
    public void endComplexNotification() {
1221
        this.delegateObservable.endComplexNotification();
1222

    
1223
    }
1224

    
1225
    @Override
1226
    public void addObserver(Observer observer) {
1227
        if (delegateObservable != null) {
1228
            this.delegateObservable.addObserver(observer);
1229
        }
1230
    }
1231

    
1232
    @Override
1233
    public void deleteObserver(Observer observer) {
1234
        if (delegateObservable != null) {
1235
            this.delegateObservable.deleteObserver(observer);
1236
        }
1237
    }
1238

    
1239
    @Override
1240
    public void deleteObservers() {
1241
        this.delegateObservable.deleteObservers();
1242

    
1243
    }
1244

    
1245
    //
1246
    // ====================================================================
1247
    // Interface Observer
1248
    //
1249
    // Usado para observar:
1250
    // - su seleccion
1251
    // - sus bloqueos
1252
    // - sus recursos
1253
    //
1254
    @Override
1255
    public void update(Observable observable, Object notification) {
1256
        if (observable instanceof FeatureSet) {
1257
            if (observable == this.selection) {
1258
                this.notifyChange(DataStoreNotification.SELECTION_CHANGE);
1259
            } else if (observable == this.locks) {
1260
                this.notifyChange(FeatureStoreNotification.LOCKS_CHANGE);
1261
            }
1262

    
1263
        } else if (observable instanceof FeatureStoreProvider) {
1264
            if (observable == this.provider) {
1265

    
1266
            }
1267
        } else if (observable instanceof FeatureReferenceSelection) {
1268
            if (notification instanceof String) {
1269
                this.notifyChange((String) notification);
1270
            }
1271
        }
1272
    }
1273

    
1274
    //
1275
    // ====================================================================
1276
    // Edicion
1277
    //
1278
    private void newVersionOfUpdate() {
1279
        this.versionOfUpdate++;
1280
    }
1281

    
1282
    private long currentVersionOfUpdate() {
1283
        return this.versionOfUpdate;
1284
    }
1285

    
1286
    private void checkInEditingMode() throws NeedEditingModeException {
1287
        if (mode != MODE_FULLEDIT) {
1288
            throw new NeedEditingModeException(this.getName());
1289
        }
1290
    }
1291

    
1292
    private void checkNotInAppendMode() throws IllegalStateException {
1293
        if (mode == MODE_APPEND) {
1294
            throw new IllegalStateException("Error: store "
1295
                    + this.getFullName() + " is in append mode");
1296
        }
1297
    }
1298

    
1299
    private void checkIsOwnFeature(Feature feature)
1300
            throws IllegalFeatureException {
1301
        if (((DefaultFeature) feature).getStore() != this) {
1302
            throw new IllegalFeatureException(this.getName());
1303
        }
1304
        // FIXME: fixFeatureType no vale para el checkIsOwnFeature
1305
        // fixFeatureType((DefaultFeatureType) feature.getType());
1306
    }
1307

    
1308
    private void exitEditingMode() {
1309
        if (commands != null) {
1310
            try {
1311
                commands.clear();
1312
            } catch (Exception ex) {
1313
                LOGGER.trace("Can't clear commands", ex);
1314
            }
1315
            commands = null;
1316
        }
1317

    
1318
        if (featureTypeManager != null) {
1319
            DisposeUtils.disposeQuietly(featureTypeManager);
1320
            featureTypeManager = null;
1321

    
1322
        }
1323

    
1324
        // TODO implementar un dispose para estos dos
1325
        featureManager = null;
1326
        if (spatialManager != null) {
1327
            spatialManager.clear();
1328
        }
1329
        spatialManager = null;
1330

    
1331
        featureCount = null;
1332

    
1333
        this.lastMode = this.mode;
1334
        mode = MODE_QUERY;
1335
        hasStrongChanges = true; // Lo deja a true por si las moscas
1336

    
1337
        this.lastEditingSessionCode = this.editingSessionCode;
1338
        this.editingSessionCode = null;
1339
        
1340
        if( StringUtils.equalsIgnoreCase(DatabaseWorkspaceManager.TABLE_RESOURCES_NAME, this.getName()) ) {
1341
            // Es un poco drastico, pero cuando terminamos edicion de la tabla
1342
            // GVSIGD_RESOURCES, borraremos las cache de todos los recursos por
1343
            // que no sabemos si se ha modificado alguno y ha quedado obsoleto.
1344
            DALLocator.getDataManager().clearAllCachedResources();
1345
        }
1346
    }
1347

    
1348
    @Override
1349
    synchronized public void edit() throws DataException {
1350
        edit(MODE_FULLEDIT);
1351
    }
1352

    
1353
    @Override
1354
    synchronized public void edit(int mode) throws DataException {
1355
        LOGGER.debug("Starting editing in mode: {}", mode);
1356
        if (this.mode != MODE_QUERY) {
1357
            throw new AlreadyEditingException(this.getName());
1358
        }
1359
        FeatureType ftype = this.getDefaultFeatureType();
1360
        String newSessionCode = this.createUniqueID();
1361
        try {
1362
            if (!this.provider.supportsAppendMode()) {
1363
                mode = MODE_FULLEDIT;
1364
            }
1365
            if (!this.canBeEdited()) {
1366
                 throw new IllegalStateException(this.getName());
1367
            }
1368
            switch (mode) {
1369
                case MODE_QUERY:
1370
                    throw new IllegalStateException(this.getName());
1371

    
1372
                case MODE_FULLEDIT:
1373
                    if (notifyChange(FeatureStoreNotification.BEFORE_STARTEDITING,
1374
                            newSessionCode, mode).isCanceled()) {
1375
                        return;
1376
                    }
1377
                    this.editingSessionCode = newSessionCode;
1378
                    invalidateIndexes();
1379
                    featureManager = new FeatureManager(this);
1380
                    featureTypeManager = new FeatureTypeManager(this);
1381
                    spatialManager = new SpatialManager(this);
1382

    
1383
                    commands = new DefaultFeatureCommandsStack(
1384
                            this, featureManager,
1385
                            spatialManager, featureTypeManager);
1386
                    this.mode = MODE_FULLEDIT;
1387
                    hasStrongChanges = false;
1388
                    notifyChange(FeatureStoreNotification.AFTER_STARTEDITING, newSessionCode, this.mode);
1389
                    break;
1390

    
1391
                case MODE_APPEND:
1392
                    if (notifyChange(FeatureStoreNotification.BEFORE_STARTEDITING,
1393
                            newSessionCode, mode).isCanceled()) {
1394
                        return;
1395
                    }
1396
                    this.editingSessionCode = newSessionCode;
1397
                    invalidateIndexes();
1398
                    this.provider.beginAppend();
1399
                    this.mode = MODE_APPEND;
1400
                    notifyChange(FeatureStoreNotification.AFTER_STARTEDITING,
1401
                            newSessionCode, this.mode);
1402
                    break;
1403
                case MODE_PASS_THROUGH:
1404
                    if (!this.provider.supportsPassThroughMode()) {
1405
                        throw new IllegalStateException(this.getName());
1406
                    }
1407
                    if (notifyChange(FeatureStoreNotification.BEFORE_STARTEDITING,
1408
                            newSessionCode, mode).isCanceled()) {
1409
                        return;
1410
                    }
1411
                    this.editingSessionCode = newSessionCode;
1412
                    invalidateIndexes();
1413
                    this.mode = MODE_PASS_THROUGH;
1414
                    notifyChange(FeatureStoreNotification.AFTER_STARTEDITING,
1415
                            newSessionCode, this.mode);
1416
                    break;
1417

    
1418
            }
1419
        } catch (Exception e) {
1420
            try {
1421
                if (this.mode != MODE_QUERY) {
1422
                    exitEditingMode();
1423
                }
1424
                notifyChange(FeatureStoreNotification.FAILED_STARTEDITING,
1425
                        newSessionCode, mode);
1426
            } catch (Throwable th) {
1427
                LOGGER.warn("Can't cleanup after error in start editing.", th);
1428
            }
1429
            throw new StoreEditException(e, this.getName());
1430
        }
1431
    }
1432

    
1433
    private void invalidateIndexes() {
1434
        setIndexesValidStatus(false);
1435
    }
1436

    
1437
    private void setIndexesValidStatus(boolean valid) {
1438
        FeatureIndexes theIndexes = getIndexes();
1439
        LOGGER.debug("Setting the store indexes to valid status {}: {}", (valid
1440
                ? Boolean.TRUE : Boolean.FALSE), theIndexes);
1441
        for (Iterator iterator = theIndexes.iterator(); iterator.hasNext();) {
1442
            FeatureIndex index = (FeatureIndex) iterator.next();
1443
            if (index instanceof FeatureIndexProviderServices) {
1444
                FeatureIndexProviderServices indexServices
1445
                        = (FeatureIndexProviderServices) index;
1446
                indexServices.setValid(valid);
1447
            }
1448
        }
1449
    }
1450

    
1451
    private void updateIndexes() throws FeatureIndexException {
1452
        FeatureIndexes theIndexes = getIndexes();
1453
        LOGGER.debug("Refilling indexes: {}", theIndexes);
1454
        for (Iterator iterator = theIndexes.iterator(); iterator.hasNext();) {
1455
            FeatureIndex index = (FeatureIndex) iterator.next();
1456
            if (index instanceof FeatureIndexProviderServices) {
1457
                FeatureIndexProviderServices indexServices
1458
                        = (FeatureIndexProviderServices) index;
1459
                indexServices.fill(true, null);
1460
            }
1461
        }
1462
    }
1463

    
1464
    private void waitForIndexes() {
1465
        FeatureIndexes theIndexes = getIndexes();
1466
        LOGGER.debug("Waiting for indexes to finish filling: {}", theIndexes);
1467
        for (Iterator iterator = theIndexes.iterator(); iterator.hasNext();) {
1468
            FeatureIndex index = (FeatureIndex) iterator.next();
1469
            if (index instanceof FeatureIndexProviderServices) {
1470
                FeatureIndexProviderServices indexServices
1471
                        = (FeatureIndexProviderServices) index;
1472
                indexServices.waitForIndex();
1473
            }
1474
        }
1475
    }
1476

    
1477
    private void disposeIndexes() {
1478
        FeatureIndexes theIndexes = getIndexes();
1479
        LOGGER.debug("Disposing indexes: {}", theIndexes);
1480
        if (theIndexes == null) {
1481
            return;
1482
        }
1483
        for (Iterator iterator = theIndexes.iterator(); iterator.hasNext();) {
1484
            FeatureIndex index = (FeatureIndex) iterator.next();
1485
            if (index instanceof FeatureIndexProviderServices) {
1486
                FeatureIndexProviderServices indexServices
1487
                        = (FeatureIndexProviderServices) index;
1488
                indexServices.dispose();
1489
            }
1490
        }
1491
    }
1492

    
1493
    @Override
1494
    public boolean isEditing() {
1495
        return mode == MODE_FULLEDIT;
1496
    }
1497

    
1498
    @Override
1499
    public boolean isAppending() {
1500
        return mode == MODE_APPEND;
1501
    }
1502

    
1503
    @Override
1504
    synchronized public void update(EditableFeatureType type)
1505
            throws DataException {
1506
        try {
1507
            if (type == null) {
1508
                throw new NullFeatureTypeException(getName());
1509
            }
1510

    
1511
            switch (this.mode) {
1512
                case MODE_QUERY:
1513
                    if (type.hasOnlyMetadataChanges(this.defaultFeatureType)) {
1514
                        if (notifyChange(FeatureStoreNotification.BEFORE_UPDATE_TYPE, type).isCanceled()) {
1515
                            return;
1516
                        }
1517
                        FeatureType theType = type.getNotEditableCopy();
1518
                        if (defaultFeatureType.getId().equals(theType.getId())) {
1519
                            defaultFeatureType = theType;
1520
                        }
1521
                        List newtypes = new ArrayList();
1522
                        for (FeatureType featureType : this.featureTypes) {
1523
                            if (featureType.getId().equals(theType.getId())) {
1524
                                newtypes.add(theType);
1525
                            } else {
1526
                                newtypes.add(featureType);
1527
                            }
1528
                        }
1529
                        this.featureTypes = newtypes;
1530
                        saveDALFile();
1531
                        notifyChange(FeatureStoreNotification.AFTER_UPDATE_TYPE, type);
1532
                    }
1533

    
1534
                    break;
1535
                case MODE_FULLEDIT:
1536
                    if (notifyChange(FeatureStoreNotification.BEFORE_UPDATE_TYPE, type).isCanceled()) {
1537
                        return;
1538
                    }
1539
                    newVersionOfUpdate();
1540

    
1541
                    FeatureType oldt = type.getSource().getCopy();
1542
                    FeatureType newt = type.getCopy();
1543
                    commands.update(newt, oldt);
1544
                    hasStrongChanges = ((DefaultEditableFeatureType) type).hasStrongChanges();
1545
                    notifyChange(FeatureStoreNotification.AFTER_UPDATE_TYPE, type);
1546
                    break;
1547
                case MODE_APPEND:
1548
                case MODE_PASS_THROUGH:
1549
                    throw new NeedEditingModeException(this.getName());
1550

    
1551
            }
1552
        } catch (Exception e) {
1553
            throw new StoreUpdateFeatureTypeException(e, this.getName());
1554
        }
1555
    }
1556

    
1557
    @Override
1558
    public void delete(Feature feature) throws DataException {
1559
        switch (this.mode) {
1560
            case MODE_PASS_THROUGH:
1561
                checkIsOwnFeature(feature);
1562
                if (notifyChange(FeatureStoreNotification.BEFORE_DELETE, feature).isCanceled()) {
1563
                    return;
1564
                }
1565
                this.provider.passThroughDelete((FeatureReferenceProviderServices) feature.getReference());
1566
                notifyChange(FeatureStoreNotification.AFTER_DELETE, feature);
1567
                break;
1568
            default:
1569
                this.commands.delete(feature);
1570
                break;
1571

    
1572
        }
1573
    }
1574

    
1575
    @Override
1576
    public void delete(String filter) {
1577
        if (StringUtils.isBlank(filter)) {
1578
            return;
1579
        }
1580
        this.delete(ExpressionUtils.createExpression(filter));
1581
    }
1582

    
1583
    @Override
1584
    public void delete(Expression filter) {
1585
        if (filter == null) {
1586
            return;
1587
        }
1588
        boolean pendingFinishEditing = false;
1589
        DisposableFeatureSetIterable features = null;
1590
        try {
1591
            switch (this.mode) {
1592
                case MODE_QUERY:
1593
                    pendingFinishEditing = true;
1594
                    this.edit();
1595
                    break;
1596
                case MODE_APPEND:
1597
                    throw new IllegalStateException("Delete not allowed in append mode.");
1598
                case MODE_FULLEDIT:
1599
                    break;
1600
                case MODE_PASS_THROUGH:
1601
                    if (notifyChange(FeatureStoreNotification.BEFORE_DELETE, filter).isCanceled()) {
1602
                        return;
1603
                    }
1604
                    this.provider.passThroughDelete(filter);
1605
                    notifyChange(FeatureStoreNotification.AFTER_DELETE, filter);                    
1606
                    return;
1607
                default:
1608
                    throw new IllegalStateException("Mode " + this.mode + " not supported.");
1609
            }
1610

    
1611
            FeatureSet fset = this.getFeatureSet(filter);
1612
            features = fset.iterable();
1613
            for (Feature f : features) {
1614
                fset.delete(f);
1615
            }
1616
        } catch (DataException ex) {
1617
            throw new DataRuntimeException(ex.getFormatString(), ex.getMessageKey(), ex.getCode()) {
1618
            };
1619
        } catch (Exception ex) {
1620
            throw new RuntimeException("Can't delete features (" + filter.getPhrase() + ").", ex);
1621
        } finally {
1622
            if (pendingFinishEditing) {
1623
                this.finishEditingQuietly();
1624
            }
1625
            DisposeUtils.disposeQuietly(features);
1626
        }
1627
    }
1628

    
1629
    synchronized public void doDelete(Feature feature) throws DataException {
1630
        if (feature == null) {
1631
            throw new IllegalArgumentException("feature argument can't be null.");
1632
        }
1633
        try {
1634
            checkInEditingMode();
1635
            checkIsOwnFeature(feature);
1636
            if (feature instanceof EditableFeature && !((EditableFeature)feature).isUpdatable()) {
1637
                //La feature no est? persistida en disco
1638
                throw new StoreDeleteEditableFeatureException(getName());
1639
            }
1640
            if (notifyChange(FeatureStoreNotification.BEFORE_DELETE, feature).isCanceled()) {
1641
                return;
1642
            }
1643

    
1644
            //Update the featureManager and the spatialManager
1645
            featureManager.delete(feature);
1646
            spatialManager.deleteFeature(feature);
1647

    
1648
            newVersionOfUpdate();
1649
            hasStrongChanges = true;
1650
            notifyChange(FeatureStoreNotification.AFTER_DELETE, feature);
1651
        } catch (Exception e) {
1652
            throw new StoreDeleteFeatureException(e, this.getName());
1653
        }
1654
    }
1655

    
1656
    @Override
1657
    public synchronized void insert(FeatureSet set) throws DataException {
1658
        switch (mode) {
1659
            case MODE_QUERY:
1660
                throw new NeedEditingModeException(this.getName());
1661

    
1662
            case MODE_APPEND:
1663
            case MODE_FULLEDIT:
1664
            case MODE_PASS_THROUGH:
1665
            try {
1666
                set.accept((Object obj) -> {
1667
                    EditableFeature ef = createNewFeature((Feature) obj);
1668
                    insert(ef);
1669
                });
1670
            } catch (BaseException ex) {
1671
                throw new StoreInsertFeatureException(ex, this.getName());
1672
            }
1673
            break;
1674
        }
1675
    }
1676

    
1677
    private static EditableFeature lastChangedFeature = null;
1678

    
1679
    @Override
1680
    public synchronized void insert(EditableFeature feature)
1681
            throws DataException {
1682
        LOGGER.debug("In editing mode {}, insert feature: {}", mode, feature);
1683
        try {
1684
            switch (mode) {
1685
                case MODE_QUERY:
1686
                    throw new NeedEditingModeException(this.getName());
1687

    
1688
                case MODE_APPEND:
1689
                    checkIsOwnFeature(feature);
1690
                    if (feature.isUpdatable()) {
1691
                        throw new NoNewFeatureInsertException(this.getName());
1692
                    }
1693
                    if (notifyChange(FeatureStoreNotification.BEFORE_INSERT, feature).isCanceled()) {
1694
                        return;
1695
                    }
1696
                    this.featureCount = null;
1697
                    feature.validate(CHECK_RULES_AT_EDITING);
1698
                    provider.append(((DefaultEditableFeature) feature).getData());
1699
                    hasStrongChanges = true;
1700
                    notifyChange(FeatureStoreNotification.AFTER_INSERT, feature);
1701
                    break;
1702

    
1703
                case MODE_FULLEDIT:
1704
                    if (feature.isUpdatable()) {
1705
                        throw new NoNewFeatureInsertException(this.getName());
1706
                    }
1707
                    feature.validate(CHECK_RULES_AT_EDITING);
1708
                    commands.insert(feature);
1709
                    break;
1710

    
1711
                case MODE_PASS_THROUGH:
1712
                    checkIsOwnFeature(feature);
1713
                    if (feature.isUpdatable()) {
1714
                        throw new NoNewFeatureInsertException(this.getName());
1715
                    }
1716
                    if (notifyChange(FeatureStoreNotification.BEFORE_INSERT, feature).isCanceled()) {
1717
                        return;
1718
                    }
1719
                    feature.validate(CHECK_RULES_AT_EDITING);
1720
                    this.provider.passThroughInsert(((DefaultEditableFeature) feature).getData());
1721
                    notifyChange(FeatureStoreNotification.AFTER_INSERT, feature);
1722
                    break;
1723
            }
1724
        } catch (Exception e) {
1725
            throw new StoreInsertFeatureException(e, this.getName());
1726
        }
1727
    }
1728

    
1729
    synchronized public void doInsert(EditableFeature feature)
1730
            throws DataException {
1731
        checkIsOwnFeature(feature);
1732

    
1733
        waitForIndexes();
1734

    
1735
        if (notifyChange(FeatureStoreNotification.BEFORE_INSERT, feature).isCanceled()) {
1736
            return;
1737
        }
1738
        newVersionOfUpdate();
1739
        if ((lastChangedFeature == null)
1740
                || (lastChangedFeature.getSource() != feature.getSource())) {
1741
            lastChangedFeature = feature;
1742
            feature.validate(CHECK_RULES_AT_EDITING);
1743
            lastChangedFeature = null;
1744
        }
1745
        //Update the featureManager and the spatialManager
1746
        ((DefaultFeature) feature).setInserted(true);
1747
        DefaultFeature newFeature = (DefaultFeature) feature.getNotEditableCopy();
1748

    
1749
        featureManager.add(feature);
1750
        spatialManager.insertFeature(newFeature);
1751

    
1752
        hasStrongChanges = true;
1753
        notifyChange(FeatureStoreNotification.AFTER_INSERT, feature);
1754
    }
1755

    
1756
    @Override
1757
    public void update(EditableFeature feature)
1758
            throws DataException {
1759
        switch (this.mode) {
1760
            case MODE_PASS_THROUGH:
1761
                checkIsOwnFeature(feature);
1762
                if (!feature.isUpdatable()) {
1763
                    throw new NoNewFeatureInsertException(this.getName());
1764
                }
1765
                if (notifyChange(FeatureStoreNotification.BEFORE_UPDATE, feature).isCanceled()) {
1766
                    return;
1767
                }
1768
                feature.validate(CHECK_RULES_AT_EDITING);
1769
                this.provider.passThroughUpdate(((DefaultEditableFeature) feature).getData());
1770
                notifyChange(FeatureStoreNotification.AFTER_UPDATE, feature);
1771
                break;
1772
            case MODE_FULLEDIT:
1773
                if(!feature.getType().supportReferences()){
1774
                    throw new UnsupportedOperationException("Can't update store in full edit mode without references support.");
1775
                }
1776
                if (feature.isUpdatable()) {
1777
                    commands.update(feature, feature.getSource());
1778
                    return;
1779
                }
1780
                // FIXME: Deberiamos lanzar aqui un error en lugar de hacer el insert.
1781
                //        O lanzar un mensaje al log?
1782
                insert(feature);
1783
                break;
1784
            default:
1785
                throw new NeedEditingModeException(this.getName());
1786
        }
1787
    }
1788

    
1789
    @Override
1790
    public void update(Object... parameters) throws DataException {
1791
        if (parameters.length == 1) {
1792
            Object param0 = parameters[0];
1793
            if (param0 instanceof EditableFeature) {
1794
                this.update((EditableFeature) param0);
1795
            } else if (param0 instanceof EditableFeatureType) {
1796
                this.update((EditableFeatureType) param0);
1797
            } else {
1798
                throw new IllegalArgumentException("Type of first parameter isn't supported");
1799
            }
1800
            return;
1801
        }
1802

    
1803
        Expression filter = null;
1804
        long end = parameters.length;
1805
        if (parameters.length % 2 == 1) { //IMPAR
1806
            Object param = parameters[parameters.length - 1];
1807
            if (param != null) {
1808
                if (param instanceof Expression) {
1809
                    filter = (Expression) param;
1810
                } else {
1811
                    filter = ExpressionUtils.createExpression(param.toString());
1812
                }
1813
            }
1814
        } else {
1815
            end = parameters.length - 1;
1816
        }
1817

    
1818
        switch (this.mode) {
1819
            case MODE_PASS_THROUGH:
1820
                this.provider.passThroughUpdate(
1821
                        //                    this.getName(), 
1822
                        parameters,
1823
                        filter);
1824
                break;
1825
            case MODE_FULLEDIT:
1826
                FeatureSet set = this.getFeatureSet(filter);
1827
                DisposableIterator it = set.fastIterator();
1828
                while (it.hasNext()) {
1829
                    Feature feature = (Feature) it.next();
1830
                    EditableFeature ef = feature.getEditable();
1831
                    for (int i = 0; i < end; i += 2) {
1832
                        String name = (String) parameters[i];
1833
                        Object value = parameters[i + 1];
1834
                        ef.set(name, value);
1835
                    }
1836
                    set.update(ef);
1837
                }
1838
                DisposeUtils.disposeQuietly(it);
1839
                DisposeUtils.disposeQuietly(set);
1840
                break;
1841
            default:
1842
                throw new NeedEditingModeException(this.getName());
1843
        }
1844
    }
1845

    
1846
    synchronized public void doUpdate(EditableFeature feature, Feature oldFeature)
1847
            throws DataException {
1848
        try {
1849
            checkInEditingMode();
1850
            checkIsOwnFeature(feature);
1851
            if (notifyChange(FeatureStoreNotification.BEFORE_UPDATE, feature).isCanceled()) {
1852
                return;
1853
            }
1854
            newVersionOfUpdate();
1855
            if ((lastChangedFeature == null)
1856
                    || (lastChangedFeature.getSource() != feature.getSource())) {
1857
                lastChangedFeature = feature;
1858
                feature.validate(CHECK_RULES_AT_EDITING);
1859
                lastChangedFeature = null;
1860
            }
1861

    
1862
            //Update the featureManager and the spatialManager
1863
            Feature newf = feature.getNotEditableCopy();
1864
            featureManager.update(feature, oldFeature);
1865
            spatialManager.updateFeature(newf, oldFeature);
1866

    
1867
            hasStrongChanges = true;
1868
            notifyChange(FeatureStoreNotification.AFTER_UPDATE, feature);
1869
        } catch (Exception e) {
1870
            throw new StoreUpdateFeatureException(e, this.getName());
1871
        }
1872
    }
1873

    
1874
    @Override
1875
    synchronized public void redo() throws RedoException {
1876
        Command redo = commands.getNextRedoCommand();
1877
        try {
1878
            checkInEditingMode();
1879
        } catch (NeedEditingModeException ex) {
1880
            throw new RedoException(redo, ex);
1881
        }
1882
        if (notifyChange(FeatureStoreNotification.BEFORE_REDO, redo).isCanceled()) {
1883
            return;
1884
        }
1885
        newVersionOfUpdate();
1886
        commands.redo();
1887
        hasStrongChanges = true;
1888
        notifyChange(FeatureStoreNotification.AFTER_REDO, redo);
1889
    }
1890

    
1891
    @Override
1892
    synchronized public void undo() throws UndoException {
1893
        Command undo = commands.getNextUndoCommand();
1894
        try {
1895
            checkInEditingMode();
1896
        } catch (NeedEditingModeException ex) {
1897
            throw new UndoException(undo, ex);
1898
        }
1899
        if (notifyChange(FeatureStoreNotification.BEFORE_UNDO, undo).isCanceled()) {
1900
            return;
1901
        }
1902
        newVersionOfUpdate();
1903
        commands.undo();
1904
        hasStrongChanges = true;
1905
        notifyChange(FeatureStoreNotification.AFTER_UNDO, undo);
1906
    }
1907

    
1908
    @Override
1909
    public List getRedoInfos() {
1910
        if (isEditing() && (commands != null)) {
1911
            return commands.getRedoInfos();
1912
        } else {
1913
            return null;
1914
        }
1915
    }
1916

    
1917
    @Override
1918
    public List getUndoInfos() {
1919
        if (isEditing() && (commands != null)) {
1920
            return commands.getUndoInfos();
1921
        } else {
1922
            return null;
1923
        }
1924
    }
1925

    
1926
    public synchronized FeatureCommandsStack getCommandsStack()
1927
            throws DataException {
1928
        checkInEditingMode();
1929
        return commands;
1930
    }
1931

    
1932
    @Override
1933
    public boolean cancelEditingQuietly() {
1934
        try {
1935
            this.cancelEditing();
1936
            return true;
1937
        } catch (Exception ex) {
1938
            LOGGER.debug("Can't cancel editing", ex);
1939
            return false;
1940
        }
1941
    }
1942

    
1943
    @Override
1944
    synchronized public void cancelEditing() throws DataException {
1945
        try {
1946
            switch (mode) {
1947
                case MODE_QUERY:
1948
                    throw new NeedEditingModeException(this.getName());
1949

    
1950
                case MODE_APPEND:
1951
                    if (notifyChange(FeatureStoreNotification.BEFORE_CANCELEDITING).isCanceled()) {
1952
                        return;
1953
                    }
1954
                    provider.abortAppend();
1955
                    exitEditingMode();
1956
                    ((FeatureSelection) this.getSelection()).deselectAll();
1957
                    updateIndexes();
1958
                    notifyChange(FeatureStoreNotification.AFTER_CANCELEDITING);
1959
                    break;
1960

    
1961
                case MODE_FULLEDIT:
1962
                    boolean clearSelection = this.hasStrongChanges;
1963
                    if (this.selection instanceof FeatureReferenceSelection) {
1964
                        clearSelection = this.hasStrongChanges || this.featureManager.hasNews();
1965
                    }
1966
                    if (notifyChange(FeatureStoreNotification.BEFORE_CANCELEDITING).isCanceled()) {
1967
                        return;
1968
                    }
1969
                    exitEditingMode();
1970
                    if (clearSelection) {
1971
                        ((FeatureSelection) this.getSelection()).deselectAll();
1972
                    }
1973
                    updateIndexes();
1974
                    notifyChange(FeatureStoreNotification.AFTER_CANCELEDITING);
1975
                    break;
1976

    
1977
                case MODE_PASS_THROUGH:
1978
                    if (notifyChange(FeatureStoreNotification.BEFORE_CANCELEDITING).isCanceled()) {
1979
                        return;
1980
                    }
1981
                    exitEditingMode();
1982
                    ((FeatureSelection) this.getSelection()).deselectAll();
1983
                    updateIndexes();
1984
                    notifyChange(FeatureStoreNotification.AFTER_CANCELEDITING);
1985
                    break;
1986
            }
1987
        } catch (Exception e) {
1988
            throw new StoreCancelEditingException(e, this.getName());
1989
        }
1990
    }
1991

    
1992
    @Override
1993
    public boolean finishEditingQuietly() {
1994
        try {
1995
            this.finishEditing();
1996
            return true;
1997
        } catch (Exception ex) {
1998
            LOGGER.debug("Can't finish editing", ex);
1999
            return false;
2000
        }
2001
    }
2002

    
2003
    @Override
2004
    synchronized public void finishEditing() throws DataException {
2005
        LOGGER.debug("finish editing of mode: {}", mode);
2006
        try {
2007
            Map<String, List<FeatureAttributeDescriptor>> computedFields = this.getComputedFields();
2008
            switch (mode) {
2009
                case MODE_QUERY:
2010
                    throw new NeedEditingModeException(this.getName());
2011

    
2012
                case MODE_APPEND:
2013
                    if (selection != null) {
2014
                        selection = null;
2015
                    }
2016
                    if (notifyChange(FeatureStoreNotification.BEFORE_FINISHEDITING).isCanceled()) {
2017
                        return;
2018
                    }
2019
                    saveDALFile();
2020
                    provider.endAppend();
2021
                    exitEditingMode();
2022
                    this.updateComputedFields(computedFields);
2023
                    loadDALFile();
2024
                    updateIndexes();
2025
                    notifyChange(FeatureStoreNotification.AFTER_FINISHEDITING);
2026
                    break;
2027

    
2028
                case MODE_FULLEDIT:
2029
                    if (featureManager.hasChanges() || featureTypeManager.hasChanges()) {
2030
                        if (hasStrongChanges && !this.allowWrite()) {
2031
                            throw new WriteNotAllowedException(getName());
2032
                        }
2033
                        if (notifyChange(FeatureStoreNotification.PREPARING_FINISHEDITING).isCanceled()) {
2034
                            return;
2035
                        }
2036
                        if (hasStrongChanges) {
2037
                            validateFeaturesAtFinishEditing();
2038
                        }
2039
                        if (notifyChange(FeatureStoreNotification.BEFORE_FINISHEDITING,
2040
                                featureManager.getDeleted(),
2041
                                featureManager.getInsertedFeatures(),
2042
                                featureManager.getUpdatedFeatures(),
2043
                                featureTypeManager.getFeatureTypesChanged().iterator(),
2044
                                featureManager.isSelectionCompromised()).isCanceled()) {
2045
                            return;
2046
                        }
2047
                        saveDALFile();
2048
                        if (featureManager.isSelectionCompromised() && selection != null) {
2049
                            selection = null;
2050
                        }
2051
                        if (hasStrongChanges) {
2052
                            // This will throw a PerformEditingException if the provider
2053
                            // does not accept the changes (for example, an invalid field name)
2054
                            provider.performChanges(featureManager.getDeleted(),
2055
                                    featureManager.getInserted(),
2056
                                    featureManager.getUpdated(),
2057
                                    removeCalculatedAttributes(featureTypeManager.getFeatureTypesChanged()).iterator());
2058

    
2059
                        }
2060
                        this.updateComputedFields(computedFields);
2061
                        exitEditingMode();
2062
                        loadDALFile();
2063
                        updateIndexes();
2064
                    } else {
2065
                        exitEditingMode();
2066
                    }
2067
                    notifyChange(FeatureStoreNotification.AFTER_FINISHEDITING);
2068
                    break;
2069
                case MODE_PASS_THROUGH:
2070
                    if (selection != null) {
2071
                        selection = null;
2072
                    }
2073
                    if (notifyChange(FeatureStoreNotification.BEFORE_FINISHEDITING).isCanceled()) {
2074
                        return;
2075
                    }
2076
                    exitEditingMode();
2077
                    updateIndexes();
2078
                    notifyChange(FeatureStoreNotification.AFTER_FINISHEDITING);
2079
                    break;
2080
            }
2081
        } catch (ValidateFeaturesException | WriteNotAllowedException ex) {
2082
            // Don't notify failed.
2083
            throw ex;
2084
        } catch (PerformEditingException pee) {
2085
            notifyChange(FeatureStoreNotification.FAILED_FINISHEDITING);
2086
            throw new WriteException(provider.getSourceId().toString(), pee);
2087
        } catch (Exception e) {
2088
            notifyChange(FeatureStoreNotification.FAILED_FINISHEDITING);
2089
            throw new FinishEditingException(e);
2090
        }
2091
    }
2092

    
2093
    @Override
2094
    public String getEditingSession() {
2095
        return this.editingSessionCode;
2096
    }
2097

    
2098
    private Map<String, List<FeatureAttributeDescriptor>> getComputedFields() throws DataException {
2099
        Map<String, List<FeatureAttributeDescriptor>> r = new HashMap<>();
2100

    
2101
        List<FeatureType> theTypes = new ArrayList<>();
2102
        theTypes.addAll(this.getFeatureTypes());
2103
        theTypes.add(this.getDefaultFeatureType());
2104
        for (int n = 0; n < theTypes.size(); n++) {
2105
            FeatureType type = theTypes.get(n);
2106
            for (FeatureAttributeDescriptor attrdesc : type) {
2107
                FeatureAttributeEmulator emulator = attrdesc.getFeatureAttributeEmulator();
2108
                if (emulator != null) {
2109
                    List<FeatureAttributeDescriptor> l = r.get(type.getId());
2110
                    if (l == null) {
2111
                        l = new ArrayList<>();
2112
                        r.put(type.getId(), l);
2113
                    }
2114
                    l.add(attrdesc);
2115
                }
2116
            }
2117
        }
2118
        return r;
2119
    }
2120

    
2121
    private void updateComputedFields(Map<String, List<FeatureAttributeDescriptor>> computedFields) throws DataException {
2122

    
2123
        List<FeatureType> theTypes = new ArrayList<>();
2124
        theTypes.addAll(this.getFeatureTypes());
2125
        theTypes.add(this.getDefaultFeatureType());
2126
        for (int n = 0; n < theTypes.size(); n++) {
2127
            DefaultFeatureType type = (DefaultFeatureType) theTypes.get(n);
2128
            List<FeatureAttributeDescriptor> x = computedFields.get(type.getId());
2129
            if (x != null && !x.isEmpty()) {
2130
                for (FeatureAttributeDescriptor attrdesc : x) {
2131
                    if (type.get(attrdesc.getName()) == null) {
2132
                        type.add(attrdesc);
2133
                    }
2134
                }
2135
            }
2136
        }
2137

    
2138
    }
2139

    
2140
    private List<FeatureTypeChanged> removeCalculatedAttributes(List<FeatureTypeChanged> ftypes) {
2141
        // FIXME: Falta por implementar
2142
//        for (FeatureStoreProvider.FeatureTypeChanged ftype : ftypes) {
2143
//            EditableFeatureType target = (EditableFeatureType) ftype.getTarget();
2144
//            for (FeatureAttributeDescriptor attributeDescriptor : ftype.getSource().getAttributeDescriptors()) {
2145
//                if (attributeDescriptor.isComputed()) {
2146
//                    target.remove(attributeDescriptor.getName());
2147
//                }
2148
//            }
2149
//        }
2150
        return ftypes;
2151
    }
2152

    
2153
    private void clearResourcesCache() {
2154
        ResourcesStorage theResourcesStorage = null;
2155
        try {
2156
            theResourcesStorage = this.getResourcesStorage();
2157
            if (theResourcesStorage == null ) {
2158
                return;
2159
            }
2160
            theResourcesStorage.clearCache();
2161
        } catch (Throwable ex) {
2162
            LOGGER.warn("Can't clear resources for store '"+this.getFullNameForTraces()+"'.", ex);
2163
        } finally {
2164
            DisposeUtils.disposeQuietly(theResourcesStorage);
2165
        }
2166
    }
2167
    
2168
    private void saveDALFile() {
2169
        if( this.ignoreDALResource ) {
2170
            return;
2171
        }
2172
        org.gvsig.tools.resourcesstorage.ResourcesStorage.Resource resource = null;
2173
        ResourcesStorage theResourcesStorage = null;
2174
        try {
2175
            theResourcesStorage = this.getResourcesStorage();
2176
            if (theResourcesStorage == null || theResourcesStorage.isReadOnly()) {
2177
                return;
2178
            }
2179
            resource = theResourcesStorage.getResource("dal");
2180
            if (resource == null || resource.isReadOnly()) {
2181
                return;
2182
            }
2183
            DALFile dalFile = DALFile.getDALFile();
2184
            dalFile.setStore(this);
2185
            if (!dalFile.isEmpty()) {
2186
                dalFile.write(resource);
2187
            }
2188
        } catch (Throwable ex) {
2189
            LOGGER.warn("Can't save DAL resource", ex);
2190
        } finally {
2191
            IOUtils.closeQuietly(resource);
2192
            DisposeUtils.disposeQuietly(theResourcesStorage);
2193
        }
2194
    }
2195

    
2196
    private void loadDALFile() {
2197
        if( this.ignoreDALResource ) {
2198
            return;
2199
        }
2200
        org.gvsig.tools.resourcesstorage.ResourcesStorage.Resource resource = null;
2201
        ResourcesStorage theResourcesStorage = null;
2202
        try {
2203
            theResourcesStorage = this.getResourcesStorage();
2204
            if (theResourcesStorage == null) {
2205
                return;
2206
            }
2207
            resource = theResourcesStorage.getResource("dal");
2208
            if (resource == null || !resource.exists()) {
2209
                return;
2210
            }
2211
            DALFile dalFile = DALFile.getDALFile(resource);
2212
            if (!dalFile.isEmpty()) {
2213
                dalFile.updateStore(this);
2214
            }
2215
        } catch (Throwable ex) {
2216
            if (resource == null || theResourcesStorage == null) {
2217
                if (theResourcesStorage == null) {
2218
                    LOGGER.warn("Can't load DAL resource (resname=null, resurl=null, storage=null)", ex);
2219
                } else {
2220
                    LOGGER.warn("Can't load DAL resource (resname=null, resurl=null, storage=" + theResourcesStorage.getClass().getName() + ").", ex);
2221
                }
2222
            } else {
2223
                LOGGER.warn("Can't load DAL resource (resname=" + resource.getName() + ", resurl=" + Objects.toString(resource.getURL()) + ", storage=" + theResourcesStorage.getClass().getName() + ").", ex);
2224
            }
2225
        } finally {
2226
            IOUtils.closeQuietly(resource);
2227
            DisposeUtils.disposeQuietly(theResourcesStorage);
2228
        }
2229
    }
2230

    
2231
    /**
2232
     * Save changes in the provider without leaving the edit mode. Do not call
2233
     * observers to communicate a change of ediding mode. The operation's
2234
     * history is eliminated to prevent inconsistencies in the data.
2235
     *
2236
     * @throws DataException
2237
     */
2238
    @Override
2239
    synchronized public void commitChanges() throws DataException {
2240
        LOGGER.debug("commitChanges of mode: {}", mode);
2241
        if (!canCommitChanges()) {
2242
            throw new WriteNotAllowedException(getName());
2243
        }
2244
        try {
2245
            switch (mode) {
2246
                case MODE_QUERY:
2247
                    throw new NeedEditingModeException(this.getName());
2248

    
2249
                case MODE_APPEND:
2250
                    this.provider.endAppend();
2251
                    exitEditingMode();
2252
                    invalidateIndexes();
2253
                    this.provider.beginAppend();
2254
                    break;
2255

    
2256
                case MODE_FULLEDIT:
2257
                    if (hasStrongChanges && !this.allowWrite()) {
2258
                        throw new WriteNotAllowedException(getName());
2259
                    }
2260
                    // FIXME: OOhh!!!! no se disparan eventos, VCSGis no se entera de estos cambios.
2261
                    if (hasStrongChanges) {
2262
                        validateFeaturesAtFinishEditing();
2263
                        provider.performChanges(featureManager.getDeleted(),
2264
                                featureManager.getInserted(),
2265
                                featureManager.getUpdated(),
2266
                                removeCalculatedAttributes(featureTypeManager.getFeatureTypesChanged()).iterator());
2267
                    }
2268
                    invalidateIndexes();
2269
                    featureManager = new FeatureManager(this);
2270
                    featureTypeManager = new FeatureTypeManager(this);
2271
                    spatialManager = new SpatialManager(this);
2272

    
2273
                    commands
2274
                            = new DefaultFeatureCommandsStack(this, featureManager,
2275
                                    spatialManager, featureTypeManager);
2276
                    featureCount = null;
2277
                    hasStrongChanges = false;
2278
                    break;
2279
            }
2280
        } catch (Exception e) {
2281
            throw new FinishEditingException(e);
2282
        }
2283
    }
2284

    
2285
    @Override
2286
    synchronized public boolean canCommitChanges() throws DataException {
2287
        if (!this.allowWrite()) {
2288
            return false;
2289
        }
2290
        switch (mode) {
2291
            default:
2292
            case MODE_QUERY:
2293
                return false;
2294

    
2295
            case MODE_APPEND:
2296
                return true;
2297

    
2298
            case MODE_FULLEDIT:
2299
                List types = this.getFeatureTypes();
2300
                for (int i = 0; i < types.size(); i++) {
2301
                    Object type = types.get(i);
2302
                    if (type instanceof DefaultEditableFeatureType) {
2303
                        if (((DefaultEditableFeatureType) type).hasStrongChanges()) {
2304
                            return false;
2305
                        }
2306
                    }
2307
                }
2308
                return true;
2309
        }
2310
    }
2311

    
2312
    @Override
2313
    public void beginEditingGroup(String description)
2314
            throws NeedEditingModeException {
2315
        checkInEditingMode();
2316
        commands.startComplex(description);
2317
    }
2318

    
2319
    @Override
2320
    public void endEditingGroup() throws NeedEditingModeException {
2321
        checkInEditingMode();
2322
        commands.endComplex();
2323
    }
2324

    
2325
    @Override
2326
    public boolean isAppendModeSupported() {
2327
        return this.provider.supportsAppendMode();
2328
    }
2329

    
2330
    @Override
2331
    public void export(DataServerExplorer explorer, String provider,
2332
            NewFeatureStoreParameters params, String name) throws DataException {
2333

    
2334
        if (this.getFeatureTypes().size() != 1) {
2335
            throw new NotYetImplemented(
2336
                    "export whith more than one type not yet implemented");
2337
        }
2338
        FeatureSelection featureSelection = (FeatureSelection) getSelection();
2339
        FeatureStore target = null;
2340
        FeatureSet features = null;
2341
        DisposableIterator iterator = null;
2342
        try {
2343
            FeatureType type = this.getDefaultFeatureType();
2344
            if ((params.getDefaultFeatureType() == null)
2345
                    || (params.getDefaultFeatureType().size() == 0)) {
2346
                params.setDefaultFeatureType(type.getEditable());
2347

    
2348
            }
2349
            explorer.add(provider, params, true);
2350
            DataManager manager = DALLocator.getDataManager();
2351

    
2352
            DataStoreParameters openParams = explorer.get(name); //OpenFeatureStoreParameters) manager.createStoreParameters(explorer.getProviderName());
2353
//            ToolsLocator.getDynObjectManager().copy(params, openParams);
2354

    
2355
            target = (FeatureStore) manager.openStore(provider, openParams);
2356
            FeatureType targetType = target.getDefaultFeatureType();
2357

    
2358
            target.edit(MODE_APPEND);
2359
            FeatureAttributeDescriptor[] pkattrs = type.getPrimaryKey();
2360
            if (featureSelection.getSize() > 0) {
2361
                features = this.getFeatureSelection();
2362
            } else {
2363
                if ((pkattrs != null) && (pkattrs.length > 0)) {
2364
                    FeatureQuery query = createFeatureQuery();
2365
                    for (FeatureAttributeDescriptor pkattr : pkattrs) {
2366
                        query.getOrder().add(pkattr.getName(), true);
2367
                    }
2368
                    features = this.getFeatureSet(query);
2369
                } else {
2370
                    features = this.getFeatureSet();
2371
                }
2372
            }
2373
            iterator = features.fastIterator();
2374
            while (iterator.hasNext()) {
2375
                DefaultFeature feature = (DefaultFeature) iterator.next();
2376
                target.insert(target.createNewFeature(targetType, feature));
2377
            }
2378
            target.finishEditing();
2379
            target.dispose();
2380
        } catch (Exception e) {
2381
            throw new DataExportException(e, params.toString());
2382
        } finally {
2383
            dispose(iterator);
2384
            dispose(features);
2385
            dispose(target);
2386
        }
2387
    }
2388

    
2389
    @Override
2390
    public void copyTo(final FeatureStore target) {
2391
        boolean finishEditingAtEnd = false;
2392
        try {
2393
            if (!target.isEditing() && !target.isAppending()) {
2394
                finishEditingAtEnd = true;
2395
                target.edit(MODE_APPEND);
2396
            }
2397
            this.accept((Object obj) -> {
2398
                Feature f_src = (Feature) obj;
2399
                EditableFeature f_dst = target.createNewFeature(f_src);
2400
                target.insert(f_dst);
2401
            });
2402
            if (finishEditingAtEnd) {
2403
                target.finishEditing();
2404
            }
2405

    
2406
        } catch (Exception ex) {
2407
            try {
2408
                if (finishEditingAtEnd) {
2409
                    target.cancelEditing();
2410
                }
2411
            } catch (Exception ex1) {
2412
            }
2413
            throw new RuntimeException("Can't copy store.", ex);
2414
        }
2415

    
2416
    }
2417

    
2418
    //
2419
    // ====================================================================
2420
    // Obtencion de datos
2421
    // getDataCollection, getFeatureCollection
2422
    //
2423
    @Override
2424
    public DataSet getDataSet() throws DataException {
2425
        return this.getFeatureSet((FeatureQuery)null);
2426
    }
2427

    
2428
    @Override
2429
    public DataSet getDataSet(DataQuery dataQuery) throws DataException {
2430
        return this.getFeatureSet((FeatureQuery)dataQuery);
2431
    }
2432

    
2433
    @Override
2434
    public void getDataSet(Observer observer) throws DataException {
2435
        checkNotInAppendMode();
2436
        this.getFeatureSet(null, observer);
2437
    }
2438

    
2439
    @Override
2440
    public void getDataSet(DataQuery dataQuery, Observer observer)
2441
            throws DataException {
2442
        checkNotInAppendMode();
2443
        this.getFeatureSet((FeatureQuery) dataQuery, observer);
2444
    }
2445

    
2446
    @Override
2447
    public FeatureSet getFeatureSet() throws DataException {
2448
        return this.getFeatureSet((FeatureQuery) null);
2449
    }
2450

    
2451
    @Override
2452
    public FeatureSet getFeatureSet(FeatureQuery featureQuery)
2453
            throws DataException {
2454
        checkNotInAppendMode();
2455
        if (featureQuery == null) {
2456
            featureQuery = new DefaultFeatureQuery(this.getDefaultFeatureType());
2457
        } else if( featureQuery.hasAggregateFunctions() || featureQuery.hasGroupByColumns() ) {
2458
            // Si tenemos datos por persistir en la bbdd (bien por que estamos en modo 
2459
            // append(batchsize) o por que estamos en modo fulledit y hay cambios
2460
            // realizados, las agrupaciones y funciones de agregado, como las gestiona
2461
            // la bbdd, pueden no dar resultados correctos. Asi que no dejamos hacer
2462
            // estas operaciones.
2463
            if( this.mode==MODE_APPEND  ) {
2464
                throw new UnsupportedOperationException("Can't create a set with aggregate functions or group by columns in append mode");
2465
            }
2466
            if( this.mode == MODE_FULLEDIT ) {
2467
                if( this.featureManager==null || this.featureManager.getPendingChangesCount()>0 ) {
2468
                   throw new UnsupportedOperationException("Can't create a set with aggregate functions or group by columns with editing changes");
2469
                }
2470
            }
2471
        }
2472
        addRequiredAttributes(featureQuery);
2473
        return new DefaultFeatureSet(this, featureQuery);
2474
    }
2475

    
2476
    @Override
2477
    public FeatureSet getFeatureSet(String filter) throws DataException {
2478
        return this.getFeatureSet(filter, null, true);
2479
    }
2480

    
2481
    @Override
2482
    public FeatureSet getFeatureSet(String filter, String sortBy) throws DataException {
2483
        return this.getFeatureSet(filter, sortBy, true);
2484
    }
2485

    
2486
    @Override
2487
    public FeatureSet getFeatureSet(Expression filter) throws DataException {
2488
        return this.getFeatureSet(filter, null, true);
2489
    }
2490

    
2491
    @Override
2492
    public FeatureSet getFeatureSet(Expression filter, String sortBy) throws DataException {
2493
        return this.getFeatureSet(filter, sortBy, true);
2494
    }
2495

    
2496
    @Override
2497
    public FeatureSet getFeatureSet(Expression filter, String sortBy, boolean asc) throws DataException {
2498
        FeatureQuery query = this.createFeatureQuery(filter, sortBy, asc);
2499
        return this.getFeatureSet(query);
2500
    }
2501

    
2502
    @Override
2503
    public FeatureSet getFeatureSet(String filter, String sortBy, boolean asc) throws DataException {
2504
        FeatureQuery query = this.createFeatureQuery(filter, sortBy, asc);
2505
        return this.getFeatureSet(query);
2506
    }
2507

    
2508
    @Override
2509
    public List<Feature> getFeatures(String filter) {
2510
        return this.getFeatures(filter, null, true);
2511
    }
2512

    
2513
    @Override
2514
    public List<Feature> getFeatures(String filter, String sortBy) {
2515
        return this.getFeatures(filter, sortBy, true);
2516
    }
2517

    
2518
    @Override
2519
    public List<Feature> getFeatures(String filter, String sortBy, boolean asc) {
2520
        FeatureQuery query = this.createFeatureQuery(filter, sortBy, asc);
2521
        return this.getFeatures(query, 0);
2522
    }
2523

    
2524
    @Override
2525
    public List<Feature> getFeatures(Expression filter) {
2526
        return this.getFeatures(filter, null, true);
2527
    }
2528

    
2529
    @Override
2530
    public List<Feature> getFeatures(Expression filter, String sortBy) {
2531
        return this.getFeatures(filter, sortBy, true);
2532
    }
2533

    
2534
    @Override
2535
    public List<Feature> getFeatures(Expression filter, String sortBy, boolean asc) {
2536
        FeatureQuery query = this.createFeatureQuery(filter, sortBy, asc);
2537
        return this.getFeatures(query, 0);
2538
    }
2539

    
2540
    @Override
2541
    public List<Feature> getFeatures(FeatureQuery query) {
2542
        return this.getFeatures(query, 0);
2543
    }
2544

    
2545
    @Override
2546
    public List<Feature> getFeatures(FeatureQuery query, int pageSize) {
2547
        try {
2548
            if (pageSize <= 0) {
2549
                pageSize = 100;
2550
            }
2551
            addRequiredAttributes(query);
2552
            FeaturePagingHelper pager = this.dataManager.createFeaturePagingHelper(this, query, pageSize);
2553
            return pager.asList();
2554
        } catch (BaseException ex) {
2555
            throw new RuntimeException("Can't create the list of features.", ex);
2556
        }
2557
    }
2558
        
2559
    @Override
2560
    public List<Feature> getFeatures() {
2561
        return this.getFeatures(null, 0);
2562
    }
2563

    
2564
    @Override
2565
    public GetItemWithSizeIsEmptyAndIterator64<Feature> getFeatures64() {
2566
        return this.getFeatures64(null, 0);
2567
    }
2568

    
2569
    @Override
2570
    public GetItemWithSizeIsEmptyAndIterator64<Feature> getFeatures64(String filter) {
2571
        return this.getFeatures64(filter, null, true);
2572
    }
2573

    
2574
    @Override
2575
    public GetItemWithSizeIsEmptyAndIterator64<Feature> getFeatures64(String filter, String sortBy, boolean asc) {
2576
        FeatureQuery query = this.createFeatureQuery(filter, sortBy, asc);
2577
        return this.getFeatures64(query, 0);
2578
    }
2579

    
2580
    @Override
2581
    public GetItemWithSizeIsEmptyAndIterator64<Feature> getFeatures64(FeatureQuery query, int pageSize) {
2582
        try {
2583
            if (pageSize <= 0) {
2584
                pageSize = 100;
2585
            }
2586
            FeaturePagingHelper pager = this.dataManager.createFeaturePagingHelper(this, query, pageSize);
2587
            return pager;
2588
        } catch (BaseException ex) {
2589
            throw new RuntimeException("Can't create the list of features.", ex);
2590
        }
2591
    }
2592

    
2593
    @Override
2594
    public Feature first() throws DataException {
2595
        return this.findFirst((FeatureQuery) null);
2596
    }
2597

    
2598
    @Override
2599
    public Feature findFirst(String filter) throws DataException {
2600
        return this.findFirst(filter, (String) null, true);
2601
    }
2602

    
2603
    @Override
2604
    public Feature findFirst(String filter, String sortBy) throws DataException {
2605
        return this.findFirst(filter, sortBy, true);
2606
    }
2607

    
2608
    @Override
2609
    public Feature findFirst(String filter, String sortBy, boolean asc) throws DataException {
2610
        FeatureQuery query = this.createFeatureQuery(filter, sortBy, asc);
2611
        return findFirst(query);
2612
    }
2613

    
2614
    @Override
2615
    public Feature findFirst(String filter, Expression sortBy, boolean asc) throws DataException {
2616
        FeatureQuery query = this.createFeatureQuery(filter, sortBy, asc);
2617
        return findFirst(query);
2618
    }
2619

    
2620
    @Override
2621
    public Feature findFirst(Expression filter) throws DataException {
2622
        return this.findFirst(filter, (String) null, true);
2623
    }
2624

    
2625
    @Override
2626
    public Feature findFirst(Expression filter, String sortBy) throws DataException {
2627
        return this.findFirst(filter, sortBy, true);
2628
    }
2629

    
2630
    @Override
2631
    public Feature findFirst(Expression filter, String sortBy, boolean asc) throws DataException {
2632
        FeatureQuery query = this.createFeatureQuery(filter, sortBy, asc);
2633
        return findFirst(query);
2634
    }
2635

    
2636
    @Override
2637
    public Feature findFirst(Expression filter, Expression sortBy, boolean asc) throws DataException {
2638
        FeatureQuery query = this.createFeatureQuery(filter, sortBy, asc);
2639
        return findFirst(query);
2640
    }
2641

    
2642
    @Override
2643
    public Feature findFirst(FeatureQuery query) throws DataException {
2644
        if (query == null) {
2645
            query = this.createFeatureQuery();
2646
        } else {
2647
            query = query.getCopy();
2648
        }
2649
        query.setLimit(1);
2650
        final MutableObject<Feature> feature = new MutableObject<>();
2651
        try {
2652
            this.accept((Object obj) -> {
2653
                feature.setValue((Feature) obj);
2654
                throw new VisitCanceledException();
2655
            }, query);
2656
        } catch (VisitCanceledException ex) {
2657

    
2658
        } catch (DataException ex) {
2659
            throw ex;
2660
        } catch (Exception ex) {
2661
            throw new RuntimeException("", ex);
2662
        }
2663
        return feature.getValue();
2664
    }
2665

    
2666
    @Override
2667
    public void accept(Visitor visitor) throws BaseException {
2668
        this.accept(visitor, null);
2669
    }
2670

    
2671
    @Override
2672
    public void accept(Visitor visitor, DataQuery dataQuery)
2673
            throws BaseException {
2674
        FeatureSet set = getFeatureSet((FeatureQuery) dataQuery);
2675
        try {
2676
            set.accept(visitor);
2677
        } finally {
2678
            set.dispose();
2679
        }
2680
    }
2681

    
2682
    public FeatureType getFeatureType(FeatureQuery featureQuery)
2683
            throws DataException {
2684
        DefaultFeatureType fType
2685
                = (DefaultFeatureType) this.getFeatureType(featureQuery
2686
                        .getFeatureTypeId());
2687
        if (featureQuery.hasAttributeNames()
2688
                || featureQuery.hasConstantsAttributeNames()
2689
                || fType.hasRequiredFields()) {
2690
            if (featureQuery.hasGroupByColumns()) {
2691
                return fType.getSubtype(featureQuery.getAttributeNames(), featureQuery.getConstantsAttributeNames(), false);
2692
            } else {
2693
                return fType.getSubtype(featureQuery.getAttributeNames(), featureQuery.getConstantsAttributeNames());
2694
            }
2695
        }
2696
        return fType;
2697
    }
2698

    
2699
    @Override
2700
    public void getFeatureSet(Observer observer) throws DataException {
2701
        checkNotInAppendMode();
2702
        this.getFeatureSet(null, observer);
2703
    }
2704

    
2705
    @Override
2706
    public void getFeatureSet(FeatureQuery query, Observer observer)
2707
            throws DataException {
2708
        class LoadInBackGround implements Runnable {
2709

    
2710
            private final FeatureStore store;
2711
            private final FeatureQuery query;
2712
            private final Observer observer;
2713

    
2714
            public LoadInBackGround(FeatureStore store, FeatureQuery query,
2715
                    Observer observer) {
2716
                this.store = store;
2717
                this.query = query;
2718
                this.observer = observer;
2719
            }
2720

    
2721
            void notify(FeatureStoreNotification theNotification) {
2722
                observer.update(store, theNotification);
2723
            }
2724

    
2725
            @Override
2726
            public void run() {
2727
                FeatureSet set = null;
2728
                try {
2729
                    set = store.getFeatureSet(query);
2730
                    notify(new DefaultFeatureStoreNotification(store,
2731
                            FeatureStoreNotification.LOAD_FINISHED, set));
2732
                } catch (Exception e) {
2733
                    notify(new DefaultFeatureStoreNotification(store,
2734
                            FeatureStoreNotification.LOAD_FINISHED, e));
2735
                } finally {
2736
                    dispose(set);
2737
                }
2738
            }
2739
        }
2740

    
2741
        checkNotInAppendMode();
2742
        if (query == null) {
2743
            query = new DefaultFeatureQuery(this.getDefaultFeatureType());
2744
        }
2745
        LoadInBackGround task = new LoadInBackGround(this, query, observer);
2746
        Thread thread = new Thread(task, "Load Feature Set in background");
2747
        thread.start();
2748
    }
2749

    
2750
    @Override
2751
    public Feature getFeatureByReference(FeatureReference reference)
2752
            throws DataException {
2753
        checkNotInAppendMode();
2754
        FeatureReferenceProviderServices ref = (FeatureReferenceProviderServices) reference;
2755
        FeatureType featureType;
2756
        if (ref.getFeatureTypeId() == null) {
2757
            featureType = this.getDefaultFeatureType();
2758
        } else {
2759
            featureType = this.getFeatureType(ref.getFeatureTypeId());
2760
        }
2761
        return this.getFeatureByReference(reference, featureType);
2762
    }
2763

    
2764
    @Override
2765
    public Feature getFeatureByReference(FeatureReference reference,
2766
            FeatureType featureType) throws DataException {
2767
        checkNotInAppendMode();
2768
        featureType = fixFeatureType((DefaultFeatureType) featureType);
2769
        if (this.mode == MODE_FULLEDIT) {
2770
            Feature f = featureManager.get(reference, this, featureType);
2771
            if (f != null) {
2772
                return f;
2773
            }
2774
        }
2775

    
2776
        FeatureType sourceFeatureType = featureType;
2777
        if (!this.transforms.isEmpty()) {
2778
            sourceFeatureType = this.transforms.getSourceFeatureTypeFrom(featureType);
2779
        }
2780
        // TODO comprobar que el id es de este store
2781

    
2782
        DefaultFeature feature
2783
                = new DefaultFeature(this,
2784
                        this.provider.getFeatureProviderByReference(
2785
                                (FeatureReferenceProviderServices) reference, sourceFeatureType));
2786

    
2787
        if (!this.transforms.isEmpty()) {
2788
            return this.transforms.applyTransform(feature, featureType);
2789
        }
2790
        return feature;
2791
    }
2792

    
2793
    //
2794
    // ====================================================================
2795
    // Gestion de features
2796
    //
2797
    private FeatureType fixFeatureType(DefaultFeatureType type)
2798
            throws DataException {
2799
        FeatureType original = this.getDefaultFeatureType();
2800

    
2801
        if ((type == null) || type.equals(original)) {
2802
            return original;
2803
        } else {
2804
            if (!type.isSubtypeOf(original)) {
2805
                Iterator iter = this.getFeatureTypes().iterator();
2806
                FeatureType tmpType;
2807
                boolean found = false;
2808
                while (iter.hasNext()) {
2809
                    tmpType = (FeatureType) iter.next();
2810
                    if (type.equals(tmpType)) {
2811
                        return type;
2812

    
2813
                    } else if (type.isSubtypeOf(tmpType)) {
2814
                        found = true;
2815
                        original = tmpType;
2816
                        break;
2817
                    }
2818

    
2819
                }
2820
                if (!found) {
2821
                    throw new IllegalFeatureTypeException(getName());
2822
                }
2823
            }
2824
        }
2825

    
2826
        // Checks that type has all fields of pk
2827
        // else add the missing attributes at the end.
2828
        if (!original.hasOID()) {
2829
            // Gets original pk attributes
2830
            DefaultEditableFeatureType edOriginal
2831
                    = (DefaultEditableFeatureType) original.getEditable();
2832
            FeatureAttributeDescriptor orgAttr;
2833
            Iterator edOriginalIter = edOriginal.iterator();
2834
            while (edOriginalIter.hasNext()) {
2835
                orgAttr = (FeatureAttributeDescriptor) edOriginalIter.next();
2836
                if (!orgAttr.isPrimaryKey()) {
2837
                    edOriginalIter.remove();
2838
                }
2839
            }
2840

    
2841
            // Checks if all pk attributes are in type
2842
            Iterator typeIterator;
2843
            edOriginalIter = edOriginal.iterator();
2844
            FeatureAttributeDescriptor attr;
2845
            while (edOriginalIter.hasNext()) {
2846
                orgAttr = (FeatureAttributeDescriptor) edOriginalIter.next();
2847
                typeIterator = type.iterator();
2848
                while (typeIterator.hasNext()) {
2849
                    attr = (FeatureAttributeDescriptor) typeIterator.next();
2850
                    if (attr.getName().equals(orgAttr.getName())) {
2851
                        edOriginalIter.remove();
2852
                        break;
2853
                    }
2854
                }
2855
            }
2856

    
2857
            // add missing pk attributes if any
2858
            if (edOriginal.size() > 0) {
2859
                boolean isEditable = type instanceof DefaultEditableFeatureType;
2860
                DefaultEditableFeatureType edType
2861
                        = (DefaultEditableFeatureType) original.getEditable();
2862
                edType.clear();
2863
                edType.addAll(type);
2864
                edType.addAll(edOriginal);
2865
                if (!isEditable) {
2866
                    type = (DefaultFeatureType) edType.getNotEditableCopy();
2867
                }
2868
            }
2869

    
2870
        }
2871

    
2872
        return type;
2873
    }
2874

    
2875
    private void validateFeaturesAtFinishEditing() throws ValidateFeaturesException {
2876
        try {
2877
            checkInEditingMode();
2878
            FeatureType type = this.getDefaultFeatureTypeQuietly();
2879
            DefaultFeatureRules rules = (DefaultFeatureRules) this.getDefaultFeatureType().getRules();
2880

    
2881
            int checks = type.isCheckFeaturesAtFinishEditing() ? CHECK_REQUIREDS : 0;
2882
            checks = rules.isEmpty() ? checks : checks | CHECK_RULES_AT_FINISH;
2883
            if (checks == 0) {
2884
                return;
2885
            }
2886

    
2887
            Iterator<EditableFeature> features = new ChainedIterator<>(
2888
                    featureManager.getInsertedFeatures(),
2889
                    featureManager.getUpdatedFeatures()
2890
            );
2891
            while (features.hasNext()) {
2892
                EditableFeature feature = features.next();
2893
                rules.validate(feature, checks);
2894
            }
2895
        } catch (Exception ex) {
2896
            throw new ValidateFeaturesException(this.getName(), ex);
2897
        }
2898
    }
2899

    
2900
    @Override
2901
    public FeatureType getDefaultFeatureType() throws DataException {
2902
        try {
2903

    
2904
            if (isEditing()) {
2905
                FeatureType auxFeatureType
2906
                        = featureTypeManager.getType(defaultFeatureType.getId());
2907
                if (auxFeatureType != null) {
2908
                    return avoidEditable(auxFeatureType);
2909
                }
2910
            }
2911
            FeatureType type = this.transforms.getDefaultFeatureType();
2912
            if (type != null) {
2913
                return avoidEditable(type);
2914
            }
2915

    
2916
            return avoidEditable(defaultFeatureType);
2917

    
2918
        } catch (Exception e) {
2919
            throw new GetFeatureTypeException(e, getName());
2920
        }
2921
    }
2922

    
2923
    @Override
2924
    public FeatureType getDefaultFeatureTypeQuietly() {
2925
        try {
2926
            return this.getDefaultFeatureType();
2927
        } catch (Exception ex) {
2928
            return null;
2929
        }
2930
    }
2931

    
2932
    private FeatureType avoidEditable(FeatureType ft) {
2933
        if (ft instanceof EditableFeatureType) {
2934
            return ((EditableFeatureType) ft).getNotEditableCopy();
2935
        } else {
2936
            return ft;
2937
        }
2938
    }
2939

    
2940
    @Override
2941
    public FeatureType getFeatureType(String featureTypeId)
2942
            throws DataException {
2943
        if (featureTypeId == null) {
2944
            return this.getDefaultFeatureType();
2945
        }
2946
        try {
2947
            if (isEditing()) {
2948
                FeatureType auxFeatureType
2949
                        = featureTypeManager.getType(featureTypeId);
2950
                if (auxFeatureType != null) {
2951
                    return auxFeatureType;
2952
                }
2953
            }
2954
            FeatureType type = this.transforms.getFeatureType(featureTypeId);
2955
            if (type != null) {
2956
                return type;
2957
            }
2958
            Iterator iter = this.featureTypes.iterator();
2959
            while (iter.hasNext()) {
2960
                type = (FeatureType) iter.next();
2961
                if (type.getId().equals(featureTypeId)) {
2962
                    return type;
2963
                }
2964
            }
2965
            return null;
2966
        } catch (Exception e) {
2967
            throw new GetFeatureTypeException(e, getName());
2968
        }
2969
    }
2970

    
2971
    public FeatureType getProviderDefaultFeatureType() {
2972
        return defaultFeatureType;
2973
    }
2974

    
2975
    @Override
2976
    public List getFeatureTypes() throws DataException {
2977
        try {
2978
            List types;
2979
            if (isEditing()) {
2980
                types = new ArrayList();
2981
                for (FeatureType type : featureTypes) {
2982
                    FeatureType typeaux = featureTypeManager.getType(type.getId());
2983
                    if (typeaux != null) {
2984
                        types.add(typeaux);
2985
                    } else {
2986
                        types.add(type);
2987
                    }
2988
                }
2989
                Iterator it = featureTypeManager.newsIterator();
2990
                while (it.hasNext()) {
2991
                    FeatureType type = (FeatureType) it.next();
2992
                    types.add(type);
2993
                }
2994
            } else {
2995
                types = this.transforms.getFeatureTypes();
2996
                if (types == null) {
2997
                    types = featureTypes;
2998
                }
2999
            }
3000
            return Collections.unmodifiableList(types);
3001
        } catch (Exception e) {
3002
            throw new GetFeatureTypeException(e, getName());
3003
        }
3004
    }
3005

    
3006
    public List getProviderFeatureTypes() throws DataException {
3007
        return Collections.unmodifiableList(this.featureTypes);
3008
    }
3009

    
3010
    @Override
3011
    public Feature createFeature(FeatureProvider data) throws DataException {
3012
        DefaultFeature feature = new DefaultFeature(this, data);
3013
        return feature;
3014
    }
3015

    
3016
    public Feature createFeature(FeatureProvider data, FeatureType type)
3017
            throws DataException {
3018
        // FIXME: falta por implementar
3019
        // Comprobar si es un subtipo del feature de data
3020
        // y construir un feature usando el subtipo.
3021
        // Probablemente requiera generar una copia del data.
3022
        throw new NotYetImplemented();
3023
    }
3024

    
3025
    @Override
3026
    public EditableFeature createNewFeature(FeatureType type,
3027
            Feature defaultValues) throws DataException {
3028
        try {
3029
            FeatureProvider data = createNewFeatureProvider(type);
3030
            DefaultEditableFeature feature
3031
                    = new DefaultEditableFeature(this, data);
3032
            feature.initializeValues(defaultValues);
3033
            data.setNew(true);
3034

    
3035
            return feature;
3036
        } catch (Exception e) {
3037
            throw new CreateFeatureException(e, getName());
3038
        }
3039
    }
3040

    
3041
    private FeatureProvider createNewFeatureProvider(FeatureType type)
3042
            throws DataException {
3043
        type = this.fixFeatureType((DefaultFeatureType) type);
3044
        FeatureProvider data = this.provider.createFeatureProvider(type);
3045
        data.setNew(true);
3046
        if (type.hasOID() && (data.getOID() == null)) {
3047
            data.setOID(this.provider.createNewOID());
3048
        } else {
3049
            data.setOID(this.getTemporalOID());
3050
        }
3051
        return data;
3052

    
3053
    }
3054

    
3055
    @Override
3056
    public EditableFeature createNewFeature(FeatureType type,
3057
            boolean defaultValues) throws DataException {
3058
        try {
3059
            FeatureProvider data = createNewFeatureProvider(type);
3060
            DefaultEditableFeature feature
3061
                    = new DefaultEditableFeature(this, data);
3062
            if (defaultValues) {
3063
                feature.initializeValues();
3064
            }
3065
            return feature;
3066
        } catch (Exception e) {
3067
            throw new CreateFeatureException(e, getName());
3068
        }
3069
    }
3070

    
3071
    @Override
3072
    public EditableFeature createNewFeature(boolean defaultValues)
3073
            throws DataException {
3074
        return this.createNewFeature(this.getDefaultFeatureType(),
3075
                defaultValues);
3076
    }
3077

    
3078
    @Override
3079
    public EditableFeature createNewFeature() throws DataException {
3080
        return this.createNewFeature(this.getDefaultFeatureType(), true);
3081
    }
3082

    
3083
    @Override
3084
    public EditableFeature createNewFeature(Feature defaultValues) throws DataException {
3085
        FeatureType ft = this.getDefaultFeatureType();
3086
        EditableFeature f = this.createNewFeature(ft, false);
3087
        f.copyFrom(defaultValues);
3088
        return f;
3089
    }
3090

    
3091
    @Override
3092
    public EditableFeature createNewFeature(JsonObject defaultValues) throws DataException {
3093
        FeatureType ft = this.getDefaultFeatureType();
3094
        EditableFeature f = this.createNewFeature(ft, false);
3095
        f.copyFrom(defaultValues);
3096
        return f;
3097
    }
3098

    
3099
    @Override
3100
    public EditableFeatureType createFeatureType() {
3101
        EditableFeatureType ftype = new DefaultEditableFeatureType(this);
3102
        return ftype;
3103
    }
3104

    
3105
    @Override
3106
    public EditableFeatureType createFeatureType(String id) {
3107
        DefaultEditableFeatureType ftype = new DefaultEditableFeatureType(this, id);
3108
        return ftype;
3109
    }
3110

    
3111
    //
3112
    // ====================================================================
3113
    // Index related methods
3114
    //
3115
    @Override
3116
    public FeatureIndexes getIndexes() {
3117
        return this.indexes;
3118
    }
3119

    
3120
    @Override
3121
    public FeatureIndex createIndex(FeatureType featureType,
3122
            String attributeName, String indexName) throws DataException {
3123
        return createIndex(null, featureType, attributeName, indexName);
3124
    }
3125

    
3126
    @Override
3127
    public FeatureIndex createIndex(String indexTypeName,
3128
            FeatureType featureType, String attributeName, String indexName)
3129
            throws DataException {
3130

    
3131
        return createIndex(indexTypeName, featureType, attributeName,
3132
                indexName, false, null);
3133
    }
3134

    
3135
    @Override
3136
    public FeatureIndex createIndex(FeatureType featureType,
3137
            String attributeName, String indexName, Observer observer)
3138
            throws DataException {
3139
        return createIndex(null, featureType, attributeName, indexName,
3140
                observer);
3141
    }
3142

    
3143
    @Override
3144
    public FeatureIndex createIndex(String indexTypeName,
3145
            FeatureType featureType, String attributeName, String indexName,
3146
            final Observer observer) throws DataException {
3147

    
3148
        return createIndex(indexTypeName, featureType, attributeName,
3149
                indexName, true, observer);
3150
    }
3151

    
3152
    private FeatureIndex createIndex(String indexTypeName,
3153
            FeatureType featureType, String attributeName, String indexName,
3154
            boolean background, final Observer observer) throws DataException {
3155

    
3156
        checkNotInAppendMode();
3157
        FeatureIndexProviderServices index;
3158
        index = dataManager.createFeatureIndexProvider(indexTypeName, this,
3159
                featureType, indexName,
3160
                featureType.getAttributeDescriptor(attributeName));
3161

    
3162
        try {
3163
            index.fill(background, observer);
3164
        } catch (FeatureIndexException e) {
3165
            throw new InitializeException(index.getName(), e);
3166
        }
3167

    
3168
        ((DefaultFeatureIndexes) getIndexes()).addIndex(index);
3169
        return index;
3170
    }
3171

    
3172
    //
3173
    // ====================================================================
3174
    // Transforms related methods
3175
    //
3176
    @Override
3177
    public FeatureStoreTransforms getTransforms() {
3178
        return this.transforms;
3179
    }
3180

    
3181
    @Override
3182
    public FeatureQuery createFeatureQuery() {
3183
        return new DefaultFeatureQuery(this.getName());
3184
    }
3185

    
3186
    @Override
3187
    public FeatureQuery createFeatureQuery(Expression filter, String sortBy, boolean asc) {
3188
        FeatureQuery query = null;
3189
        if ( !ExpressionUtils.isPhraseEmpty(filter) ) {
3190
            query = this.createFeatureQuery();
3191
            query.setFilter(filter);
3192
        }
3193
        if (!StringUtils.isBlank(sortBy)) {
3194
            if (query == null) {
3195
                query = this.createFeatureQuery();
3196
            }
3197
            if (StringUtils.containsAny(sortBy, "(", ")")) {
3198
                throw new IllegalArgumentException("Incorrect sortBy expression");
3199
            }
3200
            String[] attrnames;
3201
            if (sortBy.contains(",")) {
3202
                attrnames = StringUtils.split(sortBy, ",");
3203
            } else {
3204
                attrnames = new String[]{sortBy};
3205
            }
3206
            for (String attrname : attrnames) {
3207
                attrname = attrname.trim();
3208
                if (attrname.startsWith("-")) {
3209
                    query.getOrder().add(StringUtils.unwrap(attrname.substring(1).trim(),'"'), false);
3210
                } else if (attrname.endsWith("-")) {
3211
                    query.getOrder().add(StringUtils.unwrap(attrname.substring(0, sortBy.length() - 1).trim(),'"'), false);
3212
                } else if (attrname.startsWith("+")) {
3213
                    query.getOrder().add(StringUtils.unwrap(attrname.substring(1).trim(),'"'), true);
3214
                } else if (attrname.endsWith("-")) {
3215
                    query.getOrder().add(StringUtils.unwrap(attrname.substring(0, sortBy.length() - 1).trim(),'"'), true);
3216
                } else {
3217
                    query.getOrder().add(StringUtils.unwrap(attrname,'"'), asc);
3218
                }
3219
            }
3220
        }
3221
        if (query != null) {
3222
            query.retrievesAllAttributes();
3223
        }
3224
        return query;
3225
    }
3226

    
3227
    @Override
3228
    public FeatureQuery createFeatureQuery(String filter) {
3229
        return this.createFeatureQuery( 
3230
                ExpressionUtils.createExpression(filter),
3231
                (String) null,
3232
                true
3233
        );
3234
    }
3235

    
3236
    @Override
3237
    public FeatureQuery createFeatureQuery(Expression filter) {
3238
        return this.createFeatureQuery(
3239
                filter,
3240
                (String) null,
3241
                true
3242
        );
3243
    }
3244

    
3245
    @Override
3246
    public FeatureQuery createFeatureQuery(String filter, String sortBy, boolean asc) {
3247
        if (StringUtils.isBlank(filter)) {
3248
            return this.createFeatureQuery(
3249
                    (Expression) null,
3250
                    sortBy,
3251
                    asc
3252
            );
3253
        } else {
3254
            return this.createFeatureQuery(
3255
                    ExpressionUtils.createExpression(filter),
3256
                    sortBy,
3257
                    asc
3258
            );
3259
        }
3260
    }
3261

    
3262
    @Override
3263
    public FeatureQuery createFeatureQuery(Expression filter, Expression sortBy, boolean asc) {
3264
        FeatureQuery query = null;
3265
        if (filter != null) {
3266
            query = this.createFeatureQuery();
3267
            query.setFilter(filter);
3268
        }
3269
        if (sortBy != null) {
3270
            if (query == null) {
3271
                query = this.createFeatureQuery();
3272
            }
3273
            query.getOrder().add(sortBy, asc);
3274
        }
3275

    
3276
        if (query != null) {
3277
            query.retrievesAllAttributes();
3278
        }
3279
        return query;
3280
    }
3281

    
3282
    @Override
3283
    public FeatureQuery createFeatureQuery(String filter, Expression sortBy, boolean asc) {
3284
        if (StringUtils.isBlank(filter)) {
3285
            return this.createFeatureQuery(
3286
                    (Expression) null,
3287
                    sortBy,
3288
                    asc
3289
            );
3290
        } else {
3291
            return this.createFeatureQuery(
3292
                    ExpressionUtils.createExpression(filter),
3293
                    sortBy,
3294
                    asc
3295
            );
3296
        }
3297
    }
3298

    
3299
    @Override
3300
    public DataQuery createQuery() {
3301
        return createFeatureQuery();
3302
    }
3303

    
3304
    //
3305
    // ====================================================================
3306
    // UndoRedo related methods
3307
    //
3308
    @Override
3309
    public boolean canRedo() {
3310
        return commands.canRedo();
3311
    }
3312

    
3313
    @Override
3314
    public boolean canUndo() {
3315
        return commands.canUndo();
3316
    }
3317

    
3318
    @Override
3319
    public void redo(int num) throws RedoException {
3320
        for (int i = 0; i < num; i++) {
3321
            redo();
3322
        }
3323
    }
3324

    
3325
    @Override
3326
    public void undo(int num) throws UndoException {
3327
        for (int i = 0; i < num; i++) {
3328
            undo();
3329
        }
3330
    }
3331

    
3332
    //
3333
    // ====================================================================
3334
    // Metadata related methods
3335
    //
3336
    @Override
3337
    public Object getMetadataID() {
3338
        return this.provider.getSourceId();
3339
    }
3340

    
3341
    @Override
3342
    public void delegate(DynObject dynObject) {
3343
        this.metadata.delegate(dynObject);
3344
    }
3345

    
3346
    @Override
3347
    public DynClass getDynClass() {
3348
        return this.metadata.getDynClass();
3349
    }
3350

    
3351
    @Override
3352
    public Object getDynValue(String name) throws DynFieldNotFoundException {
3353
        try {
3354
            if (this.transforms.hasDynValue(name)) {
3355
                return this.transforms.getDynValue(name);
3356
            }
3357
            if (this.metadata.hasDynValue(name)) {
3358
                return this.metadata.getDynValue(name);
3359
            }
3360
            if (METADATA_PROVIDER.equalsIgnoreCase(name)) {
3361
                return this.provider.getProviderName();
3362
            } else if (METADATA_CONTAINERNAME.equalsIgnoreCase(name)) {
3363
                return this.provider.getSourceId();
3364
            } else if (METADATA_FEATURETYPE.equalsIgnoreCase(name)) {
3365
                try {
3366
                    return this.getDefaultFeatureType();
3367
                } catch (DataException e) {
3368
                    return null;
3369
                }
3370
            }
3371
            return this.metadata.getDynValue(name);
3372
        } catch (Exception ex) {
3373
            LOGGER.debug("Can't retrieve the value of '" + name + "' in store '" + this.getName() + "'.", ex);
3374
            return null;
3375
        }
3376
    }
3377

    
3378
    @Override
3379
    public boolean hasDynValue(String name) {
3380
        if (this.transforms.hasDynValue(name)) {
3381
            return true;
3382
        }
3383
        if (this.provider.hasDynValue(name)) {
3384
            return true;
3385
        }
3386
        if (METADATA_PROVIDER.equalsIgnoreCase(name)) {
3387
            return true;
3388
        } else if (METADATA_CONTAINERNAME.equalsIgnoreCase(name)) {
3389
            return true;
3390
        } else if (METADATA_FEATURETYPE.equalsIgnoreCase(name)) {
3391
            return true;
3392
        }
3393
        return this.metadata.hasDynValue(name);
3394
    }
3395

    
3396
    @Override
3397
    public boolean hasDynMethod(String name) {
3398
        return ((DynObject_v2) this.metadata).hasDynMethod(name);
3399
    }
3400

    
3401
    @Override
3402
    public void implement(DynClass dynClass) {
3403
        this.metadata.implement(dynClass);
3404
    }
3405

    
3406
    @Override
3407
    public Object invokeDynMethod(String name, Object[] args)
3408
            throws DynMethodException {
3409
        return this.metadata.invokeDynMethod(this, name, args);
3410
    }
3411

    
3412
    @Override
3413
    public Object invokeDynMethod(int code, Object[] args)
3414
            throws DynMethodException {
3415
        return this.metadata.invokeDynMethod(this, code, args);
3416
    }
3417

    
3418
    @Override
3419
    public void setDynValue(String name, Object value)
3420
            throws DynFieldNotFoundException {
3421
        if (this.transforms.hasDynValue(name)) {
3422
            this.transforms.setDynValue(name, value);
3423
            return;
3424
        }
3425
        this.metadata.setDynValue(name, value);
3426

    
3427
    }
3428

    
3429
    /*
3430
     * (non-Javadoc)
3431
     *
3432
     * @see org.gvsig.metadata.Metadata#getMetadataChildren()
3433
     */
3434
    @Override
3435
    public Set getMetadataChildren() {
3436
        return this.metadataChildren;
3437
    }
3438

    
3439
    /*
3440
     * (non-Javadoc)
3441
     *
3442
     * @see org.gvsig.metadata.Metadata#getMetadataName()
3443
     */
3444
    @Override
3445
    public String getMetadataName() {
3446
        return this.provider.getProviderName();
3447
    }
3448

    
3449
    public FeatureTypeManager getFeatureTypeManager() {
3450
        return this.featureTypeManager;
3451
    }
3452

    
3453
    @Override
3454
    public long getFeatureCount() throws DataException {
3455
        if (featureCount == null) {
3456
            featureCount = this.provider.getFeatureCount();
3457
        }
3458
        if (this.isEditing()) {
3459
            if (this.isAppending()) {
3460
                try {
3461
                    throw new IllegalStateException();
3462
                } catch (IllegalStateException e) {
3463
                    LOGGER.info("Call DefaultFeatureStore.getFeatureCount editing in mode APPEND", e);
3464
                }
3465
                return -1;
3466
            } else {
3467
                return featureCount
3468
                        + this.featureManager.getDeltaSize();
3469
            }
3470
        }
3471
        return featureCount;
3472
    }
3473

    
3474
    private Long getTemporalOID() {
3475
        return this.temporalOid++;
3476
    }
3477

    
3478
    @Override
3479
    public FeatureType getProviderFeatureType(String featureTypeId) {
3480
        if (featureTypeId == null) {
3481
            return this.defaultFeatureType;
3482
        }
3483
        FeatureType type;
3484
        Iterator iter = this.featureTypes.iterator();
3485
        while (iter.hasNext()) {
3486
            type = (FeatureType) iter.next();
3487
            if (type.getId().equals(featureTypeId)) {
3488
                return type;
3489
            }
3490
        }
3491
        return null;
3492
    }
3493

    
3494
    @Override
3495
    public FeatureProvider getFeatureProviderFromFeature(Feature feature) {
3496
        return ((DefaultFeature) feature).getData();
3497
    }
3498

    
3499
    @Override
3500
    public DataStore getStore() {
3501
        return this;
3502
    }
3503

    
3504
    @Override
3505
    public FeatureStore getFeatureStore() {
3506
        return this;
3507
    }
3508

    
3509
    @Override
3510
    public void createCache(String name, DynObject parameters)
3511
            throws DataException {
3512
        cache = dataManager.createFeatureCacheProvider(name, parameters);
3513
        if (cache == null) {
3514
            throw new CreateException("FeaureCacheProvider", null);
3515
        }
3516
        cache.apply(this, provider);
3517
        provider = cache;
3518

    
3519
        featureCount = null;
3520
    }
3521

    
3522
    @Override
3523
    public FeatureCache getCache() {
3524
        return cache;
3525
    }
3526

    
3527
    @Override
3528
    public void clear() {
3529
        if (metadata != null) {
3530
            metadata.clear();
3531
        }
3532
    }
3533

    
3534
    @Override
3535
    public String getName() {
3536
        if (this.provider != null) {
3537
            return this.provider.getName();
3538
        }
3539
        if (this.parameters instanceof HasAFile) {
3540
            return FilenameUtils.getName(((HasAFile) this.parameters).getFile().getName());
3541
        }
3542
        return "unknow";
3543
    }
3544

    
3545
    @Override
3546
    public String getFullName() {
3547
        try {
3548
            String fullname = null;
3549
            if (this.provider != null) {
3550
                fullname = this.provider.getFullName();
3551
            }
3552
            if ( StringUtils.isBlank(fullname) && this.parameters instanceof HasAFile) {
3553
                fullname = (((HasAFile) this.parameters).getFile().getAbsolutePath());
3554
            }
3555
            if(StringUtils.isBlank(fullNameForTraces) ) {
3556
                fullNameForTraces = fullname;
3557
            }
3558
            return fullname;
3559
        } catch (Throwable th) {
3560
            return null;
3561
        }
3562
    }
3563
    
3564
    protected String getFullNameForTraces() {
3565
        if(StringUtils.isBlank(fullNameForTraces) ) {
3566
            return this.getFullName();
3567
        }
3568
        return fullNameForTraces;
3569
    }
3570

    
3571
    @Override
3572
    public String getProviderName() {
3573
        if (this.provider != null) {
3574
            return this.provider.getProviderName();
3575
        }
3576
        if (this.parameters != null) {
3577
            return this.parameters.getDataStoreName();
3578
        }
3579
        return null;
3580

    
3581
    }
3582

    
3583
    @Override
3584
    public boolean isKnownEnvelope() {
3585
        return this.provider.isKnownEnvelope();
3586
    }
3587

    
3588
    @Override
3589
    public boolean hasRetrievedFeaturesLimit() {
3590
        return this.provider.hasRetrievedFeaturesLimit();
3591
    }
3592

    
3593
    @Override
3594
    public int getRetrievedFeaturesLimit() {
3595
        return this.provider.getRetrievedFeaturesLimit();
3596
    }
3597

    
3598
    @Override
3599
    public Interval getInterval() {
3600
        if (this.timeSupport != null) {
3601
            return this.timeSupport.getInterval();
3602
        }
3603
        try {
3604
            FeatureType type = this.getDefaultFeatureType();
3605
            FeatureAttributeDescriptor attr = type.getDefaultTimeAttribute();
3606
            if (attr != null) {
3607
                Interval interval = attr.getInterval();
3608
                if (interval != null) {
3609
                    return interval;
3610
                }
3611
            }
3612
        } catch (DataException ex) {
3613
        }
3614
        return this.provider.getInterval();
3615
    }
3616

    
3617
    @Override
3618
    public Collection getTimes() {
3619
        if (this.timeSupport != null) {
3620
            return this.timeSupport.getTimes();
3621
        }
3622
        return this.provider.getTimes();
3623
    }
3624

    
3625
    @Override
3626
    public Collection getTimes(Interval interval) {
3627
        if (this.timeSupport != null) {
3628
            return this.timeSupport.getTimes(interval);
3629
        }
3630
        return this.provider.getTimes(interval);
3631
    }
3632

    
3633
    public void setTimeSupport(FeatureStoreTimeSupport timeSupport) {
3634
        if (this.isEditing()) {
3635
            throw new RuntimeException("Can't add time support over attribute '" + timeSupport.getAttributeName() + "' while store is editing.");
3636
        }
3637
        if (!this.transforms.isEmpty()) {
3638
            throw new RuntimeException("Can't add time support over attribute '" + timeSupport.getAttributeName() + "' if has transforms.");
3639
        }
3640
        FeatureType ft = this.defaultFeatureType;
3641
        FeatureAttributeDescriptor attr = ft.getAttributeDescriptor(timeSupport.getRequiredFieldNames()[0]);
3642
        if (attr == null) {
3643
            throw new RuntimeException("Can't add time support over attribute '" + timeSupport.getAttributeName() + "', this attribute don't exists.");
3644
        }
3645
        EditableFeatureType eft = ft.getEditable();
3646
        attr = eft.getAttributeDescriptor(timeSupport.getAttributeName());
3647
        if (attr != null) {
3648
            if (!(attr.getFeatureAttributeEmulator() instanceof FeatureStoreTimeSupport)) {
3649
                throw new RuntimeException("Can't add time support, attribute '" + timeSupport.getAttributeName() + "'already exists.");
3650
            }
3651
            eft.remove(attr.getName());
3652
        }
3653
        EditableFeatureAttributeDescriptor attrTime = eft.add(
3654
                timeSupport.getAttributeName(),
3655
                timeSupport.getDataType()
3656
        );
3657
        attrTime.setIsTime(true);
3658
        attrTime.setFeatureAttributeEmulator(timeSupport);
3659
        eft.setDefaultTimeAttributeName(timeSupport.getAttributeName());
3660
        this.defaultFeatureType = eft.getNotEditableCopy();
3661

    
3662
        this.timeSupport = timeSupport;
3663
    }
3664

    
3665
    @Override
3666
    @SuppressWarnings("CloneDoesntCallSuperClone")
3667
    public Object clone() throws CloneNotSupportedException {
3668

    
3669
        DataStoreParameters dsp = getParameters();
3670

    
3671
        DefaultFeatureStore cloned_store = null;
3672

    
3673
        try {
3674
            cloned_store = (DefaultFeatureStore) DALLocator.getDataManager().
3675
                    openStore(this.getProviderName(), dsp);
3676
            if (transforms != null) {
3677
                cloned_store.transforms = (DefaultFeatureStoreTransforms) transforms.clone();
3678
                cloned_store.transforms.setStoreForClone(cloned_store);
3679
            }
3680
        } catch (Exception e) {
3681
            throw new CloneException(e);
3682
        }
3683
        return cloned_store;
3684

    
3685
    }
3686

    
3687
    @Override
3688
    public Feature getFeature(DynObject dynobject) {
3689
        if (dynobject instanceof DynObjectFeatureFacade) {
3690
            Feature f = ((DynObjectFeatureFacade) dynobject).getFeature();
3691
            return f;
3692
        }
3693
        return null;
3694
    }
3695

    
3696
    @Override
3697
    public Iterator iterator() {
3698
        FeatureSet fset = null;
3699
        try {
3700
            fset = this.getFeatureSet();
3701
            return fset.fastIterator();
3702
        } catch (DataException ex) {
3703
            throw new RuntimeException(ex);
3704
        } finally {
3705
            DisposeUtils.disposeQuietly(fset);
3706
        }
3707
    }
3708

    
3709
    @Override
3710
    public long size64() {
3711
        FeatureSet fset = null;
3712
        try {
3713
            fset = this.getFeatureSet();
3714
            return fset.getSize();
3715
        } catch (DataException ex) {
3716
            throw new RuntimeException(ex);
3717
        } finally {
3718
            DisposeUtils.disposeQuietly(fset);
3719
        }
3720
    }
3721

    
3722
    @Override
3723
    public ExpressionBuilder createExpressionBuilder() {
3724
        ExpressionBuilder builder = GeometryExpressionUtils.createExpressionBuilder();
3725
        return builder;
3726
    }
3727

    
3728
    @Override
3729
    public ExpressionBuilder createExpression() {
3730
        return createExpressionBuilder();
3731
    }
3732

    
3733
    public FeatureSet features() throws DataException {
3734
        // This is to avoid jython to create a property with this name
3735
        // to access method getFeatures.
3736
        return this.getFeatureSet();
3737
    }
3738

    
3739
    @Override
3740
    public DataStoreProviderFactory getProviderFactory() {
3741
        DataStoreProviderFactory factory = dataManager.getStoreProviderFactory(parameters.getDataStoreName());
3742
        return factory;
3743
    }
3744

    
3745
    @Override
3746
    public void useCache(String providerName, DynObject parameters) throws DataException {
3747
        throw new UnsupportedOperationException();
3748
    }
3749

    
3750
    @Override
3751
    public boolean isBroken() {
3752
        return this.state.isBroken();
3753
    }
3754

    
3755
    @Override
3756
    public Throwable getBreakingsCause() {
3757
        return this.state.getBreakingsCause();
3758
    }
3759

    
3760
    @Override
3761
    public SpatialIndex wrapSpatialIndex(SpatialIndex index) {
3762
        FeatureStoreProviderFactory factory = (FeatureStoreProviderFactory) this.getProviderFactory();
3763
        if (!factory.supportNumericOID()) {
3764
            return null;
3765
        }
3766
        SpatialIndex wrappedIndex = new WrappedSpatialIndex(index, this);
3767
        return wrappedIndex;
3768
    }
3769

    
3770
    @Override
3771
    public FeatureReference getFeatureReference(String code) {
3772
        FeatureReference featureReference = FeatureReferenceFactory.createFromCode(this, code);
3773
        return featureReference;
3774
    }
3775

    
3776
    @Override
3777
    public long getPendingChangesCount() {
3778
        if (this.featureManager == null) {
3779
            return 0;
3780
        }
3781
        return this.featureManager.getPendingChangesCount();
3782
    }
3783

    
3784
    private ResourcesStorage resourcesStorage;
3785

    
3786
    @Override
3787
    public ResourcesStorage getResourcesStorage() {
3788
        if (this.resourcesStorage != null) {
3789
            DisposeUtils.bind(this.resourcesStorage);
3790
            return this.resourcesStorage;
3791
        }
3792
        ResourcesStorage theResourcesStorage;
3793
        try {
3794
            theResourcesStorage = this.provider.getResourcesStorage();
3795
            if (theResourcesStorage != null) {
3796
                this.resourcesStorage = theResourcesStorage;
3797
                DisposeUtils.bind(this.resourcesStorage);
3798
                return theResourcesStorage;
3799
            }
3800
        } catch (Throwable th) {
3801

    
3802
        }
3803
        try {
3804
            DataServerExplorer explorer = this.getExplorer();
3805
            if (explorer == null) {
3806
                return null;
3807
            }
3808
            theResourcesStorage = explorer.getResourcesStorage(this);
3809
            explorer.dispose();
3810
            this.resourcesStorage = theResourcesStorage;
3811
            DisposeUtils.bind(this.resourcesStorage);
3812
            return theResourcesStorage;
3813
        } catch (Exception ex) {
3814
            LOGGER.trace("Can't create resources storage", ex);
3815
            return null;
3816
        }
3817
    }
3818

    
3819
    @Override
3820
    public StoresRepository getStoresRepository() {
3821
        final StoresRepository mainRepository = this.dataManager.getStoresRepository();
3822
        StoresRepository localRepository = this.provider.getStoresRepository();
3823
        if (localRepository == null) {
3824
            return mainRepository;
3825
        }
3826
        StoresRepository repository = new BaseStoresRepository(this.getName());
3827
        repository.addRepository(localRepository);
3828
        repository.addRepository(mainRepository);
3829
        return repository;
3830
    }
3831

    
3832
    @Override
3833
    public Feature getSampleFeature() {
3834
        if( sampleFeatureCache==null )  {
3835
            this.sampleFeatureCache = new CachedValue<Feature>(sample_feature_cache_timeout_ms) {
3836
                @Override
3837
                protected void reload() {
3838
                    Feature sampleFeature;
3839
                    long t1 = System.currentTimeMillis();
3840
                    try {                        
3841
                        FeatureSelection theSelection = getFeatureSelection();
3842
                        if (theSelection != null && !theSelection.isEmpty()) {
3843
                            sampleFeature = theSelection.first();
3844
                        } else {
3845
                            sampleFeature = first();
3846
                        }
3847
                        if (sampleFeature == null) {
3848
                            sampleFeature = createNewFeature();
3849
                        }
3850
                    } catch (Exception ex) {
3851
                        sampleFeature = null;
3852
                    }
3853
                    long t2 = System.currentTimeMillis();
3854
                    if( (t2 - t1)>5000 ) {
3855
                        // Mas de 5 seg es muy costoso, subimos mucho el tiempo de cache.
3856
                        this.setExpireTime(((60*60)*2)*1000); // 2h
3857
                    }
3858
                    this.setValue(sampleFeature);
3859
                }
3860
            };
3861
        }
3862
        return this.sampleFeatureCache.get();
3863
    }
3864

    
3865
    @Override
3866
    public boolean supportReferences() {
3867
        try {
3868
            return this.getDefaultFeatureType().supportReferences();
3869
        } catch (Exception ex) {
3870
            return false;
3871
        }
3872
    }
3873

    
3874
    private Boolean temporary = null;
3875
    
3876
    @Override
3877
    public boolean isTemporary() {
3878
        if(temporary != null) {
3879
            return this.temporary;
3880
        }
3881
        if (this.provider == null) {
3882
            return true;
3883
        }
3884
        return this.provider.isTemporary();
3885
    }
3886
    
3887
    @Override
3888
    public void setTemporary(Boolean temporary){
3889
        this.temporary = temporary;
3890
    }
3891

    
3892
    public FeatureType getOriginalFeatureType(FeatureType featureType) {
3893
        // FIXME this don't work for Store.featureTypes.size() > 1
3894
        
3895
        FeatureTypeManager manager = this.featureTypeManager;
3896
        if (manager == null) {
3897
            return null;
3898
        }
3899
        FeatureType originalFeatureType = manager.getOriginalFeatureType();
3900
        if (originalFeatureType == null) {
3901
            return null;
3902
        }
3903
        return originalFeatureType.getCopy();
3904
    }
3905

    
3906
    @Override
3907
    public Object getProperty(String name) {
3908
        if (this.propertiesSupportHelper == null) {
3909
            return null;
3910
        }
3911
        return this.propertiesSupportHelper.getProperty(name);
3912
    }
3913

    
3914
    @Override
3915
    public void setProperty(String name, Object value) {
3916
        if (this.propertiesSupportHelper == null) {
3917
            this.propertiesSupportHelper = new PropertiesSupportHelper();
3918
        }
3919
        this.propertiesSupportHelper.setProperty(name, value);
3920
    }
3921

    
3922
    @Override
3923
    public Map<String, Object> getProperties() {
3924
        if (this.propertiesSupportHelper == null) {
3925
            return Collections.EMPTY_MAP;
3926
        }
3927
        return this.propertiesSupportHelper.getProperties();
3928
    }
3929

    
3930
    @Override
3931
    public Feature getOriginalFeature(FeatureReference id) {
3932
        if (this.featureManager == null) {
3933
            return null;
3934
        }
3935
        return featureManager.getOriginal(id);
3936
    }
3937

    
3938
    @Override
3939
    public Feature getOriginalFeature(Feature feature) {
3940
        if (feature == null) {
3941
            return null;
3942
        }
3943
        return getOriginalFeature(feature.getReference());
3944
    }
3945

    
3946
    @Override
3947
    public boolean isFeatureModified(FeatureReference id) {
3948
        if (this.featureManager == null) {
3949
            return false;
3950
        }
3951
        return featureManager.isFeatureModified(id);
3952
    }
3953

    
3954
    @Override
3955
    public boolean isFeatureModified(Feature feature) {
3956
        if (feature == null) {
3957
            return false;
3958
        }
3959
        return isFeatureModified(feature.getReference());
3960
    }
3961

    
3962
    @Override
3963
    public void setTransaction(DataTransaction transaction) {
3964
        if( this.transaction!=null ) {
3965
            this.transaction.deleteObserver(transactionObserver);
3966
        }
3967
        this.transaction = transaction;
3968
        if (transaction == null || transaction instanceof DataTransactionServices) {
3969
            this.provider.setTransaction((DataTransactionServices) transaction);
3970
        }
3971
        if( transaction!=null ) {
3972
            transaction.addObserver(transactionObserver);
3973
        }
3974
    }
3975

    
3976
    @Override
3977
    public DataTransaction getTransaction() {
3978
        return transaction;
3979
    }
3980

    
3981
    @Override
3982
    public String toString() {
3983
        try {
3984
            ToStringBuilder builder = new ToStringBuilder(this);
3985
            builder.append("provider", this.provider==null? null:this.provider.getProviderName());
3986
            builder.append("fullname", this.getFullName());
3987
            return builder.toString();
3988
        } catch (Exception e) {
3989
            return super.toString();
3990
        }
3991
    }
3992

    
3993
    public String createUniqueID() {
3994
        UUID x = UUID.randomUUID();
3995
        String s = x.toString();
3996
        return s;
3997
    }
3998

    
3999
    @Override
4000
    public List<FeatureReference> getEditedFeatures() {
4001
        if( this.featureManager == null ) {
4002
            return Collections.EMPTY_LIST;
4003
        }
4004
        List<FeatureReference> references = this.featureManager.getAddedAndUpdatedFeatures();
4005
        if( references==null ) {
4006
            return Collections.EMPTY_LIST;
4007
        }
4008
        return references;
4009
    }
4010
    
4011
    public List<FeatureReference> getEditedFeaturesNotValidated() {
4012

    
4013
        try {
4014
            if (this.featureManager == null) {
4015
                return Collections.EMPTY_LIST;
4016
            }
4017
            
4018
            FeatureType type = this.getDefaultFeatureTypeQuietly();
4019
            DefaultFeatureRules rules = (DefaultFeatureRules) this.getDefaultFeatureType().getRules();
4020
            
4021
//            int checks = type.isCheckFeaturesAtFinishEditing() ? CHECK_REQUIREDS | CHECK_BASIC : 0;
4022
            int checks = CHECK_REQUIREDS | CHECK_BASIC;
4023
            if(type.isCheckFeaturesAtFinishEditing()){
4024
                checks = rules.isEmpty() ? checks : checks | CHECK_RULES_AT_FINISH;
4025
            }
4026
            if (checks == 0) {
4027
                return Collections.EMPTY_LIST;
4028
            }
4029
            List<FeatureReference> references = this.featureManager
4030
                    .getAddedAndUpdatedFeaturesNotValidated(rules, checks);
4031
            if (references == null) {
4032
                return Collections.EMPTY_LIST;
4033
            }
4034
            return references;
4035
        } catch (DataException ex) {
4036
            return null;
4037
        }
4038

    
4039
    }
4040

    
4041
    @Override
4042
    public Iterator<Feature> getFeaturesIterator(Iterator<FeatureReference> references) {
4043
        return new FeatureReferenceIteratorToFeatureIterator(this, references);
4044
    }
4045

    
4046
    @Override
4047
    public Iterable<Feature> getFeaturesIterable(Iterator<FeatureReference> references) {
4048
        return () -> new FeatureReferenceIteratorToFeatureIterator(this, references);
4049
    }
4050

    
4051
    @Override
4052
    public boolean isFeatureSelectionAvailable() {
4053
        try {
4054
            FeatureType type = this.getDefaultFeatureType();
4055
            return type.supportReferences();
4056
        } catch (DataException ex) {
4057
            return false;
4058
        }
4059
    }
4060
    
4061
    @Override
4062
    public boolean canBeEdited() {
4063
        return this.transforms.isEmpty();
4064
    }
4065

    
4066
    @Override
4067
    public String getLabel() {
4068
        FeatureType ft = this.getDefaultFeatureTypeQuietly();
4069
        if( ft == null ) {
4070
            return this.getName();
4071
        }
4072
        String label = ft.getLabel();
4073
        if( StringUtils.isBlank(label) ) {
4074
            return this.getName();
4075
        }
4076
        return label;
4077
    }
4078

    
4079
    public void addRequiredAttributes(FeatureQuery fq) {
4080
        if(this.transforms != null && !this.transforms.isEmpty()){
4081
            //FIXME: A?adir solo los atributos necesarios para la transformaci?n
4082
            // this.transforms.addRequiredAttributes(fq) //No hay api todav?a
4083
            fq.retrievesAllAttributes();
4084
        }
4085
    }
4086

    
4087
    
4088
}