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

History | View | Annotate | Download (96.8 KB)

1 40559 jjdelcerro
/**
2
 * gvSIG. Desktop Geographic Information System.
3 40435 jjdelcerro
 *
4 40559 jjdelcerro
 * Copyright (C) 2007-2013 gvSIG Association.
5 40435 jjdelcerro
 *
6 42293 jjdelcerro
 * 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 40435 jjdelcerro
 *
11 42293 jjdelcerro
 * 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 40435 jjdelcerro
 *
16 42293 jjdelcerro
 * 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 40435 jjdelcerro
 *
21 42293 jjdelcerro
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23 40435 jjdelcerro
 */
24 42293 jjdelcerro
25 40435 jjdelcerro
package org.gvsig.fmap.dal.feature.impl;
26
27 43954 jjdelcerro
import java.io.File;
28 43840 jjdelcerro
import org.gvsig.fmap.dal.feature.impl.editing.memory.SpatialManager;
29
import org.gvsig.fmap.dal.feature.impl.editing.memory.FeatureTypeManager;
30
import org.gvsig.fmap.dal.feature.impl.editing.memory.FeatureManager;
31 43020 jjdelcerro
import org.gvsig.fmap.dal.feature.spi.SQLBuilderBase;
32 43152 fdiaz
33 40435 jjdelcerro
import java.util.ArrayList;
34
import java.util.Collection;
35
import java.util.Collections;
36
import java.util.HashMap;
37
import java.util.HashSet;
38
import java.util.Iterator;
39
import java.util.List;
40
import java.util.Map;
41
import java.util.Map.Entry;
42
import java.util.Set;
43 43954 jjdelcerro
import java.util.logging.Level;
44 43981 omartinez
import org.apache.commons.collections4.ListUtils;
45 43371 fdiaz
46 43215 jjdelcerro
import org.apache.commons.io.FilenameUtils;
47 43533 jjdelcerro
import org.apache.commons.lang3.StringUtils;
48 40435 jjdelcerro
import org.cresques.cts.IProjection;
49 44023 jjdelcerro
import org.gvsig.expressionevaluator.Expression;
50 43152 fdiaz
51 40435 jjdelcerro
import org.gvsig.fmap.dal.DALLocator;
52
import org.gvsig.fmap.dal.DataManager;
53
import org.gvsig.fmap.dal.DataQuery;
54
import org.gvsig.fmap.dal.DataServerExplorer;
55
import org.gvsig.fmap.dal.DataSet;
56
import org.gvsig.fmap.dal.DataStore;
57
import org.gvsig.fmap.dal.DataStoreNotification;
58
import org.gvsig.fmap.dal.DataStoreParameters;
59 43152 fdiaz
import org.gvsig.fmap.dal.DataStoreProviderFactory;
60 43521 jjdelcerro
import org.gvsig.fmap.dal.ExpressionBuilder;
61 40435 jjdelcerro
import org.gvsig.fmap.dal.exception.CloneException;
62
import org.gvsig.fmap.dal.exception.CloseException;
63
import org.gvsig.fmap.dal.exception.CreateException;
64
import org.gvsig.fmap.dal.exception.DataException;
65
import org.gvsig.fmap.dal.exception.InitializeException;
66
import org.gvsig.fmap.dal.exception.OpenException;
67
import org.gvsig.fmap.dal.exception.ReadException;
68
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
69 40597 jldominguez
import org.gvsig.fmap.dal.exception.WriteException;
70 40435 jjdelcerro
import org.gvsig.fmap.dal.feature.EditableFeature;
71 43610 jjdelcerro
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
72 40435 jjdelcerro
import org.gvsig.fmap.dal.feature.EditableFeatureType;
73
import org.gvsig.fmap.dal.feature.Feature;
74
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
75 43981 omartinez
import org.gvsig.fmap.dal.feature.FeatureAttributeEmulator;
76 40435 jjdelcerro
import org.gvsig.fmap.dal.feature.FeatureCache;
77
import org.gvsig.fmap.dal.feature.FeatureIndex;
78
import org.gvsig.fmap.dal.feature.FeatureIndexes;
79
import org.gvsig.fmap.dal.feature.FeatureLocks;
80
import org.gvsig.fmap.dal.feature.FeatureQuery;
81
import org.gvsig.fmap.dal.feature.FeatureReference;
82
import org.gvsig.fmap.dal.feature.FeatureReferenceSelection;
83 43642 jjdelcerro
import org.gvsig.fmap.dal.feature.FeatureRules;
84 40435 jjdelcerro
import org.gvsig.fmap.dal.feature.FeatureSelection;
85
import org.gvsig.fmap.dal.feature.FeatureSet;
86
import org.gvsig.fmap.dal.feature.FeatureStore;
87
import org.gvsig.fmap.dal.feature.FeatureStoreNotification;
88 43705 jjdelcerro
import org.gvsig.fmap.dal.feature.FeatureStoreProviderFactory;
89 40435 jjdelcerro
import org.gvsig.fmap.dal.feature.FeatureStoreTransforms;
90
import org.gvsig.fmap.dal.feature.FeatureType;
91
import org.gvsig.fmap.dal.feature.NewFeatureStoreParameters;
92 43135 jjdelcerro
import org.gvsig.fmap.dal.feature.FeatureStoreTimeSupport;
93 43215 jjdelcerro
import org.gvsig.fmap.dal.feature.FeatureStoreTransform;
94 40435 jjdelcerro
import org.gvsig.fmap.dal.feature.exception.AlreadyEditingException;
95
import org.gvsig.fmap.dal.feature.exception.ConcurrentDataModificationException;
96
import org.gvsig.fmap.dal.feature.exception.CreateFeatureException;
97
import org.gvsig.fmap.dal.feature.exception.DataExportException;
98
import org.gvsig.fmap.dal.feature.exception.FeatureIndexException;
99
import org.gvsig.fmap.dal.feature.exception.FinishEditingException;
100
import org.gvsig.fmap.dal.feature.exception.GetFeatureTypeException;
101
import org.gvsig.fmap.dal.feature.exception.IllegalFeatureException;
102
import org.gvsig.fmap.dal.feature.exception.IllegalFeatureTypeException;
103
import org.gvsig.fmap.dal.feature.exception.NeedEditingModeException;
104
import org.gvsig.fmap.dal.feature.exception.NoNewFeatureInsertException;
105
import org.gvsig.fmap.dal.feature.exception.NullFeatureTypeException;
106 40597 jldominguez
import org.gvsig.fmap.dal.feature.exception.PerformEditingException;
107 40435 jjdelcerro
import org.gvsig.fmap.dal.feature.exception.PersistenceCantFindFeatureTypeException;
108
import org.gvsig.fmap.dal.feature.exception.PersistenceStoreAlreadyLoadedException;
109
import org.gvsig.fmap.dal.feature.exception.SelectionNotAllowedException;
110
import org.gvsig.fmap.dal.feature.exception.StoreCancelEditingException;
111
import org.gvsig.fmap.dal.feature.exception.StoreDeleteEditableFeatureException;
112
import org.gvsig.fmap.dal.feature.exception.StoreDeleteFeatureException;
113
import org.gvsig.fmap.dal.feature.exception.StoreEditException;
114
import org.gvsig.fmap.dal.feature.exception.StoreInsertFeatureException;
115
import org.gvsig.fmap.dal.feature.exception.StoreUpdateFeatureException;
116
import org.gvsig.fmap.dal.feature.exception.StoreUpdateFeatureTypeException;
117
import org.gvsig.fmap.dal.feature.exception.ValidateFeaturesException;
118
import org.gvsig.fmap.dal.feature.exception.WriteNotAllowedException;
119
import org.gvsig.fmap.dal.feature.impl.featureset.DefaultFeatureSet;
120 42775 jjdelcerro
import org.gvsig.fmap.dal.feature.impl.dynobjectutils.DynObjectFeatureFacade;
121 40435 jjdelcerro
import org.gvsig.fmap.dal.feature.impl.undo.DefaultFeatureCommandsStack;
122
import org.gvsig.fmap.dal.feature.impl.undo.FeatureCommandsStack;
123 42925 jjdelcerro
import org.gvsig.fmap.dal.feature.paging.FeaturePagingHelper;
124 40435 jjdelcerro
import org.gvsig.fmap.dal.feature.spi.DefaultFeatureProvider;
125
import org.gvsig.fmap.dal.feature.spi.FeatureProvider;
126
import org.gvsig.fmap.dal.feature.spi.FeatureReferenceProviderServices;
127
import org.gvsig.fmap.dal.feature.spi.FeatureStoreProvider;
128
import org.gvsig.fmap.dal.feature.spi.FeatureStoreProviderServices;
129 43020 jjdelcerro
import org.gvsig.fmap.dal.feature.spi.FeatureStoreProvider_v2;
130 40435 jjdelcerro
import org.gvsig.fmap.dal.feature.spi.cache.FeatureCacheProvider;
131
import org.gvsig.fmap.dal.feature.spi.index.FeatureIndexProviderServices;
132
import org.gvsig.fmap.dal.impl.DefaultDataManager;
133
import org.gvsig.fmap.dal.resource.Resource;
134 43020 jjdelcerro
import org.gvsig.fmap.dal.spi.DataStoreInitializer2;
135 40435 jjdelcerro
import org.gvsig.fmap.dal.spi.DataStoreProvider;
136 43020 jjdelcerro
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
137 43358 jjdelcerro
import org.gvsig.fmap.geom.SpatialIndex;
138 40435 jjdelcerro
import org.gvsig.fmap.geom.primitive.Envelope;
139
import org.gvsig.metadata.MetadataLocator;
140
import org.gvsig.metadata.MetadataManager;
141
import org.gvsig.metadata.exceptions.MetadataException;
142
import org.gvsig.timesupport.Interval;
143
import org.gvsig.tools.ToolsLocator;
144
import org.gvsig.tools.dispose.DisposableIterator;
145 43642 jjdelcerro
import org.gvsig.tools.dispose.DisposeUtils;
146 40435 jjdelcerro
import org.gvsig.tools.dispose.impl.AbstractDisposable;
147
import org.gvsig.tools.dynobject.DelegatedDynObject;
148
import org.gvsig.tools.dynobject.DynClass;
149
import org.gvsig.tools.dynobject.DynObject;
150
import org.gvsig.tools.dynobject.DynObjectManager;
151 43246 jjdelcerro
import org.gvsig.tools.dynobject.DynObject_v2;
152 40435 jjdelcerro
import org.gvsig.tools.dynobject.DynStruct;
153
import org.gvsig.tools.dynobject.exception.DynFieldNotFoundException;
154
import org.gvsig.tools.dynobject.exception.DynMethodException;
155
import org.gvsig.tools.exception.BaseException;
156
import org.gvsig.tools.exception.NotYetImplemented;
157 41928 jjdelcerro
import org.gvsig.tools.identitymanagement.SimpleIdentityManager;
158 40435 jjdelcerro
import org.gvsig.tools.observer.Observable;
159
import org.gvsig.tools.observer.Observer;
160
import org.gvsig.tools.observer.impl.DelegateWeakReferencingObservable;
161
import org.gvsig.tools.persistence.PersistenceManager;
162
import org.gvsig.tools.persistence.Persistent;
163
import org.gvsig.tools.persistence.PersistentState;
164
import org.gvsig.tools.persistence.exception.PersistenceException;
165
import org.gvsig.tools.undo.RedoException;
166
import org.gvsig.tools.undo.UndoException;
167
import org.gvsig.tools.undo.command.Command;
168 43215 jjdelcerro
import org.gvsig.tools.util.HasAFile;
169 40435 jjdelcerro
import org.gvsig.tools.visitor.Visitor;
170 43152 fdiaz
171 42533 dmartinezizquierdo
import org.slf4j.Logger;
172
import org.slf4j.LoggerFactory;
173 40435 jjdelcerro
174 41243 jjdelcerro
public class DefaultFeatureStore extends AbstractDisposable implements
175 43020 jjdelcerro
    DataStoreInitializer2, FeatureStoreProviderServices, FeatureStore, Observer {
176 40435 jjdelcerro
177
    private static final Logger LOG = LoggerFactory
178 42293 jjdelcerro
        .getLogger(DefaultFeatureStore.class);
179 40435 jjdelcerro
180
    private static final String PERSISTENCE_DEFINITION_NAME = "FeatureStore";
181
182
    private DataStoreParameters parameters = null;
183
    private FeatureSelection selection;
184
    private FeatureLocks locks;
185
186 42293 jjdelcerro
    private DelegateWeakReferencingObservable delegateObservable =
187
        new DelegateWeakReferencingObservable(this);
188 40435 jjdelcerro
189
    private FeatureCommandsStack commands;
190 43841 jjdelcerro
191
    /*
192
    TODO: Sustituir estos tres manager por un EditingManager
193
    */
194 40435 jjdelcerro
    private FeatureTypeManager featureTypeManager;
195
    private FeatureManager featureManager;
196
    private SpatialManager spatialManager;
197
198
    private FeatureType defaultFeatureType = null;
199
    private List featureTypes = new ArrayList();
200
201
    private int mode = MODE_QUERY;
202
    private long versionOfUpdate = 0;
203
    private boolean hasStrongChanges = true;
204
    private boolean hasInserts = true;
205
206
    private DefaultDataManager dataManager = null;
207
208
    private FeatureStoreProvider provider = null;
209
210
    private DefaultFeatureIndexes indexes;
211
212
    private DefaultFeatureStoreTransforms transforms;
213
214
    DelegatedDynObject metadata;
215 41818 fdiaz
216 40435 jjdelcerro
    private Set metadataChildren;
217
218
    private Long featureCount = null;
219
220
    private long temporalOid = 0;
221
222
    private FeatureCacheProvider cache;
223
224 43215 jjdelcerro
    StateInformation state;
225 43270 fdiaz
226 43135 jjdelcerro
    FeatureStoreTimeSupport timeSupport;
227 43215 jjdelcerro
228
229
    private class StateInformation extends HashMap<Object, Object> {
230
231
        private static final long serialVersionUID = 4109026189635185666L;
232
233
        private boolean broken;
234
        private Throwable breakingsCause;
235 43270 fdiaz
236 43840 jjdelcerro
        @SuppressWarnings("OverridableMethodCallInConstructor")
237 43215 jjdelcerro
        public StateInformation() {
238
            this.clear();
239
        }
240 43270 fdiaz
241 43215 jjdelcerro
        @Override
242
        public void clear() {
243
            this.broken = false;
244
            this.breakingsCause = null;
245
            super.clear();
246
        }
247 43270 fdiaz
248 43215 jjdelcerro
        public boolean isBroken() {
249
            return this.broken;
250
        }
251 43270 fdiaz
252 43215 jjdelcerro
        public void broken() {
253
            this.broken = true;
254
        }
255 43270 fdiaz
256 43215 jjdelcerro
        public Throwable getBreakingsCause() {
257
            return this.breakingsCause;
258
        }
259 43270 fdiaz
260 43215 jjdelcerro
        public void setBreakingsCause(Throwable cause) {
261
            if( this.breakingsCause==null ) {
262
                this.breakingsCause = cause;
263
            }
264
            this.broken = true;
265 43270 fdiaz
        }
266 43215 jjdelcerro
    }
267
268
269 43270 fdiaz
270 40435 jjdelcerro
    /*
271
     * TODO:
272 41818 fdiaz
     *
273 40435 jjdelcerro
     * - Comprobar que solo se pueden a?adir reglas de validacion sobre un
274
     * EditableFeatureType. - Comprobar que solo se puede hacer un update con un
275
     * featureType al que se le han cambiado las reglas de validacion cuando
276
     * hasStrongChanges=false.
277
     */
278 42293 jjdelcerro
279 40435 jjdelcerro
    public DefaultFeatureStore() {
280 43215 jjdelcerro
        this.state = new StateInformation();
281 40435 jjdelcerro
    }
282
283 43020 jjdelcerro
    @Override
284
    public void intialize(DataManager dataManager,
285 42293 jjdelcerro
        DataStoreParameters parameters) throws InitializeException {
286 40435 jjdelcerro
287
        DynObjectManager dynManager = ToolsLocator.getDynObjectManager();
288
289 43020 jjdelcerro
        this.metadata = (DelegatedDynObject) dynManager.createDynObject(
290 43152 fdiaz
            FeatureStore.METADATA_DEFINITION_NAME,
291 43020 jjdelcerro
            MetadataManager.METADATA_NAMESPACE
292
        );
293 40435 jjdelcerro
294
        this.dataManager = (DefaultDataManager) dataManager;
295
296
        this.parameters = parameters;
297
        this.transforms = new DefaultFeatureStoreTransforms(this);
298
        try {
299
            indexes = new DefaultFeatureIndexes(this);
300
        } catch (DataException e) {
301
            throw new InitializeException(e);
302
        }
303
304
    }
305
306 43020 jjdelcerro
    @Override
307
    public void setProvider(org.gvsig.fmap.dal.DataStoreProvider provider) {
308 40435 jjdelcerro
        this.provider = (FeatureStoreProvider) provider;
309 43020 jjdelcerro
        this.delegate((DynObject) provider);
310 40435 jjdelcerro
        this.metadataChildren = new HashSet();
311
        this.metadataChildren.add(provider);
312 43958 jjdelcerro
        loadDALFile();
313 40435 jjdelcerro
    }
314
315 43215 jjdelcerro
    @Override
316 40435 jjdelcerro
    public DataStoreParameters getParameters() {
317
        return parameters;
318
    }
319
320
    public int getMode() {
321
        return this.mode;
322
    }
323
324 43215 jjdelcerro
    @Override
325 40435 jjdelcerro
    public DataManager getManager() {
326
        return this.dataManager;
327
    }
328
329 43215 jjdelcerro
    @Override
330 40435 jjdelcerro
    public Iterator getChildren() {
331
        return this.provider.getChilds();
332
    }
333
334 43215 jjdelcerro
    @Override
335 40435 jjdelcerro
    public FeatureStoreProvider getProvider() {
336
        return this.provider;
337
    }
338
339
    public FeatureManager getFeatureManager() {
340
        return this.featureManager;
341
    }
342
343 43215 jjdelcerro
    @Override
344 40435 jjdelcerro
    public void setFeatureTypes(List types, FeatureType defaultType) {
345
        this.featureTypes = types;
346
        this.defaultFeatureType = defaultType;
347
    }
348
349
    public void open() throws OpenException {
350 42049 jjdelcerro
        if (this.mode != MODE_QUERY) {
351
            // TODO: Se puede hacer un open estando en edicion ?
352
            try {
353
                throw new IllegalStateException();
354 42293 jjdelcerro
            } catch(Exception ex) {
355
                LOG.warn("Opening a store in editing/append mode ("+this.getFullName()+").",ex);
356 42049 jjdelcerro
            }
357
        }
358 40435 jjdelcerro
        this.notifyChange(DataStoreNotification.BEFORE_OPEN);
359
        this.provider.open();
360
        this.notifyChange(DataStoreNotification.AFTER_OPEN);
361
    }
362
363 43215 jjdelcerro
    @Override
364 40435 jjdelcerro
    public void refresh() throws OpenException, InitializeException {
365
        if (this.mode != MODE_QUERY) {
366
            throw new IllegalStateException();
367
        }
368
        this.notifyChange(FeatureStoreNotification.BEFORE_REFRESH);
369 43215 jjdelcerro
        if( state.isBroken() ) {
370
            this.load(state);
371
        } else {
372
            this.featureCount = null;
373
            this.provider.refresh();
374
        }
375 40435 jjdelcerro
        this.notifyChange(FeatureStoreNotification.AFTER_REFRESH);
376
    }
377
378
    public void close() throws CloseException {
379 42049 jjdelcerro
        if (this.mode != MODE_QUERY) {
380
            // TODO: Se puede hacer un close estando en edicion ?
381
            try {
382
                throw new IllegalStateException();
383 42293 jjdelcerro
            } catch(Exception ex) {
384
                LOG.warn("Clossing a store in editing/append mode ("+this.getFullName()+").",ex);
385 42049 jjdelcerro
            }
386
        }
387 40435 jjdelcerro
        this.notifyChange(DataStoreNotification.BEFORE_CLOSE);
388
        this.featureCount = null;
389
        this.provider.close();
390
        this.notifyChange(DataStoreNotification.AFTER_CLOSE);
391
    }
392
393 43215 jjdelcerro
    @Override
394 40435 jjdelcerro
    protected void doDispose() throws BaseException {
395 42049 jjdelcerro
        if (this.mode != MODE_QUERY) {
396
            // TODO: Se puede hacer un dispose estando en edicion ?
397
            try {
398
                throw new IllegalStateException();
399 42293 jjdelcerro
            } catch(Exception ex) {
400
                LOG.warn("Dispossing a store in editing/append mode ("+this.getFullName()+").",ex);
401 42049 jjdelcerro
            }
402
        }
403 40435 jjdelcerro
        this.notifyChange(DataStoreNotification.BEFORE_DISPOSE);
404
        this.disposeIndexes();
405 43377 jjdelcerro
        if( this.provider!=null ) {
406
            this.provider.dispose();
407
        }
408 40435 jjdelcerro
        if (this.selection != null) {
409
            this.selection.dispose();
410
            this.selection = null;
411
        }
412
        this.commands = null;
413
        this.featureCount = null;
414
        if (this.locks != null) {
415
            // this.locks.dispose();
416
            this.locks = null;
417
        }
418
419
        if (this.featureTypeManager != null) {
420
            this.featureTypeManager.dispose();
421
            this.featureTypeManager = null;
422
        }
423
424
        this.featureManager = null;
425
        this.spatialManager = null;
426
427
        this.parameters = null;
428
        this.notifyChange(DataStoreNotification.AFTER_DISPOSE);
429
        if (delegateObservable != null) {
430
            this.delegateObservable.deleteObservers();
431
            this.delegateObservable = null;
432
        }
433
    }
434
435 43215 jjdelcerro
    @Override
436 40435 jjdelcerro
    public boolean allowWrite() {
437 41928 jjdelcerro
        SimpleIdentityManager identityManager = ToolsLocator.getIdentityManager();
438 42293 jjdelcerro
        if( ! identityManager.getCurrentIdentity().isAuthorized(DataManager.WRITE_STORE_AUTHORIZATION,this.getParameters(), this.getName()) ) {
439 41928 jjdelcerro
            return false;
440
        }
441 40435 jjdelcerro
        return this.provider.allowWrite();
442
    }
443
444 43215 jjdelcerro
    @Override
445 40435 jjdelcerro
    public boolean canWriteGeometry(int geometryType) throws DataException {
446
        return this.provider.canWriteGeometry(geometryType, 0);
447
    }
448
449 43215 jjdelcerro
    @Override
450 40435 jjdelcerro
    public DataServerExplorer getExplorer() throws ReadException,
451 42293 jjdelcerro
        ValidateDataParametersException {
452 43215 jjdelcerro
        if( this.state.isBroken() ) {
453
            try {
454
                return this.provider.getExplorer();
455
            } catch(Throwable th) {
456
                return null;
457
            }
458
        } else {
459
            return this.provider.getExplorer();
460
        }
461 40435 jjdelcerro
    }
462
463
    /*
464
     * public Metadata getMetadata() throws MetadataNotFoundException {
465
     * // TODO:
466
     * // Si el provider devuelbe null habria que ver de construir aqui
467
     * // los metadatos basicos, como el Envelope y el SRS.
468 41818 fdiaz
     *
469 40435 jjdelcerro
     * // TODO: Estando en edicion el Envelope deberia de
470
     * // actualizarse usando el spatialManager
471
     * return this.provider.getMetadata();
472
     * }
473
     */
474 42293 jjdelcerro
475 43215 jjdelcerro
    @Override
476 40435 jjdelcerro
    public Envelope getEnvelope() throws DataException {
477
        if (this.mode == MODE_FULLEDIT) {
478 42293 jjdelcerro
                // Just in case another thread tries to write in the store
479
                synchronized (this) {
480
                        return this.spatialManager.getEnvelope();
481
                        }
482 40435 jjdelcerro
        }
483 42293 jjdelcerro
        if (hasDynValue(DataStore.METADATA_ENVELOPE)){
484
            return (Envelope)getDynValue(DataStore.METADATA_ENVELOPE);
485 40435 jjdelcerro
        }
486
        return this.provider.getEnvelope();
487
    }
488
489
    /**
490 43840 jjdelcerro
     * @throws org.gvsig.fmap.dal.exception.DataException
491 40435 jjdelcerro
     * @deprecated use getDefaultFeatureType().getDefaultSRS()
492
     */
493 43215 jjdelcerro
    @Override
494 40435 jjdelcerro
    public IProjection getSRSDefaultGeometry() throws DataException {
495
        return this.getDefaultFeatureType().getDefaultSRS();
496
    }
497
498 43215 jjdelcerro
    @Override
499 40435 jjdelcerro
    public FeatureSelection createDefaultFeatureSelection()
500 42293 jjdelcerro
        throws DataException {
501 40435 jjdelcerro
        return new DefaultFeatureSelection(this);
502
    }
503
504 43215 jjdelcerro
    @Override
505 40435 jjdelcerro
    public FeatureProvider createDefaultFeatureProvider(FeatureType type)
506 42293 jjdelcerro
        throws DataException {
507 40435 jjdelcerro
        if (type.hasOID()) {
508
            return new DefaultFeatureProvider(type,
509 42293 jjdelcerro
                this.provider.createNewOID());
510 40435 jjdelcerro
        }
511
        return new DefaultFeatureProvider(type);
512
    }
513
514 43215 jjdelcerro
    @Override
515 40435 jjdelcerro
    public void saveToState(PersistentState state) throws PersistenceException {
516 40776 nbrodin
        /*if (this.mode != FeatureStore.MODE_QUERY) {
517 42293 jjdelcerro
            throw new PersistenceException(new IllegalStateException(
518
                this.getName()));
519
        }*/
520 40435 jjdelcerro
        state.set("dataStoreName", this.getName());
521
        state.set("parameters", this.parameters);
522
        state.set("selection", this.selection);
523
        state.set("transforms", this.transforms);
524
        // TODO locks persistence
525
        // state.set("locks", this.locks);
526
        // TODO indexes persistence
527
        // state.set("indexes", this.indexes);
528
        Map evaluatedAttr = new HashMap(1);
529
        Iterator iterType = featureTypes.iterator();
530
        Iterator iterAttr;
531
        FeatureType type;
532
        DefaultFeatureAttributeDescriptor attr;
533
        List attrs;
534
        while (iterType.hasNext()) {
535
            type = (FeatureType) iterType.next();
536
            attrs = new ArrayList();
537
            iterAttr = type.iterator();
538
            while (iterAttr.hasNext()) {
539
                attr = (DefaultFeatureAttributeDescriptor) iterAttr.next();
540
                if ((attr.getEvaluator() != null)
541 42293 jjdelcerro
                    && (attr.getEvaluator() instanceof Persistent)) {
542 40435 jjdelcerro
                    attrs.add(attr);
543
                }
544
            }
545
            if (!attrs.isEmpty()) {
546
                evaluatedAttr.put(type.getId(), attrs);
547
            }
548
549
        }
550
551
        if (evaluatedAttr.isEmpty()) {
552
            evaluatedAttr = null;
553
        }
554
555
        state.set("evaluatedAttributes", evaluatedAttr);
556
        state.set("defaultFeatureTypeId", defaultFeatureType.getId());
557
558
    }
559 43270 fdiaz
560 43215 jjdelcerro
    @Override
561
    public void loadFromState(final PersistentState persistentState)
562 42293 jjdelcerro
        throws PersistenceException {
563 40435 jjdelcerro
        if (this.provider != null) {
564
            throw new PersistenceStoreAlreadyLoadedException(this.getName());
565
        }
566
        if (this.getManager() == null) {
567
            this.dataManager = (DefaultDataManager) DALLocator.getDataManager();
568
        }
569 43215 jjdelcerro
        state.clear();
570
        try {
571
            state.put("parameters", persistentState.get("parameters"));
572
        } catch(Throwable th) {
573
            state.setBreakingsCause(th);
574
        }
575
        try {
576
            state.put("selection", persistentState.get("selection"));
577
        } catch(Throwable th) {
578
            state.setBreakingsCause(th);
579
        }
580
        try {
581
            state.put("transforms",  persistentState.get("transforms"));
582
        } catch(Throwable th) {
583
            state.setBreakingsCause(th);
584
        }
585
        try {
586
            state.put("evaluatedAttributes",  persistentState.get("evaluatedAttributes"));
587
        } catch(Throwable th) {
588
            state.setBreakingsCause(th);
589
        }
590
        try {
591
            state.put("defaultFeatureTypeId", persistentState.getString("defaultFeatureTypeId"));
592
        } catch(Throwable th) {
593
            state.setBreakingsCause(th);
594
        }
595
        load(state);
596 43270 fdiaz
    }
597
598
    private void load(StateInformation state) {
599 43215 jjdelcerro
        this.featureTypes = new ArrayList();
600
        this.defaultFeatureType = null;
601
        this.featureCount = null;
602 40435 jjdelcerro
603 43215 jjdelcerro
        DataStoreParameters params = (DataStoreParameters) state.get("parameters");
604
        try {
605
            intialize(dataManager, params);
606
        } catch(Throwable th) {
607
            state.setBreakingsCause(th);
608
        }
609 40435 jjdelcerro
610
        try {
611 43215 jjdelcerro
            DataStoreProvider prov = dataManager.createProvider(
612
                getStoreProviderServices(),
613
                params
614 43020 jjdelcerro
            );
615 43215 jjdelcerro
            setProvider(prov);
616
        } catch(Throwable th) {
617
            state.setBreakingsCause(th);
618
        }
619 43152 fdiaz
620 43215 jjdelcerro
        try {
621
            selection = (FeatureSelection) state.get("selection");
622
        } catch(Throwable th) {
623
            state.setBreakingsCause(th);
624
        }
625
626
        try {
627
            this.transforms = (DefaultFeatureStoreTransforms) state.get("transforms");
628
            this.transforms.setFeatureStore(this);
629
            for( FeatureStoreTransform transform : this.transforms ) {
630
                try {
631
                    transform.setUp();
632
                } catch(Throwable th) {
633
                    state.setBreakingsCause(th);
634
                }
635
            }
636
        } catch(Throwable th) {
637
            state.setBreakingsCause(th);
638
        }
639
640
        try {
641 40435 jjdelcerro
            Map evaluatedAttributes = (Map) state.get("evaluatedAttributes");
642
            if ((evaluatedAttributes != null) && !evaluatedAttributes.isEmpty()) {
643 43215 jjdelcerro
                    Iterator iterEntries = evaluatedAttributes.entrySet().iterator();
644
                    while (iterEntries.hasNext()) {
645
                            Entry entry = (Entry) iterEntries.next();
646
                            List attrs = (List) entry.getValue();
647
                            if (attrs.isEmpty()) {
648
                                    continue;
649
                            }
650
                            int fTypePos = -1;
651
                            DefaultFeatureType type = null;
652
                            for (int i = 0; i < featureTypes.size(); i++) {
653
                                    type = (DefaultFeatureType) featureTypes.get(i);
654
                                    if (type.getId().equals(entry.getKey())) {
655
                                            fTypePos = i;
656
                                            break;
657
                                    }
658
                            }
659
                            if (type == null) {
660
                                    throw new PersistenceCantFindFeatureTypeException(
661
                                            getName(), (String) entry.getKey());
662
                            }
663
                            DefaultEditableFeatureType eType = (DefaultEditableFeatureType) type.getEditable();
664
                            Iterator<FeatureAttributeDescriptor> iterAttr = attrs.iterator();
665
                            while (iterAttr.hasNext()) {
666
                                    FeatureAttributeDescriptor attr = iterAttr.next();
667
                                    eType.addLike(attr);
668
                            }
669
                            featureTypes.set(fTypePos, eType.getNotEditableCopy());
670
671 40435 jjdelcerro
                    }
672
673
            }
674 43215 jjdelcerro
        } catch(Throwable th) {
675
            state.setBreakingsCause(th);
676
        }
677 40435 jjdelcerro
678 43270 fdiaz
679 43215 jjdelcerro
        try {
680
            String defaultFeatureTypeId = (String) state.get("defaultFeatureTypeId");
681
            FeatureType ftype;
682 41818 fdiaz
683 43215 jjdelcerro
            if (defaultFeatureType == null ||
684
                    defaultFeatureType.getId() == null ||
685
                    !defaultFeatureType.getId().equals(defaultFeatureTypeId)) {
686 40435 jjdelcerro
687 43215 jjdelcerro
                    ftype = getFeatureType(defaultFeatureTypeId);
688
                    if (ftype == null) {
689
                            /*
690
                             * Un error en el m?todo de PostgreSQL getName(), hace que
691
                             * el nombre del featureType sea valor retornado por el getProviderName()
692
                             * De momento se pone este parche para apa?arlo y poder mantener compatibilidad
693
                             * con proyectos antiguos (2.1 y 2.2)
694
                             */
695
                            ftype = getFeatureType(getName());
696
                            if(ftype == null ) {
697
                                    throw new RuntimeException("Can't locate feature type");
698
                            }
699
                    }
700
                    defaultFeatureType = ftype;
701 40435 jjdelcerro
            }
702 43215 jjdelcerro
        } catch(Throwable th) {
703
            state.setBreakingsCause(th);
704 40435 jjdelcerro
        }
705
706 43270 fdiaz
        LOG.info("load() broken:{}, {}, {}.",
707 43215 jjdelcerro
                new Object[] { state.isBroken(), this.getProviderName(), params }
708
        );
709 40435 jjdelcerro
    }
710
711 43215 jjdelcerro
        public DataStoreProviderServices getStoreProviderServices() {
712
                return this;
713
        }
714 43270 fdiaz
715 40435 jjdelcerro
    public static void registerPersistenceDefinition() {
716
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
717
        if (manager.getDefinition(PERSISTENCE_DEFINITION_NAME) == null) {
718 42293 jjdelcerro
            DynStruct definition =
719
                manager.addDefinition(DefaultFeatureStore.class,
720
                    PERSISTENCE_DEFINITION_NAME, PERSISTENCE_DEFINITION_NAME
721
                        + " Persistent definition", null, null);
722 40435 jjdelcerro
            definition.addDynFieldString("dataStoreName").setMandatory(true)
723 42293 jjdelcerro
                .setPersistent(true);
724 40435 jjdelcerro
725
            definition.addDynFieldObject("parameters")
726 42293 jjdelcerro
                .setClassOfValue(DynObject.class).setMandatory(true)
727
                .setPersistent(true);
728 40435 jjdelcerro
729
            definition.addDynFieldObject("selection")
730 42293 jjdelcerro
                .setClassOfValue(FeatureSelection.class).setMandatory(false)
731
                .setPersistent(true);
732 40435 jjdelcerro
733
            definition.addDynFieldObject("transforms")
734 42293 jjdelcerro
                .setClassOfValue(DefaultFeatureStoreTransforms.class)
735
                .setMandatory(true).setPersistent(true);
736 40435 jjdelcerro
737
            definition.addDynFieldMap("evaluatedAttributes")
738 42293 jjdelcerro
                .setClassOfItems(List.class) // List<DefaultFeatureAttributeDescriptor>
739
                .setMandatory(false).setPersistent(true);
740 40435 jjdelcerro
741
            definition.addDynFieldString("defaultFeatureTypeId")
742 42293 jjdelcerro
                .setMandatory(true).setPersistent(true);
743 40435 jjdelcerro
        }
744
    }
745
746
    public static void registerMetadataDefinition() throws MetadataException {
747
        MetadataManager manager = MetadataLocator.getMetadataManager();
748 43020 jjdelcerro
        if (manager.getDefinition(FeatureStore.METADATA_DEFINITION_NAME) == null) {
749 42293 jjdelcerro
            DynStruct metadataDefinition =
750 43020 jjdelcerro
                manager.addDefinition(FeatureStore.METADATA_DEFINITION_NAME, null);
751 40435 jjdelcerro
            metadataDefinition.extend(manager
752 42293 jjdelcerro
                .getDefinition(DataStore.METADATA_DEFINITION_NAME));
753 40435 jjdelcerro
        }
754
    }
755
756
    //
757
    // ====================================================================
758
    // Gestion de la seleccion
759
    //
760 42293 jjdelcerro
761 43215 jjdelcerro
    @Override
762 40435 jjdelcerro
    public void setSelection(DataSet selection) throws DataException {
763
        this.setSelection((FeatureSet) selection);
764
    }
765
766 43215 jjdelcerro
    @Override
767 40435 jjdelcerro
    public DataSet createSelection() throws DataException {
768
        return createFeatureSelection();
769
    }
770
771 43215 jjdelcerro
    @Override
772 40435 jjdelcerro
    public DataSet getSelection() throws DataException {
773
        return this.getFeatureSelection();
774
    }
775
776 43215 jjdelcerro
    @Override
777 40435 jjdelcerro
    public void setSelection(FeatureSet selection) throws DataException {
778
        setSelection(selection, true);
779
    }
780
781
    public void setSelection(FeatureSet selection, boolean undoable)
782 42293 jjdelcerro
        throws DataException {
783 40435 jjdelcerro
        if (selection == null) {
784
            if (undoable) {
785
                throw new SelectionNotAllowedException(getName());
786
            }
787
788
        } else {
789
            if (selection.equals(this.selection)) {
790
                return;
791
            }
792
            if (!selection.isFromStore(this)) {
793
                throw new SelectionNotAllowedException(getName());
794
            }
795
        }
796
797
        if (this.selection != null) {
798
            this.selection.deleteObserver(this);
799
        }
800
        if (selection == null) {
801
            if (this.selection != null) {
802
                this.selection.dispose();
803
            }
804
            this.selection = null;
805
            return;
806
        }
807
        if (selection instanceof FeatureSelection) {
808
            if (undoable && isEditing()) {
809
                commands.selectionSet(this, this.selection,
810 42293 jjdelcerro
                    (FeatureSelection) selection);
811 40435 jjdelcerro
            }
812
            if (this.selection != null) {
813
                this.selection.dispose();
814
            }
815
            this.selection = (FeatureSelection) selection;
816
        } else {
817
            if (undoable && isEditing()) {
818
                commands.startComplex("_selectionSet");
819
            }
820
            if (selection instanceof DefaultFeatureSelection) {
821 42293 jjdelcerro
                DefaultFeatureSelection defSelection =
822
                    (DefaultFeatureSelection) selection;
823 40435 jjdelcerro
                defSelection.deselectAll(undoable);
824
                defSelection.select(selection, undoable);
825
            } else {
826
                this.selection.deselectAll();
827
                this.selection.select(selection);
828
            }
829
            if (undoable && isEditing()) {
830
                commands.endComplex();
831
            }
832
        }
833
        this.selection.addObserver(this);
834
835
        this.notifyChange(DataStoreNotification.SELECTION_CHANGE);
836
    }
837
838 43215 jjdelcerro
    @Override
839 40435 jjdelcerro
    public FeatureSelection createFeatureSelection() throws DataException {
840
        return this.provider.createFeatureSelection();
841
    }
842
843 43215 jjdelcerro
    @Override
844 40435 jjdelcerro
    public FeatureSelection getFeatureSelection() throws DataException {
845
        if (selection == null) {
846
            this.selection = createFeatureSelection();
847
            this.selection.addObserver(this);
848
        }
849
        return selection;
850
    }
851
852
    //
853
    // ====================================================================
854
    // Gestion de notificaciones
855
    //
856 42293 jjdelcerro
857 43093 jjdelcerro
    @Override
858
    public void notifyChange(FeatureStoreNotification storeNotification) {
859
        try {
860
            delegateObservable.notifyObservers(storeNotification);
861
        } catch (Throwable ex) {
862
            LOG.warn("Problems notifying changes in the store '"+this.getName()+" ("+storeNotification.getType()+").",ex);
863
        }
864
    }
865
866
    @Override
867 40435 jjdelcerro
    public void notifyChange(String notification) {
868
        if (delegateObservable != null) {
869
            notifyChange(new DefaultFeatureStoreNotification(this, notification));
870
        }
871
872
    }
873
874 43093 jjdelcerro
    @Override
875 40435 jjdelcerro
    public void notifyChange(String notification, FeatureProvider data) {
876 43093 jjdelcerro
        Feature f = null;
877 40435 jjdelcerro
        try {
878 43093 jjdelcerro
            f = createFeature(data);
879
        } catch (Throwable ex) {
880
            LOG.warn("Problems creating a feature to notifying changes in the store '"+this.getName()+" ("+notification+").",ex);
881 40435 jjdelcerro
        }
882 43093 jjdelcerro
        notifyChange(notification, f);
883 40435 jjdelcerro
    }
884
885
    public void notifyChange(String notification, Feature feature) {
886
        notifyChange(new DefaultFeatureStoreNotification(this, notification,
887 42293 jjdelcerro
            feature));
888 40435 jjdelcerro
    }
889
890
    public void notifyChange(String notification, Command command) {
891
        notifyChange(new DefaultFeatureStoreNotification(this, notification,
892 42293 jjdelcerro
            command));
893 40435 jjdelcerro
    }
894
895
    public void notifyChange(String notification, EditableFeatureType type) {
896
        notifyChange(new DefaultFeatureStoreNotification(this, notification,
897 42293 jjdelcerro
            type));
898 40435 jjdelcerro
    }
899
900 43093 jjdelcerro
    @Override
901 40435 jjdelcerro
    public void notifyChange(String notification, Resource resource) {
902
        notifyChange(new DefaultFeatureStoreNotification(this,
903 42293 jjdelcerro
            DataStoreNotification.RESOURCE_CHANGED));
904 40435 jjdelcerro
    }
905
906
    //
907
    // ====================================================================
908
    // Gestion de bloqueos
909
    //
910 42293 jjdelcerro
911 43215 jjdelcerro
    @Override
912 40435 jjdelcerro
    public boolean isLocksSupported() {
913
        return this.provider.isLocksSupported();
914
    }
915
916 43215 jjdelcerro
    @Override
917 40435 jjdelcerro
    public FeatureLocks getLocks() throws DataException {
918
        if (!this.provider.isLocksSupported()) {
919
            LOG.warn("Locks not supported");
920
            return null;
921
        }
922
        if (locks == null) {
923
            this.locks = this.provider.createFeatureLocks();
924
        }
925
        return locks;
926
    }
927
928
    //
929
    // ====================================================================
930
    // Interface Observable
931
    //
932 42293 jjdelcerro
933 43215 jjdelcerro
    @Override
934 40435 jjdelcerro
    public void disableNotifications() {
935
        this.delegateObservable.disableNotifications();
936
937
    }
938
939 43215 jjdelcerro
    @Override
940 40435 jjdelcerro
    public void enableNotifications() {
941
        this.delegateObservable.enableNotifications();
942
    }
943
944 43215 jjdelcerro
    @Override
945 40435 jjdelcerro
    public void beginComplexNotification() {
946
        this.delegateObservable.beginComplexNotification();
947
948
    }
949
950 43215 jjdelcerro
    @Override
951 40435 jjdelcerro
    public void endComplexNotification() {
952
        this.delegateObservable.endComplexNotification();
953
954
    }
955
956 43215 jjdelcerro
    @Override
957 40435 jjdelcerro
    public void addObserver(Observer observer) {
958
        if (delegateObservable != null) {
959
            this.delegateObservable.addObserver(observer);
960
        }
961
    }
962
963 43215 jjdelcerro
    @Override
964 40435 jjdelcerro
    public void deleteObserver(Observer observer) {
965
        if (delegateObservable != null) {
966
            this.delegateObservable.deleteObserver(observer);
967
        }
968
    }
969
970 43215 jjdelcerro
    @Override
971 40435 jjdelcerro
    public void deleteObservers() {
972
        this.delegateObservable.deleteObservers();
973
974
    }
975
976
    //
977
    // ====================================================================
978
    // Interface Observer
979
    //
980
    // Usado para observar:
981
    // - su seleccion
982
    // - sus bloqueos
983
    // - sus recursos
984
    //
985 42293 jjdelcerro
986 43215 jjdelcerro
    @Override
987 40435 jjdelcerro
    public void update(Observable observable, Object notification) {
988
        if (observable instanceof FeatureSet) {
989
            if (observable == this.selection) {
990
                this.notifyChange(DataStoreNotification.SELECTION_CHANGE);
991 43270 fdiaz
            } else if (observable == this.locks) {
992
                this.notifyChange(FeatureStoreNotification.LOCKS_CHANGE);
993
            }
994 40435 jjdelcerro
995 43270 fdiaz
        } else if (observable instanceof FeatureStoreProvider) {
996
            if (observable == this.provider) {
997 40435 jjdelcerro
998
            }
999 43270 fdiaz
        } else if (observable instanceof FeatureReferenceSelection) {
1000
            if(notification instanceof String){
1001
                    this.notifyChange((String)notification);
1002
            }
1003
        }
1004 40435 jjdelcerro
    }
1005
1006
    //
1007
    // ====================================================================
1008
    // Edicion
1009
    //
1010 42293 jjdelcerro
1011 40435 jjdelcerro
    private void newVersionOfUpdate() {
1012
        this.versionOfUpdate++;
1013
    }
1014
1015
    private long currentVersionOfUpdate() {
1016
        return this.versionOfUpdate;
1017
    }
1018
1019
    private void checkInEditingMode() throws NeedEditingModeException {
1020
        if (mode != MODE_FULLEDIT) {
1021
            throw new NeedEditingModeException(this.getName());
1022
        }
1023
    }
1024
1025
    private void checkNotInAppendMode() throws IllegalStateException {
1026
        if (mode == MODE_APPEND) {
1027 42293 jjdelcerro
                        throw new IllegalStateException("Error: store "
1028
                                        + this.getFullName() + " is in append mode");
1029 40435 jjdelcerro
        }
1030
    }
1031
1032
    private void checkIsOwnFeature(Feature feature)
1033 42293 jjdelcerro
        throws IllegalFeatureException {
1034 40435 jjdelcerro
        if (((DefaultFeature) feature).getStore() != this) {
1035
            throw new IllegalFeatureException(this.getName());
1036
        }
1037
        // FIXME: fixFeatureType no vale para el checkIsOwnFeature
1038
        // fixFeatureType((DefaultFeatureType) feature.getType());
1039
    }
1040
1041
    private void exitEditingMode() {
1042
        if (commands != null) {
1043
            commands.clear();
1044
            commands = null;
1045
        }
1046
1047
        if (featureTypeManager != null) {
1048
            featureTypeManager.dispose();
1049
            featureTypeManager = null;
1050
1051
        }
1052
1053
        // TODO implementar un dispose para estos dos
1054
        featureManager = null;
1055
        spatialManager = null;
1056
1057
        featureCount = null;
1058
1059
        mode = MODE_QUERY;
1060
        hasStrongChanges = true; // Lo deja a true por si las moscas
1061
        hasInserts = true;
1062
    }
1063
1064 43215 jjdelcerro
    @Override
1065 40435 jjdelcerro
    synchronized public void edit() throws DataException {
1066
        edit(MODE_FULLEDIT);
1067
    }
1068
1069 43215 jjdelcerro
    @Override
1070 40435 jjdelcerro
    synchronized public void edit(int mode) throws DataException {
1071 43215 jjdelcerro
        LOG.debug("Starting editing in mode: {}", mode);
1072 40435 jjdelcerro
        try {
1073
            if (this.mode != MODE_QUERY) {
1074
                throw new AlreadyEditingException(this.getName());
1075
            }
1076
            if (!this.provider.supportsAppendMode()) {
1077
                mode = MODE_FULLEDIT;
1078
            }
1079
            switch (mode) {
1080 42293 jjdelcerro
            case MODE_QUERY:
1081
                throw new IllegalStateException(this.getName());
1082
1083
            case MODE_FULLEDIT:
1084
                if (!this.transforms.isEmpty()) {
1085 40435 jjdelcerro
                    throw new IllegalStateException(this.getName());
1086 42293 jjdelcerro
                }
1087
                notifyChange(FeatureStoreNotification.BEFORE_STARTEDITING);
1088
                invalidateIndexes();
1089 43840 jjdelcerro
                featureManager = new FeatureManager();
1090
                featureTypeManager = new FeatureTypeManager(this);
1091
                spatialManager = new SpatialManager(this, provider.getEnvelope());
1092 40435 jjdelcerro
1093 43840 jjdelcerro
                commands = new DefaultFeatureCommandsStack(
1094
                        this, featureManager,
1095 42293 jjdelcerro
                        spatialManager, featureTypeManager);
1096
                this.mode = MODE_FULLEDIT;
1097
                hasStrongChanges = false;
1098
                hasInserts = false;
1099
                notifyChange(FeatureStoreNotification.AFTER_STARTEDITING);
1100
                break;
1101
            case MODE_APPEND:
1102
                if (!this.transforms.isEmpty()) {
1103
                    throw new IllegalStateException(this.getName());
1104
                }
1105
                notifyChange(FeatureStoreNotification.BEFORE_STARTEDITING);
1106
                invalidateIndexes();
1107
                this.provider.beginAppend();
1108
                this.mode = MODE_APPEND;
1109
                hasInserts = false;
1110
                notifyChange(FeatureStoreNotification.AFTER_STARTEDITING);
1111
                break;
1112 40435 jjdelcerro
            }
1113
        } catch (Exception e) {
1114
            throw new StoreEditException(e, this.getName());
1115
        }
1116
    }
1117
1118
    private void invalidateIndexes() {
1119
        setIndexesValidStatus(false);
1120
    }
1121
1122
    private void setIndexesValidStatus(boolean valid) {
1123 43215 jjdelcerro
        FeatureIndexes theIndexes = getIndexes();
1124 40435 jjdelcerro
        LOG.debug("Setting the store indexes to valid status {}: {}", (valid
1125 43215 jjdelcerro
            ? Boolean.TRUE : Boolean.FALSE), theIndexes);
1126
        for (Iterator iterator = theIndexes.iterator(); iterator.hasNext();) {
1127 40435 jjdelcerro
            FeatureIndex index = (FeatureIndex) iterator.next();
1128
            if (index instanceof FeatureIndexProviderServices) {
1129 42293 jjdelcerro
                FeatureIndexProviderServices indexServices =
1130
                    (FeatureIndexProviderServices) index;
1131 40435 jjdelcerro
                indexServices.setValid(valid);
1132
            }
1133
        }
1134
    }
1135
1136
    private void updateIndexes() throws FeatureIndexException {
1137 43215 jjdelcerro
        FeatureIndexes theIndexes = getIndexes();
1138
        LOG.debug("Refilling indexes: {}", theIndexes);
1139
        for (Iterator iterator = theIndexes.iterator(); iterator.hasNext();) {
1140 40435 jjdelcerro
            FeatureIndex index = (FeatureIndex) iterator.next();
1141
            if (index instanceof FeatureIndexProviderServices) {
1142 42293 jjdelcerro
                FeatureIndexProviderServices indexServices =
1143
                    (FeatureIndexProviderServices) index;
1144 40435 jjdelcerro
                indexServices.fill(true, null);
1145
            }
1146
        }
1147
    }
1148
1149
    private void waitForIndexes() {
1150 43215 jjdelcerro
        FeatureIndexes theIndexes = getIndexes();
1151
        LOG.debug("Waiting for indexes to finish filling: {}", theIndexes);
1152
        for (Iterator iterator = theIndexes.iterator(); iterator.hasNext();) {
1153 40435 jjdelcerro
            FeatureIndex index = (FeatureIndex) iterator.next();
1154
            if (index instanceof FeatureIndexProviderServices) {
1155 42293 jjdelcerro
                FeatureIndexProviderServices indexServices =
1156
                    (FeatureIndexProviderServices) index;
1157 40435 jjdelcerro
                indexServices.waitForIndex();
1158
            }
1159
        }
1160
    }
1161
1162
    private void disposeIndexes() {
1163 43215 jjdelcerro
        FeatureIndexes theIndexes = getIndexes();
1164
        LOG.debug("Disposing indexes: {}", theIndexes);
1165 43377 jjdelcerro
        if( theIndexes==null ) {
1166
            return;
1167
        }
1168 43215 jjdelcerro
        for (Iterator iterator = theIndexes.iterator(); iterator.hasNext();) {
1169 40435 jjdelcerro
            FeatureIndex index = (FeatureIndex) iterator.next();
1170
            if (index instanceof FeatureIndexProviderServices) {
1171 42293 jjdelcerro
                FeatureIndexProviderServices indexServices =
1172
                    (FeatureIndexProviderServices) index;
1173 40435 jjdelcerro
                indexServices.dispose();
1174
            }
1175
        }
1176
    }
1177
1178 43215 jjdelcerro
    @Override
1179 40435 jjdelcerro
    public boolean isEditing() {
1180
        return mode == MODE_FULLEDIT;
1181
    }
1182
1183 43215 jjdelcerro
    @Override
1184 40435 jjdelcerro
    public boolean isAppending() {
1185
        return mode == MODE_APPEND;
1186
    }
1187
1188 43215 jjdelcerro
    @Override
1189 40435 jjdelcerro
    synchronized public void update(EditableFeatureType type)
1190 42293 jjdelcerro
        throws DataException {
1191 40435 jjdelcerro
        try {
1192
            if (type == null) {
1193
                throw new NullFeatureTypeException(getName());
1194
            }
1195 43981 omartinez
            boolean typehasStrongChanges = ((DefaultEditableFeatureType) type).hasStrongChanges();
1196
            if (typehasStrongChanges) {
1197
                checkInEditingMode();
1198 43992 jjdelcerro
            }  else if(this.isAppending()) {
1199 43981 omartinez
                throw new NeedEditingModeException(this.getName());
1200
            }
1201 40435 jjdelcerro
            // FIXME: Comprobar que es un featureType aceptable.
1202
            notifyChange(FeatureStoreNotification.BEFORE_UPDATE_TYPE, type);
1203
            newVersionOfUpdate();
1204 43981 omartinez
1205
            if (typehasStrongChanges) {
1206
                FeatureType oldt = type.getSource().getCopy();
1207
                FeatureType newt = type.getCopy();
1208
                commands.update(newt, oldt);
1209 40435 jjdelcerro
                hasStrongChanges = true;
1210 43981 omartinez
            } else {
1211
                boolean ok = this.featureTypes.remove(this.defaultFeatureType);
1212 43992 jjdelcerro
                this.defaultFeatureType = type.getNotEditableCopy();
1213 43981 omartinez
                if (ok) {
1214
                    this.featureTypes.add(this.defaultFeatureType);
1215
                }
1216 40435 jjdelcerro
            }
1217
            notifyChange(FeatureStoreNotification.AFTER_UPDATE_TYPE, type);
1218
        } catch (Exception e) {
1219
            throw new StoreUpdateFeatureTypeException(e, this.getName());
1220
        }
1221
    }
1222
1223 43215 jjdelcerro
    @Override
1224 41818 fdiaz
    public void delete(Feature feature) throws DataException {
1225 40435 jjdelcerro
        this.commands.delete(feature);
1226
    }
1227 41818 fdiaz
1228 40435 jjdelcerro
    synchronized public void doDelete(Feature feature) throws DataException {
1229
        try {
1230
            checkInEditingMode();
1231
            checkIsOwnFeature(feature);
1232
            if (feature instanceof EditableFeature) {
1233
                throw new StoreDeleteEditableFeatureException(getName());
1234
            }
1235 41818 fdiaz
            notifyChange(FeatureStoreNotification.BEFORE_DELETE, feature);
1236
1237 40435 jjdelcerro
            //Update the featureManager and the spatialManager
1238
            featureManager.delete(feature.getReference());
1239
            spatialManager.deleteFeature(feature);
1240 41818 fdiaz
1241 40435 jjdelcerro
            newVersionOfUpdate();
1242
            hasStrongChanges = true;
1243
            notifyChange(FeatureStoreNotification.AFTER_DELETE, feature);
1244
        } catch (Exception e) {
1245
            throw new StoreDeleteFeatureException(e, this.getName());
1246
        }
1247
    }
1248
1249
    private static EditableFeature lastChangedFeature = null;
1250
1251 43215 jjdelcerro
    @Override
1252 41818 fdiaz
    public synchronized void insert(EditableFeature feature)
1253 42293 jjdelcerro
        throws DataException {
1254 43215 jjdelcerro
        LOG.debug("In editing mode {}, insert feature: {}", mode, feature);
1255 40435 jjdelcerro
        try {
1256
            switch (mode) {
1257 42293 jjdelcerro
            case MODE_QUERY:
1258
                throw new NeedEditingModeException(this.getName());
1259 40435 jjdelcerro
1260 42293 jjdelcerro
            case MODE_APPEND:
1261
                checkIsOwnFeature(feature);
1262
                if (feature.getSource() != null) {
1263
                    throw new NoNewFeatureInsertException(this.getName());
1264
                }
1265
                this.featureCount = null;
1266
                notifyChange(FeatureStoreNotification.BEFORE_INSERT, feature);
1267
                feature.validate(Feature.UPDATE);
1268
                provider.append(((DefaultEditableFeature) feature).getData());
1269
                hasStrongChanges = true;
1270
                hasInserts = true;
1271
                notifyChange(FeatureStoreNotification.AFTER_INSERT, feature);
1272
                break;
1273 40435 jjdelcerro
1274 42293 jjdelcerro
            case MODE_FULLEDIT:
1275
                if (feature.getSource() != null) {
1276
                    throw new NoNewFeatureInsertException(this.getName());
1277
                }
1278
                commands.insert(feature);
1279 40435 jjdelcerro
            }
1280
        } catch (Exception e) {
1281
            throw new StoreInsertFeatureException(e, this.getName());
1282
        }
1283
    }
1284 41818 fdiaz
1285 40435 jjdelcerro
    synchronized public void doInsert(EditableFeature feature)
1286 42293 jjdelcerro
        throws DataException {
1287 40435 jjdelcerro
        checkIsOwnFeature(feature);
1288 41818 fdiaz
1289 40435 jjdelcerro
        waitForIndexes();
1290
1291
        notifyChange(FeatureStoreNotification.BEFORE_INSERT, feature);
1292
        newVersionOfUpdate();
1293
        if ((lastChangedFeature == null)
1294 42293 jjdelcerro
            || (lastChangedFeature.getSource() != feature.getSource())) {
1295 40435 jjdelcerro
            lastChangedFeature = feature;
1296
            feature.validate(Feature.UPDATE);
1297
            lastChangedFeature = null;
1298
        }
1299
        //Update the featureManager and the spatialManager
1300
        ((DefaultEditableFeature) feature).setInserted(true);
1301
        DefaultFeature newFeature = (DefaultFeature) feature.getNotEditableCopy();
1302 41818 fdiaz
1303 42293 jjdelcerro
1304 40435 jjdelcerro
        featureManager.add(newFeature);
1305
        spatialManager.insertFeature(newFeature);
1306 41818 fdiaz
1307 40435 jjdelcerro
        hasStrongChanges = true;
1308
        hasInserts = true;
1309 41818 fdiaz
        notifyChange(FeatureStoreNotification.AFTER_INSERT, feature);
1310 40435 jjdelcerro
    }
1311 41818 fdiaz
1312 43215 jjdelcerro
    @Override
1313 40435 jjdelcerro
    public void update(EditableFeature feature)
1314 42293 jjdelcerro
    throws DataException {
1315 40435 jjdelcerro
        if ((feature).getSource() == null) {
1316
            insert(feature);
1317
            return;
1318
        }
1319
        commands.update(feature, feature.getSource());
1320
    }
1321
1322
    synchronized public void doUpdate(EditableFeature feature, Feature oldFeature)
1323 42293 jjdelcerro
        throws DataException {
1324 41818 fdiaz
        try {
1325 40435 jjdelcerro
            checkInEditingMode();
1326
            checkIsOwnFeature(feature);
1327
            notifyChange(FeatureStoreNotification.BEFORE_UPDATE, feature);
1328
            newVersionOfUpdate();
1329
            if ((lastChangedFeature == null)
1330 42293 jjdelcerro
                || (lastChangedFeature.getSource() != feature.getSource())) {
1331 40435 jjdelcerro
                lastChangedFeature = feature;
1332
                feature.validate(Feature.UPDATE);
1333
                lastChangedFeature = null;
1334
            }
1335 41818 fdiaz
1336 40435 jjdelcerro
            //Update the featureManager and the spatialManager
1337
            Feature newf = feature.getNotEditableCopy();
1338
            featureManager.update(newf, oldFeature);
1339
            spatialManager.updateFeature(newf, oldFeature);
1340 41818 fdiaz
1341 40435 jjdelcerro
            hasStrongChanges = true;
1342
            notifyChange(FeatureStoreNotification.AFTER_UPDATE, feature);
1343
        } catch (Exception e) {
1344
            throw new StoreUpdateFeatureException(e, this.getName());
1345
        }
1346
    }
1347
1348 43215 jjdelcerro
    @Override
1349 40435 jjdelcerro
    synchronized public void redo() throws RedoException {
1350
        Command redo = commands.getNextRedoCommand();
1351
        try {
1352
            checkInEditingMode();
1353
        } catch (NeedEditingModeException ex) {
1354
            throw new RedoException(redo, ex);
1355
        }
1356
        notifyChange(FeatureStoreNotification.BEFORE_REDO, redo);
1357
        newVersionOfUpdate();
1358
        commands.redo();
1359
        hasStrongChanges = true;
1360
        notifyChange(FeatureStoreNotification.AFTER_REDO, redo);
1361
    }
1362
1363 43215 jjdelcerro
    @Override
1364 40435 jjdelcerro
    synchronized public void undo() throws UndoException {
1365
        Command undo = commands.getNextUndoCommand();
1366
        try {
1367
            checkInEditingMode();
1368
        } catch (NeedEditingModeException ex) {
1369
            throw new UndoException(undo, ex);
1370
        }
1371
        notifyChange(FeatureStoreNotification.BEFORE_UNDO, undo);
1372
        newVersionOfUpdate();
1373
        commands.undo();
1374
        hasStrongChanges = true;
1375
        notifyChange(FeatureStoreNotification.AFTER_UNDO, undo);
1376
    }
1377
1378 43215 jjdelcerro
    @Override
1379 40435 jjdelcerro
    public List getRedoInfos() {
1380
        if (isEditing() && (commands != null)) {
1381
            return commands.getRedoInfos();
1382
        } else {
1383
            return null;
1384
        }
1385
    }
1386
1387 43215 jjdelcerro
    @Override
1388 40435 jjdelcerro
    public List getUndoInfos() {
1389
        if (isEditing() && (commands != null)) {
1390
            return commands.getUndoInfos();
1391
        } else {
1392
            return null;
1393
        }
1394
    }
1395
1396
    public synchronized FeatureCommandsStack getCommandsStack()
1397 42293 jjdelcerro
        throws DataException {
1398 40435 jjdelcerro
        checkInEditingMode();
1399
        return commands;
1400
    }
1401
1402 43215 jjdelcerro
    @Override
1403 40435 jjdelcerro
    synchronized public void cancelEditing() throws DataException {
1404 43642 jjdelcerro
        if( spatialManager!=null ) {
1405
            spatialManager.cancelModifies();
1406
        }
1407 40435 jjdelcerro
        try {
1408 43408 jjdelcerro
            switch (mode) {
1409
            case MODE_QUERY:
1410
                throw new NeedEditingModeException(this.getName());
1411 40435 jjdelcerro
1412 43408 jjdelcerro
            case MODE_APPEND:
1413
                notifyChange(FeatureStoreNotification.BEFORE_CANCELEDITING);
1414
                provider.abortAppend();
1415
                exitEditingMode();
1416 40435 jjdelcerro
                ((FeatureSelection) this.getSelection()).deselectAll();
1417 43408 jjdelcerro
                updateIndexes();
1418
                notifyChange(FeatureStoreNotification.AFTER_CANCELEDITING);
1419
1420
            case MODE_FULLEDIT:
1421
                boolean clearSelection = this.hasStrongChanges;
1422
                if (this.selection instanceof FeatureReferenceSelection) {
1423
                    clearSelection = this.hasInserts;
1424
                }
1425
                notifyChange(FeatureStoreNotification.BEFORE_CANCELEDITING);
1426
                exitEditingMode();
1427
                if (clearSelection) {
1428
                    ((FeatureSelection) this.getSelection()).deselectAll();
1429
                }
1430
                updateIndexes();
1431
                notifyChange(FeatureStoreNotification.AFTER_CANCELEDITING);
1432 40435 jjdelcerro
            }
1433
        } catch (Exception e) {
1434
            throw new StoreCancelEditingException(e, this.getName());
1435
        }
1436
    }
1437
1438 43215 jjdelcerro
    @Override
1439 40435 jjdelcerro
    synchronized public void finishEditing() throws DataException {
1440 43215 jjdelcerro
        LOG.debug("finish editing of mode: {}", mode);
1441 40435 jjdelcerro
        try {
1442 41818 fdiaz
1443 40435 jjdelcerro
            /*
1444
             * Selection needs to be cleared when editing stops
1445
             * to prevent conflicts with selection remaining from
1446
             * editing mode.
1447
             */
1448 42639 dmartinezizquierdo
//            ((FeatureSelection) this.getSelection()).deselectAll();
1449 43981 omartinez
            Map<String,List<FeatureAttributeDescriptor>> computedFields = this.getComputedFields();
1450 40435 jjdelcerro
            switch (mode) {
1451 42293 jjdelcerro
            case MODE_QUERY:
1452
                throw new NeedEditingModeException(this.getName());
1453 40435 jjdelcerro
1454 42293 jjdelcerro
            case MODE_APPEND:
1455 43377 jjdelcerro
                if( selection!=null ) {
1456
                    selection = null;
1457
                }
1458 42293 jjdelcerro
                notifyChange(FeatureStoreNotification.BEFORE_FINISHEDITING);
1459
                provider.endAppend();
1460
                exitEditingMode();
1461 43981 omartinez
                this.updateComputedFields(computedFields);
1462
                saveDALFile();
1463 42293 jjdelcerro
                updateIndexes();
1464
                notifyChange(FeatureStoreNotification.AFTER_FINISHEDITING);
1465
                break;
1466 40435 jjdelcerro
1467 42293 jjdelcerro
            case MODE_FULLEDIT:
1468
                if (hasStrongChanges && !this.allowWrite()) {
1469
                    throw new WriteNotAllowedException(getName());
1470
                }
1471 43377 jjdelcerro
                if(featureManager.isSelectionCompromised() && selection!=null ) {
1472
                    selection = null;
1473
                }
1474 42293 jjdelcerro
                notifyChange(FeatureStoreNotification.BEFORE_FINISHEDITING);
1475
                if (hasStrongChanges) {
1476
                    validateFeatures(Feature.FINISH_EDITING);
1477 41818 fdiaz
1478 42293 jjdelcerro
                    /*
1479
                     * This will throw a PerformEditingExceptionif the provider
1480
                     * does not accept the changes (for example, an invalid field name)
1481
                     */
1482
                    provider.performChanges(featureManager.getDeleted(),
1483
                        featureManager.getInserted(),
1484
                        featureManager.getUpdated(),
1485 43967 jjdelcerro
                        removeCalculatedAttributes(featureTypeManager.getFeatureTypesChanged()).iterator());
1486 43981 omartinez
1487 43954 jjdelcerro
                }
1488 43981 omartinez
                exitEditingMode();
1489
                this.updateComputedFields(computedFields);
1490 43954 jjdelcerro
                saveDALFile();
1491 42293 jjdelcerro
                updateIndexes();
1492
                notifyChange(FeatureStoreNotification.AFTER_FINISHEDITING);
1493
                break;
1494 40435 jjdelcerro
            }
1495 40597 jldominguez
        } catch (PerformEditingException pee) {
1496 41437 jjdelcerro
            throw new WriteException(provider.getSourceId().toString(), pee);
1497 40435 jjdelcerro
        } catch (Exception e) {
1498
            throw new FinishEditingException(e);
1499
        }
1500
    }
1501 43981 omartinez
    private Map<String,List<FeatureAttributeDescriptor>> getComputedFields() throws DataException {
1502
        Map<String,List<FeatureAttributeDescriptor>> r = new HashMap<>();
1503
1504
        List<FeatureType> theTypes = new ArrayList<>();
1505
        theTypes.addAll(this.getFeatureTypes());
1506
        theTypes.add(this.getDefaultFeatureType());
1507
        for( int n=0; n<theTypes.size(); n++ ) {
1508
            FeatureType type = theTypes.get(n);
1509
                for (FeatureAttributeDescriptor attrdesc : type) {
1510
                    FeatureAttributeEmulator emulator = attrdesc.getFeatureAttributeEmulator();
1511
                    if( emulator!= null) {
1512
                        List<FeatureAttributeDescriptor> l = r.get(type.getId());
1513
                        if (l==null) {
1514
                            l = new ArrayList<>();
1515
                            r.put(type.getId(), l);
1516
                        }
1517
                        l.add(attrdesc);
1518
                    }
1519
            }
1520
        }
1521
        return r;
1522
    }
1523
    private void updateComputedFields(Map<String,List<FeatureAttributeDescriptor>> computedFields) throws DataException {
1524
1525
        List<FeatureType> theTypes = new ArrayList<>();
1526
        theTypes.addAll(this.getFeatureTypes());
1527
        theTypes.add(this.getDefaultFeatureType());
1528
        for( int n=0; n<theTypes.size(); n++ ) {
1529
            DefaultFeatureType type = (DefaultFeatureType) theTypes.get(n);
1530
            List<FeatureAttributeDescriptor> x = computedFields.get(type.getId());
1531
            if(x!=null && !x.isEmpty()) {
1532
                for (FeatureAttributeDescriptor attrdesc : x) {
1533
                    if (type.get(attrdesc.getName())==null) {
1534
                        type.add(attrdesc);
1535
                    }
1536
                }
1537
            }
1538
        }
1539
1540
    }
1541 43967 jjdelcerro
    private List<FeatureStoreProvider.FeatureTypeChanged> removeCalculatedAttributes(List<FeatureStoreProvider.FeatureTypeChanged> ftypes) {
1542
        // FIXME: Falta por implementar
1543 43978 omartinez
//        for (FeatureStoreProvider.FeatureTypeChanged ftype : ftypes) {
1544
//            EditableFeatureType target = (EditableFeatureType) ftype.getTarget();
1545
//            for (FeatureAttributeDescriptor attributeDescriptor : ftype.getSource().getAttributeDescriptors()) {
1546
//                if (attributeDescriptor.isComputed()) {
1547
//                    target.remove(attributeDescriptor.getName());
1548
//                }
1549
//            }
1550
//        }
1551 43967 jjdelcerro
        return ftypes;
1552
    }
1553
1554 40435 jjdelcerro
1555 43954 jjdelcerro
    @SuppressWarnings("UseSpecificCatch")
1556
    private void saveDALFile() {
1557
        try {
1558
            DataServerExplorer explorer = this.getExplorer();
1559 43956 jjdelcerro
            if( explorer == null ) {
1560
                return;
1561
            }
1562 43954 jjdelcerro
            File f = explorer.getResourcePath(this, "dal");
1563
            if( f == null ) {
1564
                return;
1565
            }
1566
            DALFile dalFile = DALFile.getDALFile();
1567
            dalFile.setStore(this);
1568
            if( !dalFile.isEmpty() ) {
1569
                dalFile.write(f);
1570
            }
1571
        } catch (Exception ex) {
1572
            LOG.warn("Can't save DAL File", ex);
1573
        }
1574
    }
1575
1576
    @SuppressWarnings("UseSpecificCatch")
1577
    private void loadDALFile() {
1578
        try {
1579
            DataServerExplorer explorer = this.getExplorer();
1580 43956 jjdelcerro
            if( explorer == null ) {
1581
                return;
1582
            }
1583 43954 jjdelcerro
            File f = explorer.getResourcePath(this, "dal");
1584 43958 jjdelcerro
            if( f == null || !f.exists() ) {
1585 43954 jjdelcerro
                return;
1586
            }
1587
            DALFile dalFile = DALFile.getDALFile(f);
1588
            if( !dalFile.isEmpty() ) {
1589
                dalFile.updateStore(this);
1590
            }
1591
        } catch (Exception ex) {
1592
            LOG.warn("Can't load DAL File", ex);
1593
        }
1594
    }
1595
1596 40435 jjdelcerro
    /**
1597 42293 jjdelcerro
     * Save changes in the provider without leaving the edit mode.
1598
     * Do not call observers to communicate a change of ediding mode.
1599
     * The operation's history is eliminated to prevent inconsistencies
1600
     * in the data.
1601 40435 jjdelcerro
     *
1602
     * @throws DataException
1603
     */
1604 43215 jjdelcerro
    @Override
1605 40435 jjdelcerro
    synchronized public void commitChanges() throws DataException {
1606 43215 jjdelcerro
      LOG.debug("commitChanges of mode: {}", mode);
1607 42293 jjdelcerro
      if( !canCommitChanges() ) {
1608
              throw new WriteNotAllowedException(getName());
1609
      }
1610
      try {
1611
        switch (mode) {
1612
        case MODE_QUERY:
1613
          throw new NeedEditingModeException(this.getName());
1614 40435 jjdelcerro
1615 42293 jjdelcerro
        case MODE_APPEND:
1616
          this.provider.endAppend();
1617
          exitEditingMode();
1618
          invalidateIndexes();
1619
          this.provider.beginAppend();
1620
          hasInserts = false;
1621
          break;
1622 40435 jjdelcerro
1623 42293 jjdelcerro
        case MODE_FULLEDIT:
1624
          if (hasStrongChanges && !this.allowWrite()) {
1625
            throw new WriteNotAllowedException(getName());
1626
          }
1627
          if (hasStrongChanges) {
1628
            validateFeatures(Feature.FINISH_EDITING);
1629
            provider.performChanges(featureManager.getDeleted(),
1630
              featureManager.getInserted(),
1631
              featureManager.getUpdated(),
1632 43967 jjdelcerro
              removeCalculatedAttributes(featureTypeManager.getFeatureTypesChanged()).iterator());
1633 42293 jjdelcerro
          }
1634
          invalidateIndexes();
1635 43840 jjdelcerro
          featureManager = new FeatureManager();
1636
          featureTypeManager = new FeatureTypeManager(this);
1637
          spatialManager = new SpatialManager(this, provider.getEnvelope());
1638 40435 jjdelcerro
1639 42293 jjdelcerro
          commands =
1640
            new DefaultFeatureCommandsStack(this, featureManager,
1641
              spatialManager, featureTypeManager);
1642
          featureCount = null;
1643
          hasStrongChanges = false;
1644
          hasInserts = false;
1645
          break;
1646 40435 jjdelcerro
        }
1647 42293 jjdelcerro
      } catch (Exception e) {
1648
        throw new FinishEditingException(e);
1649
      }
1650 40435 jjdelcerro
    }
1651
1652 43215 jjdelcerro
    @Override
1653 40435 jjdelcerro
    synchronized public boolean canCommitChanges() throws DataException {
1654 42293 jjdelcerro
        if ( !this.allowWrite()) {
1655
                return false;
1656 40435 jjdelcerro
        }
1657 42293 jjdelcerro
            switch (mode) {
1658
            default:
1659
        case MODE_QUERY:
1660
                return false;
1661 41818 fdiaz
1662 42293 jjdelcerro
        case MODE_APPEND:
1663
                return true;
1664 41818 fdiaz
1665 42293 jjdelcerro
        case MODE_FULLEDIT:
1666
            List types = this.getFeatureTypes();
1667
            for( int i=0; i<types.size(); i++ ) {
1668
                    Object type = types.get(i);
1669
                    if( type instanceof DefaultEditableFeatureType ) {
1670
                            if( ((DefaultEditableFeatureType)type).hasStrongChanges() ) {
1671
                                    return false;
1672
                            }
1673
                    }
1674
            }
1675
            return true;
1676
            }
1677 40435 jjdelcerro
    }
1678 41818 fdiaz
1679 43215 jjdelcerro
    @Override
1680 40435 jjdelcerro
    public void beginEditingGroup(String description)
1681 42293 jjdelcerro
        throws NeedEditingModeException {
1682 40435 jjdelcerro
        checkInEditingMode();
1683
        commands.startComplex(description);
1684
    }
1685
1686 43215 jjdelcerro
    @Override
1687 40435 jjdelcerro
    public void endEditingGroup() throws NeedEditingModeException {
1688
        checkInEditingMode();
1689
        commands.endComplex();
1690
    }
1691
1692 43215 jjdelcerro
    @Override
1693 40435 jjdelcerro
    public boolean isAppendModeSupported() {
1694
        return this.provider.supportsAppendMode();
1695
    }
1696
1697 43215 jjdelcerro
    @Override
1698 40435 jjdelcerro
    public void export(DataServerExplorer explorer, String provider,
1699 42293 jjdelcerro
        NewFeatureStoreParameters params) throws DataException {
1700 40435 jjdelcerro
1701
        if (this.getFeatureTypes().size() != 1) {
1702
            throw new NotYetImplemented(
1703 42293 jjdelcerro
                "export whith more than one type not yet implemented");
1704 40435 jjdelcerro
        }
1705
        FeatureSelection featureSelection = (FeatureSelection) getSelection();
1706
        FeatureStore target = null;
1707
        FeatureSet features = null;
1708
        DisposableIterator iterator = null;
1709
        try {
1710
            FeatureType type = this.getDefaultFeatureType();
1711
            if ((params.getDefaultFeatureType() == null)
1712 42293 jjdelcerro
                || (params.getDefaultFeatureType().size() == 0)) {
1713 40435 jjdelcerro
                params.setDefaultFeatureType(type.getEditable());
1714
1715
            }
1716
            explorer.add(provider, params, true);
1717
1718
            DataManager manager = DALLocator.getDataManager();
1719
            target = (FeatureStore) manager.openStore(provider, params);
1720
            FeatureType targetType = target.getDefaultFeatureType();
1721
1722
            target.edit(MODE_APPEND);
1723 43840 jjdelcerro
            FeatureAttributeDescriptor[] pkattrs = type.getPrimaryKey();
1724 40435 jjdelcerro
            if (featureSelection.getSize() > 0) {
1725
                features = this.getFeatureSelection();
1726
            } else {
1727 43840 jjdelcerro
                if ((pkattrs != null) && (pkattrs.length > 0)) {
1728 40435 jjdelcerro
                    FeatureQuery query = createFeatureQuery();
1729 43840 jjdelcerro
                    for (FeatureAttributeDescriptor pkattr : pkattrs) {
1730
                        query.getOrder().add(pkattr.getName(), true);
1731 40435 jjdelcerro
                    }
1732
                    features = this.getFeatureSet(query);
1733
                } else {
1734
                    features = this.getFeatureSet();
1735
                }
1736
            }
1737
            iterator = features.fastIterator();
1738
            while (iterator.hasNext()) {
1739
                DefaultFeature feature = (DefaultFeature) iterator.next();
1740
                target.insert(target.createNewFeature(targetType, feature));
1741
            }
1742
            target.finishEditing();
1743
            target.dispose();
1744
        } catch (Exception e) {
1745
            throw new DataExportException(e, params.toString());
1746
        } finally {
1747
            dispose(iterator);
1748
            dispose(features);
1749
            dispose(target);
1750
        }
1751
    }
1752
1753
    //
1754
    // ====================================================================
1755
    // Obtencion de datos
1756
    // getDataCollection, getFeatureCollection
1757
    //
1758 42293 jjdelcerro
1759 43215 jjdelcerro
    @Override
1760 40435 jjdelcerro
    public DataSet getDataSet() throws DataException {
1761
        checkNotInAppendMode();
1762 42293 jjdelcerro
        FeatureQuery query =
1763
            new DefaultFeatureQuery(this.getDefaultFeatureType());
1764 40435 jjdelcerro
        return new DefaultFeatureSet(this, query);
1765
    }
1766
1767 43215 jjdelcerro
    @Override
1768 40435 jjdelcerro
    public DataSet getDataSet(DataQuery dataQuery) throws DataException {
1769
        checkNotInAppendMode();
1770
        return new DefaultFeatureSet(this, (FeatureQuery) dataQuery);
1771
    }
1772
1773 43215 jjdelcerro
    @Override
1774 40435 jjdelcerro
    public void getDataSet(Observer observer) throws DataException {
1775
        checkNotInAppendMode();
1776
        this.getFeatureSet(null, observer);
1777
    }
1778
1779 43215 jjdelcerro
    @Override
1780 40435 jjdelcerro
    public void getDataSet(DataQuery dataQuery, Observer observer)
1781 42293 jjdelcerro
        throws DataException {
1782 40435 jjdelcerro
        checkNotInAppendMode();
1783
        this.getFeatureSet((FeatureQuery) dataQuery, observer);
1784
    }
1785
1786 42799 jjdelcerro
    @Override
1787 40435 jjdelcerro
    public FeatureSet getFeatureSet() throws DataException {
1788 42799 jjdelcerro
        return this.getFeatureSet((FeatureQuery)null);
1789 40435 jjdelcerro
    }
1790
1791 42799 jjdelcerro
    @Override
1792 40435 jjdelcerro
    public FeatureSet getFeatureSet(FeatureQuery featureQuery)
1793 42293 jjdelcerro
        throws DataException {
1794 40435 jjdelcerro
        checkNotInAppendMode();
1795 42799 jjdelcerro
        if( featureQuery==null ) {
1796
            featureQuery = new DefaultFeatureQuery(this.getDefaultFeatureType());
1797
        }
1798 40435 jjdelcerro
        return new DefaultFeatureSet(this, featureQuery);
1799
    }
1800
1801 42925 jjdelcerro
    @Override
1802 43533 jjdelcerro
    public FeatureSet getFeatureSet(String filter) throws DataException {
1803
        return this.getFeatureSet(filter, null, true);
1804
    }
1805
1806
    @Override
1807
    public FeatureSet getFeatureSet(String filter, String sortBy) throws DataException {
1808
        return this.getFeatureSet(filter, sortBy, true);
1809
    }
1810
1811
    @Override
1812 44023 jjdelcerro
    public FeatureSet getFeatureSet(Expression filter) throws DataException {
1813
        return this.getFeatureSet(filter, null, true);
1814
    }
1815
1816
    @Override
1817
    public FeatureSet getFeatureSet(Expression filter, String sortBy) throws DataException {
1818
        return this.getFeatureSet(filter, sortBy, true);
1819
    }
1820
1821
    @Override
1822
    public FeatureSet getFeatureSet(Expression filter, String sortBy, boolean asc) throws DataException {
1823
        FeatureQuery query = this.createFeatureQuery();
1824
        if( filter!=null ) {
1825
            query.setFilter(filter);
1826
        }
1827
        if( !StringUtils.isEmpty(sortBy) ) {
1828
            query.getOrder().add(sortBy, asc);
1829
        }
1830 44036 jjdelcerro
        query.retrievesAllAttributes();
1831 44023 jjdelcerro
        return this.getFeatureSet(query);
1832
    }
1833
1834
    @Override
1835 43533 jjdelcerro
    public FeatureSet getFeatureSet(String filter, String sortBy, boolean asc) throws DataException {
1836
        FeatureQuery query = this.createFeatureQuery();
1837
        if( !StringUtils.isEmpty(filter) ) {
1838
            query.setFilter(filter);
1839
        }
1840
        if( !StringUtils.isEmpty(sortBy) ) {
1841
            query.getOrder().add(sortBy, asc);
1842
        }
1843
        return this.getFeatureSet(query);
1844
    }
1845 43628 jjdelcerro
1846
    @Override
1847
    public List<Feature> getFeatures(String filter)  {
1848
        return this.getFeatures(filter, null, true);
1849
    }
1850 43533 jjdelcerro
1851
    @Override
1852 43628 jjdelcerro
    public List<Feature> getFeatures(String filter, String sortBy)  {
1853
        return this.getFeatures(filter, sortBy, true);
1854
    }
1855
1856
    @Override
1857
    public List<Feature> getFeatures(String filter, String sortBy, boolean asc)  {
1858
        FeatureQuery query = this.createFeatureQuery();
1859
        if( !StringUtils.isEmpty(filter) ) {
1860
            query.setFilter(filter);
1861
        }
1862
        if( !StringUtils.isEmpty(sortBy) ) {
1863
            query.getOrder().add(sortBy, asc);
1864
        }
1865
        return this.getFeatures(query, 100);
1866
    }
1867
1868
    @Override
1869 44023 jjdelcerro
    public List<Feature> getFeatures(Expression filter)  {
1870
        return this.getFeatures(filter, null, true);
1871
    }
1872
1873
    @Override
1874
    public List<Feature> getFeatures(Expression filter, String sortBy)  {
1875
        return this.getFeatures(filter, sortBy, true);
1876
    }
1877
1878
    @Override
1879
    public List<Feature> getFeatures(Expression filter, String sortBy, boolean asc)  {
1880
        FeatureQuery query = this.createFeatureQuery();
1881
        if( filter!=null ) {
1882
            query.setFilter(filter);
1883
        }
1884
        if( !StringUtils.isEmpty(sortBy) ) {
1885
            query.getOrder().add(sortBy, asc);
1886
        }
1887
        return this.getFeatures(query, 100);
1888
    }
1889
1890
    @Override
1891 43550 jjdelcerro
    public List<Feature> getFeatures(FeatureQuery query)  {
1892
        return this.getFeatures(query, 100);
1893
    }
1894
1895
    @Override
1896 42925 jjdelcerro
    public List<Feature> getFeatures(FeatureQuery query, int pageSize)  {
1897
        try {
1898
            FeaturePagingHelper pager = this.dataManager.createFeaturePagingHelper(this, query, pageSize);
1899
            return pager.asList();
1900
        } catch (BaseException ex) {
1901
            throw new RuntimeException("Can't create the list of features.", ex);
1902
        }
1903
    }
1904 43020 jjdelcerro
1905
    @Override
1906
    public List<Feature> getFeatures() {
1907
        return this.getFeatures(null, 500);
1908
    }
1909 43152 fdiaz
1910 43215 jjdelcerro
    @Override
1911 43628 jjdelcerro
    public Feature findFirst(String filter) throws DataException {
1912
        return this.findFirst(filter, null, true);
1913
    }
1914
1915
    @Override
1916
    public Feature findFirst(String filter, String sortBy) throws DataException {
1917
        return this.findFirst(filter, sortBy, true);
1918
    }
1919
1920
    @Override
1921
    public Feature findFirst(String filter, String sortBy, boolean asc) throws DataException {
1922
        FeatureSet set = this.getFeatureSet(filter, sortBy, asc);
1923
        if( set==null || set.isEmpty() ) {
1924
            return null;
1925
        }
1926
        DisposableIterator it = set.iterator();
1927
        Feature f = (Feature) it.next();
1928
        it.dispose();
1929
        return f;
1930
    }
1931
1932
    @Override
1933 44023 jjdelcerro
    public Feature findFirst(Expression filter) throws DataException {
1934
        return this.findFirst(filter, null, true);
1935
    }
1936
1937
    @Override
1938
    public Feature findFirst(Expression filter, String sortBy) throws DataException {
1939
        return this.findFirst(filter, sortBy, true);
1940
    }
1941
1942
    @Override
1943
    public Feature findFirst(Expression filter, String sortBy, boolean asc) throws DataException {
1944
        FeatureSet set = this.getFeatureSet(filter, sortBy, asc);
1945
        if( set==null || set.isEmpty() ) {
1946
            return null;
1947
        }
1948
        DisposableIterator it = set.iterator();
1949
        Feature f = (Feature) it.next();
1950
        it.dispose();
1951
        return f;
1952
    }
1953
1954
    @Override
1955 40435 jjdelcerro
    public void accept(Visitor visitor) throws BaseException {
1956
        FeatureSet set = getFeatureSet();
1957
        try {
1958
            set.accept(visitor);
1959
        } finally {
1960
            set.dispose();
1961
        }
1962
    }
1963
1964 43215 jjdelcerro
    @Override
1965 40435 jjdelcerro
    public void accept(Visitor visitor, DataQuery dataQuery)
1966 42293 jjdelcerro
        throws BaseException {
1967 40435 jjdelcerro
        FeatureSet set = getFeatureSet((FeatureQuery) dataQuery);
1968
        try {
1969
            set.accept(visitor);
1970
        } finally {
1971
            set.dispose();
1972
        }
1973
    }
1974
1975
    public FeatureType getFeatureType(FeatureQuery featureQuery)
1976 42293 jjdelcerro
        throws DataException {
1977
        DefaultFeatureType fType =
1978
            (DefaultFeatureType) this.getFeatureType(featureQuery
1979
                .getFeatureTypeId());
1980 43998 jjdelcerro
        if( featureQuery.hasAttributeNames() ||
1981
            featureQuery.hasConstantsAttributeNames() ||
1982
            fType.hasRequiredFields()
1983
            ) {
1984 42293 jjdelcerro
            return fType.getSubtype(featureQuery.getAttributeNames(), featureQuery.getConstantsAttributeNames() );
1985 40435 jjdelcerro
        }
1986
        return fType;
1987
    }
1988
1989 43215 jjdelcerro
    @Override
1990 40435 jjdelcerro
    public void getFeatureSet(Observer observer) throws DataException {
1991
        checkNotInAppendMode();
1992
        this.getFeatureSet(null, observer);
1993
    }
1994
1995 43215 jjdelcerro
    @Override
1996 40435 jjdelcerro
    public void getFeatureSet(FeatureQuery query, Observer observer)
1997 42293 jjdelcerro
        throws DataException {
1998 40435 jjdelcerro
        class LoadInBackGround implements Runnable {
1999
2000 43215 jjdelcerro
            private final FeatureStore store;
2001
            private final FeatureQuery query;
2002
            private final Observer observer;
2003 40435 jjdelcerro
2004
            public LoadInBackGround(FeatureStore store, FeatureQuery query,
2005 42293 jjdelcerro
                Observer observer) {
2006 40435 jjdelcerro
                this.store = store;
2007
                this.query = query;
2008
                this.observer = observer;
2009
            }
2010
2011
            void notify(FeatureStoreNotification theNotification) {
2012
                observer.update(store, theNotification);
2013
            }
2014
2015 43215 jjdelcerro
            @Override
2016 40435 jjdelcerro
            public void run() {
2017
                FeatureSet set = null;
2018
                try {
2019
                    set = store.getFeatureSet(query);
2020
                    notify(new DefaultFeatureStoreNotification(store,
2021 42293 jjdelcerro
                        FeatureStoreNotification.LOAD_FINISHED, set));
2022 40435 jjdelcerro
                } catch (Exception e) {
2023
                    notify(new DefaultFeatureStoreNotification(store,
2024 42293 jjdelcerro
                        FeatureStoreNotification.LOAD_FINISHED, e));
2025 40435 jjdelcerro
                } finally {
2026
                    dispose(set);
2027
                }
2028
            }
2029
        }
2030
2031
        checkNotInAppendMode();
2032
        if (query == null) {
2033
            query = new DefaultFeatureQuery(this.getDefaultFeatureType());
2034
        }
2035
        LoadInBackGround task = new LoadInBackGround(this, query, observer);
2036
        Thread thread = new Thread(task, "Load Feature Set in background");
2037
        thread.start();
2038
    }
2039
2040 43215 jjdelcerro
    @Override
2041 40435 jjdelcerro
    public Feature getFeatureByReference(FeatureReference reference)
2042 42293 jjdelcerro
        throws DataException {
2043 40435 jjdelcerro
        checkNotInAppendMode();
2044
        DefaultFeatureReference ref = (DefaultFeatureReference) reference;
2045
        FeatureType featureType;
2046
        if (ref.getFeatureTypeId() == null) {
2047
            featureType = this.getDefaultFeatureType();
2048
        } else {
2049
            featureType = this.getFeatureType(ref.getFeatureTypeId());
2050
        }
2051
        return this.getFeatureByReference(reference, featureType);
2052
    }
2053
2054 43215 jjdelcerro
    @Override
2055 40435 jjdelcerro
    public Feature getFeatureByReference(FeatureReference reference,
2056 42293 jjdelcerro
        FeatureType featureType) throws DataException {
2057 40435 jjdelcerro
        checkNotInAppendMode();
2058
        featureType = fixFeatureType((DefaultFeatureType) featureType);
2059
        if (this.mode == MODE_FULLEDIT) {
2060
            Feature f = featureManager.get(reference, this, featureType);
2061
            if (f != null) {
2062
                return f;
2063
            }
2064
        }
2065 41818 fdiaz
2066 42092 fdiaz
        FeatureType sourceFeatureType = featureType;
2067
        if (!this.transforms.isEmpty()) {
2068
            sourceFeatureType = this.transforms.getSourceFeatureTypeFrom(featureType);
2069
        }
2070
        // TODO comprobar que el id es de este store
2071 41818 fdiaz
2072 42293 jjdelcerro
        DefaultFeature feature =
2073
            new DefaultFeature(this,
2074
                this.provider.getFeatureProviderByReference(
2075
                    (FeatureReferenceProviderServices) reference, sourceFeatureType));
2076 40435 jjdelcerro
2077
        if (!this.transforms.isEmpty()) {
2078
            return this.transforms.applyTransform(feature, featureType);
2079
        }
2080
        return feature;
2081
    }
2082
2083
    //
2084
    // ====================================================================
2085
    // Gestion de features
2086
    //
2087 42293 jjdelcerro
2088 40435 jjdelcerro
    private FeatureType fixFeatureType(DefaultFeatureType type)
2089 42293 jjdelcerro
        throws DataException {
2090 40435 jjdelcerro
        FeatureType original = this.getDefaultFeatureType();
2091
2092
        if ((type == null) || type.equals(original)) {
2093
            return original;
2094
        } else {
2095
            if (!type.isSubtypeOf(original)) {
2096
                Iterator iter = this.getFeatureTypes().iterator();
2097
                FeatureType tmpType;
2098
                boolean found = false;
2099
                while (iter.hasNext()) {
2100
                    tmpType = (FeatureType) iter.next();
2101
                    if (type.equals(tmpType)) {
2102
                        return type;
2103
2104 42293 jjdelcerro
                    } else
2105
                        if (type.isSubtypeOf(tmpType)) {
2106
                            found = true;
2107
                            original = tmpType;
2108
                            break;
2109
                        }
2110 40435 jjdelcerro
2111
                }
2112
                if (!found) {
2113
                    throw new IllegalFeatureTypeException(getName());
2114
                }
2115
            }
2116
        }
2117
2118
        // Checks that type has all fields of pk
2119
        // else add the missing attributes at the end.
2120
        if (!original.hasOID()) {
2121
            // Gets original pk attributes
2122 42293 jjdelcerro
            DefaultEditableFeatureType edOriginal =
2123
                (DefaultEditableFeatureType) original.getEditable();
2124 40435 jjdelcerro
            FeatureAttributeDescriptor orgAttr;
2125
            Iterator edOriginalIter = edOriginal.iterator();
2126
            while (edOriginalIter.hasNext()) {
2127
                orgAttr = (FeatureAttributeDescriptor) edOriginalIter.next();
2128
                if (!orgAttr.isPrimaryKey()) {
2129
                    edOriginalIter.remove();
2130
                }
2131
            }
2132
2133
            // Checks if all pk attributes are in type
2134
            Iterator typeIterator;
2135
            edOriginalIter = edOriginal.iterator();
2136
            FeatureAttributeDescriptor attr;
2137
            while (edOriginalIter.hasNext()) {
2138
                orgAttr = (FeatureAttributeDescriptor) edOriginalIter.next();
2139
                typeIterator = type.iterator();
2140
                while (typeIterator.hasNext()) {
2141
                    attr = (FeatureAttributeDescriptor) typeIterator.next();
2142
                    if (attr.getName().equals(orgAttr.getName())) {
2143
                        edOriginalIter.remove();
2144
                        break;
2145
                    }
2146
                }
2147
            }
2148
2149
            // add missing pk attributes if any
2150
            if (edOriginal.size() > 0) {
2151
                boolean isEditable = type instanceof DefaultEditableFeatureType;
2152 42293 jjdelcerro
                DefaultEditableFeatureType edType =
2153
                    (DefaultEditableFeatureType) original.getEditable();
2154 40435 jjdelcerro
                edType.clear();
2155
                edType.addAll(type);
2156
                edType.addAll(edOriginal);
2157
                if (!isEditable) {
2158
                    type = (DefaultFeatureType) edType.getNotEditableCopy();
2159
                }
2160
            }
2161
2162
        }
2163
2164
        return type;
2165
    }
2166
2167 43215 jjdelcerro
    @Override
2168 40435 jjdelcerro
    public void validateFeatures(int mode) throws DataException {
2169
        FeatureSet collection = null;
2170
        DisposableIterator iter = null;
2171
        try {
2172 43642 jjdelcerro
            FeatureRules rules = this.getDefaultFeatureType().getRules();
2173
            if( rules==null || rules.isEmpty() ) {
2174
                return;
2175
            }
2176 40435 jjdelcerro
            checkNotInAppendMode();
2177
            collection = this.getFeatureSet();
2178
            iter = collection.fastIterator();
2179
            long previousVersionOfUpdate = currentVersionOfUpdate();
2180
            while (iter.hasNext()) {
2181
                ((DefaultFeature) iter.next()).validate(mode);
2182
                if (previousVersionOfUpdate != currentVersionOfUpdate()) {
2183
                    throw new ConcurrentDataModificationException(getName());
2184
                }
2185
            }
2186
        } catch (Exception e) {
2187
            throw new ValidateFeaturesException(e, getName());
2188
        } finally {
2189 43642 jjdelcerro
            DisposeUtils.disposeQuietly(iter);
2190
            DisposeUtils.disposeQuietly(collection);
2191 40435 jjdelcerro
        }
2192
    }
2193
2194 43215 jjdelcerro
    @Override
2195 40435 jjdelcerro
    public FeatureType getDefaultFeatureType() throws DataException {
2196
        try {
2197 41818 fdiaz
2198 40435 jjdelcerro
            if (isEditing()) {
2199 42293 jjdelcerro
                FeatureType auxFeatureType =
2200
                    featureTypeManager.getType(defaultFeatureType.getId());
2201 40435 jjdelcerro
                if (auxFeatureType != null) {
2202
                    return avoidEditable(auxFeatureType);
2203
                }
2204
            }
2205
            FeatureType type = this.transforms.getDefaultFeatureType();
2206 43998 jjdelcerro
                if (type != null) {
2207 40435 jjdelcerro
                return avoidEditable(type);
2208 43998 jjdelcerro
                }
2209 41818 fdiaz
2210 40435 jjdelcerro
            return avoidEditable(defaultFeatureType);
2211 41818 fdiaz
2212 40435 jjdelcerro
        } catch (Exception e) {
2213
            throw new GetFeatureTypeException(e, getName());
2214
        }
2215
    }
2216 41818 fdiaz
2217 40435 jjdelcerro
    private FeatureType avoidEditable(FeatureType ft) {
2218
        if (ft instanceof EditableFeatureType) {
2219
            return ((EditableFeatureType) ft).getNotEditableCopy();
2220
        } else {
2221
            return ft;
2222
        }
2223
    }
2224
2225 43215 jjdelcerro
    @Override
2226 40435 jjdelcerro
    public FeatureType getFeatureType(String featureTypeId)
2227 42293 jjdelcerro
        throws DataException {
2228 40435 jjdelcerro
        if (featureTypeId == null) {
2229
            return this.getDefaultFeatureType();
2230
        }
2231
        try {
2232
            if (isEditing()) {
2233 42293 jjdelcerro
                FeatureType auxFeatureType =
2234
                    featureTypeManager.getType(featureTypeId);
2235 40435 jjdelcerro
                if (auxFeatureType != null) {
2236
                    return auxFeatureType;
2237
                }
2238
            }
2239
            FeatureType type = this.transforms.getFeatureType(featureTypeId);
2240
            if (type != null) {
2241
                return type;
2242
            }
2243
            Iterator iter = this.featureTypes.iterator();
2244
            while (iter.hasNext()) {
2245
                type = (FeatureType) iter.next();
2246
                if (type.getId().equals(featureTypeId)) {
2247
                    return type;
2248
                }
2249
            }
2250
            return null;
2251
        } catch (Exception e) {
2252
            throw new GetFeatureTypeException(e, getName());
2253
        }
2254
    }
2255
2256
    public FeatureType getProviderDefaultFeatureType() {
2257
        return defaultFeatureType;
2258
    }
2259
2260 43215 jjdelcerro
    @Override
2261 40435 jjdelcerro
    public List getFeatureTypes() throws DataException {
2262
        try {
2263
            List types;
2264
            if (isEditing()) {
2265
                types = new ArrayList();
2266
                Iterator it = featureTypes.iterator();
2267
                while (it.hasNext()) {
2268
                    FeatureType type = (FeatureType) it.next();
2269 42293 jjdelcerro
                    FeatureType typeaux =
2270
                        featureTypeManager.getType(type.getId());
2271 40435 jjdelcerro
                    if (typeaux != null) {
2272
                        types.add(typeaux);
2273
                    } else {
2274
                        types.add(type);
2275
                    }
2276
                }
2277
                it = featureTypeManager.newsIterator();
2278
                while (it.hasNext()) {
2279
                    FeatureType type = (FeatureType) it.next();
2280
                    types.add(type);
2281
                }
2282
            } else {
2283
                types = this.transforms.getFeatureTypes();
2284
                if (types == null) {
2285
                    types = featureTypes;
2286
                }
2287
            }
2288
            return Collections.unmodifiableList(types);
2289
        } catch (Exception e) {
2290
            throw new GetFeatureTypeException(e, getName());
2291
        }
2292
    }
2293
2294
    public List getProviderFeatureTypes() throws DataException {
2295
        return Collections.unmodifiableList(this.featureTypes);
2296
    }
2297
2298 43215 jjdelcerro
    @Override
2299 40435 jjdelcerro
    public Feature createFeature(FeatureProvider data) throws DataException {
2300
        DefaultFeature feature = new DefaultFeature(this, data);
2301
        return feature;
2302
    }
2303
2304
    public Feature createFeature(FeatureProvider data, FeatureType type)
2305 42293 jjdelcerro
        throws DataException {
2306 40435 jjdelcerro
        // FIXME: falta por implementar
2307
        // Comprobar si es un subtipo del feature de data
2308
        // y construir un feature usando el subtipo.
2309
        // Probablemente requiera generar una copia del data.
2310
        throw new NotYetImplemented();
2311
    }
2312
2313 43215 jjdelcerro
    @Override
2314 40435 jjdelcerro
    public EditableFeature createNewFeature(FeatureType type,
2315 42293 jjdelcerro
        Feature defaultValues) throws DataException {
2316 40435 jjdelcerro
        try {
2317
            FeatureProvider data = createNewFeatureProvider(type);
2318 42293 jjdelcerro
            DefaultEditableFeature feature =
2319
                new DefaultEditableFeature(this, data);
2320 40435 jjdelcerro
            feature.initializeValues(defaultValues);
2321
            data.setNew(true);
2322 41818 fdiaz
2323 40435 jjdelcerro
            return feature;
2324
        } catch (Exception e) {
2325
            throw new CreateFeatureException(e, getName());
2326
        }
2327
    }
2328
2329
    private FeatureProvider createNewFeatureProvider(FeatureType type)
2330 42293 jjdelcerro
        throws DataException {
2331 40435 jjdelcerro
        type = this.fixFeatureType((DefaultFeatureType) type);
2332
        FeatureProvider data = this.provider.createFeatureProvider(type);
2333
        data.setNew(true);
2334
        if (type.hasOID() && (data.getOID() == null)) {
2335
            data.setOID(this.provider.createNewOID());
2336
        } else {
2337
            data.setOID(this.getTemporalOID());
2338
        }
2339
        return data;
2340
2341
    }
2342
2343 43215 jjdelcerro
    @Override
2344 40435 jjdelcerro
    public EditableFeature createNewFeature(FeatureType type,
2345 42293 jjdelcerro
        boolean defaultValues) throws DataException {
2346 40435 jjdelcerro
        try {
2347
            FeatureProvider data = createNewFeatureProvider(type);
2348 42293 jjdelcerro
            DefaultEditableFeature feature =
2349
                new DefaultEditableFeature(this, data);
2350 40435 jjdelcerro
            if (defaultValues) {
2351
                feature.initializeValues();
2352
            }
2353
            return feature;
2354
        } catch (Exception e) {
2355
            throw new CreateFeatureException(e, getName());
2356
        }
2357
    }
2358
2359 43215 jjdelcerro
    @Override
2360 40435 jjdelcerro
    public EditableFeature createNewFeature(boolean defaultValues)
2361 42293 jjdelcerro
        throws DataException {
2362 40435 jjdelcerro
        return this.createNewFeature(this.getDefaultFeatureType(),
2363 42293 jjdelcerro
            defaultValues);
2364 40435 jjdelcerro
    }
2365
2366 43215 jjdelcerro
    @Override
2367 40435 jjdelcerro
    public EditableFeature createNewFeature() throws DataException {
2368
        return this.createNewFeature(this.getDefaultFeatureType(), true);
2369
    }
2370
2371 43215 jjdelcerro
    @Override
2372 42293 jjdelcerro
    public EditableFeature createNewFeature(Feature defaultValues) throws DataException {
2373
        FeatureType ft = this.getDefaultFeatureType();
2374
        EditableFeature f = this.createNewFeature(ft, false);
2375 43215 jjdelcerro
                for( FeatureAttributeDescriptor desc : ft ) {
2376
                        try {
2377
                                f.set(desc.getName(), defaultValues.get(desc.getName()));
2378
                        } catch(Throwable th) {
2379
                                // Ignore
2380
                        }
2381
                }
2382 42293 jjdelcerro
        return f;
2383
    }
2384
2385 43215 jjdelcerro
    @Override
2386 40435 jjdelcerro
    public EditableFeatureType createFeatureType() {
2387 43739 jjdelcerro
        EditableFeatureType ftype = new DefaultEditableFeatureType(this);
2388 40435 jjdelcerro
        return ftype;
2389
    }
2390
2391 43215 jjdelcerro
    @Override
2392 40435 jjdelcerro
    public EditableFeatureType createFeatureType(String id) {
2393 43739 jjdelcerro
        DefaultEditableFeatureType ftype = new DefaultEditableFeatureType(this, id);
2394 40435 jjdelcerro
        return ftype;
2395
    }
2396
2397
    //
2398
    // ====================================================================
2399
    // Index related methods
2400
    //
2401 42293 jjdelcerro
2402 43215 jjdelcerro
    @Override
2403 40435 jjdelcerro
    public FeatureIndexes getIndexes() {
2404
        return this.indexes;
2405
    }
2406
2407 43215 jjdelcerro
    @Override
2408 40435 jjdelcerro
    public FeatureIndex createIndex(FeatureType featureType,
2409 42293 jjdelcerro
        String attributeName, String indexName) throws DataException {
2410 40435 jjdelcerro
        return createIndex(null, featureType, attributeName, indexName);
2411
    }
2412
2413 43215 jjdelcerro
    @Override
2414 40435 jjdelcerro
    public FeatureIndex createIndex(String indexTypeName,
2415 42293 jjdelcerro
        FeatureType featureType, String attributeName, String indexName)
2416
        throws DataException {
2417 40435 jjdelcerro
2418
        return createIndex(indexTypeName, featureType, attributeName,
2419 42293 jjdelcerro
            indexName, false, null);
2420 40435 jjdelcerro
    }
2421
2422 43215 jjdelcerro
    @Override
2423 40435 jjdelcerro
    public FeatureIndex createIndex(FeatureType featureType,
2424 42293 jjdelcerro
        String attributeName, String indexName, Observer observer)
2425
        throws DataException {
2426 40435 jjdelcerro
        return createIndex(null, featureType, attributeName, indexName,
2427 42293 jjdelcerro
            observer);
2428 40435 jjdelcerro
    }
2429
2430 43215 jjdelcerro
    @Override
2431 40435 jjdelcerro
    public FeatureIndex createIndex(String indexTypeName,
2432 42293 jjdelcerro
        FeatureType featureType, String attributeName, String indexName,
2433
        final Observer observer) throws DataException {
2434 40435 jjdelcerro
2435
        return createIndex(indexTypeName, featureType, attributeName,
2436 42293 jjdelcerro
            indexName, true, observer);
2437 40435 jjdelcerro
    }
2438
2439
    private FeatureIndex createIndex(String indexTypeName,
2440 42293 jjdelcerro
        FeatureType featureType, String attributeName, String indexName,
2441
        boolean background, final Observer observer) throws DataException {
2442 40435 jjdelcerro
2443
        checkNotInAppendMode();
2444 43215 jjdelcerro
        FeatureIndexProviderServices index;
2445
        index = dataManager.createFeatureIndexProvider(indexTypeName, this,
2446 42293 jjdelcerro
                featureType, indexName,
2447
                featureType.getAttributeDescriptor(attributeName));
2448 40435 jjdelcerro
2449
        try {
2450
            index.fill(background, observer);
2451
        } catch (FeatureIndexException e) {
2452
            throw new InitializeException(index.getName(), e);
2453
        }
2454
2455
        ((DefaultFeatureIndexes) getIndexes()).addIndex(index);
2456
        return index;
2457
    }
2458
2459
    //
2460
    // ====================================================================
2461
    // Transforms related methods
2462
    //
2463 42293 jjdelcerro
2464 43215 jjdelcerro
    @Override
2465 40435 jjdelcerro
    public FeatureStoreTransforms getTransforms() {
2466
        return this.transforms;
2467
    }
2468
2469 43215 jjdelcerro
    @Override
2470 40435 jjdelcerro
    public FeatureQuery createFeatureQuery() {
2471
        return new DefaultFeatureQuery();
2472
    }
2473
2474 43215 jjdelcerro
    @Override
2475 40435 jjdelcerro
    public DataQuery createQuery() {
2476
        return createFeatureQuery();
2477
    }
2478
2479
    //
2480
    // ====================================================================
2481
    // UndoRedo related methods
2482
    //
2483 42293 jjdelcerro
2484 43215 jjdelcerro
    @Override
2485 40435 jjdelcerro
    public boolean canRedo() {
2486
        return commands.canRedo();
2487
    }
2488
2489 43215 jjdelcerro
    @Override
2490 40435 jjdelcerro
    public boolean canUndo() {
2491
        return commands.canUndo();
2492
    }
2493
2494 43215 jjdelcerro
    @Override
2495 40435 jjdelcerro
    public void redo(int num) throws RedoException {
2496
        for (int i = 0; i < num; i++) {
2497
            redo();
2498
        }
2499
    }
2500
2501 43215 jjdelcerro
    @Override
2502 40435 jjdelcerro
    public void undo(int num) throws UndoException {
2503
        for (int i = 0; i < num; i++) {
2504
            undo();
2505
        }
2506
    }
2507
2508
    //
2509
    // ====================================================================
2510
    // Metadata related methods
2511
    //
2512 42293 jjdelcerro
2513 43215 jjdelcerro
    @Override
2514 40435 jjdelcerro
    public Object getMetadataID() {
2515
        return this.provider.getSourceId();
2516
    }
2517
2518 43215 jjdelcerro
    @Override
2519 40435 jjdelcerro
    public void delegate(DynObject dynObject) {
2520
        this.metadata.delegate(dynObject);
2521
    }
2522
2523 43215 jjdelcerro
    @Override
2524 40435 jjdelcerro
    public DynClass getDynClass() {
2525
        return this.metadata.getDynClass();
2526
    }
2527
2528 43215 jjdelcerro
    @Override
2529 42293 jjdelcerro
        public Object getDynValue(String name) throws DynFieldNotFoundException {
2530
                if( this.transforms.hasDynValue(name) ) {
2531
                        return this.transforms.getDynValue(name);
2532
                }
2533
                if (this.metadata.hasDynValue(name)) {
2534
                        return this.metadata.getDynValue(name);
2535
                }
2536
                if (METADATA_PROVIDER.equalsIgnoreCase(name)) {
2537
                        return this.provider.getProviderName();
2538
                } else if (METADATA_CONTAINERNAME.equalsIgnoreCase(name)) {
2539
                        return this.provider.getSourceId();
2540
                } else if (METADATA_FEATURETYPE.equalsIgnoreCase(name)) {
2541
                        try {
2542
                                return this.getDefaultFeatureType();
2543
                        } catch (DataException e) {
2544
                                return null;
2545
                        }
2546
                }
2547
                return this.metadata.getDynValue(name);
2548
        }
2549 40435 jjdelcerro
2550 43215 jjdelcerro
    @Override
2551 40435 jjdelcerro
    public boolean hasDynValue(String name) {
2552 42293 jjdelcerro
                if( this.transforms.hasDynValue(name) ) {
2553
                        return true;
2554
                }
2555 40435 jjdelcerro
        return this.metadata.hasDynValue(name);
2556
    }
2557 43270 fdiaz
2558 43215 jjdelcerro
    @Override
2559 43246 jjdelcerro
    public boolean hasDynMethod(String name) {
2560
        return ((DynObject_v2)this.metadata).hasDynMethod(name);
2561
    }
2562 43270 fdiaz
2563 43246 jjdelcerro
    @Override
2564 40435 jjdelcerro
    public void implement(DynClass dynClass) {
2565
        this.metadata.implement(dynClass);
2566
    }
2567
2568 43215 jjdelcerro
    @Override
2569 42775 jjdelcerro
    public Object invokeDynMethod(String name, Object[] args)
2570 42293 jjdelcerro
        throws DynMethodException {
2571 42775 jjdelcerro
        return this.metadata.invokeDynMethod(this, name, args);
2572 40435 jjdelcerro
    }
2573
2574 43215 jjdelcerro
    @Override
2575 42775 jjdelcerro
    public Object invokeDynMethod(int code, Object[] args)
2576 42293 jjdelcerro
        throws DynMethodException {
2577 42775 jjdelcerro
        return this.metadata.invokeDynMethod(this, code, args);
2578 40435 jjdelcerro
    }
2579
2580 43215 jjdelcerro
    @Override
2581 40435 jjdelcerro
    public void setDynValue(String name, Object value)
2582 42293 jjdelcerro
        throws DynFieldNotFoundException {
2583
                if( this.transforms.hasDynValue(name) ) {
2584
                        this.transforms.setDynValue(name, value);
2585
                        return;
2586
                }
2587 40435 jjdelcerro
        this.metadata.setDynValue(name, value);
2588
2589
    }
2590
2591
    /*
2592
     * (non-Javadoc)
2593 41818 fdiaz
     *
2594 40435 jjdelcerro
     * @see org.gvsig.metadata.Metadata#getMetadataChildren()
2595
     */
2596 43215 jjdelcerro
    @Override
2597 40435 jjdelcerro
    public Set getMetadataChildren() {
2598
        return this.metadataChildren;
2599
    }
2600
2601
    /*
2602
     * (non-Javadoc)
2603 41818 fdiaz
     *
2604 40435 jjdelcerro
     * @see org.gvsig.metadata.Metadata#getMetadataName()
2605
     */
2606 43215 jjdelcerro
    @Override
2607 40435 jjdelcerro
    public String getMetadataName() {
2608
        return this.provider.getProviderName();
2609
    }
2610
2611
    public FeatureTypeManager getFeatureTypeManager() {
2612
        return this.featureTypeManager;
2613
    }
2614
2615 43215 jjdelcerro
    @Override
2616 40435 jjdelcerro
    public long getFeatureCount() throws DataException {
2617
        if (featureCount == null) {
2618 43215 jjdelcerro
            featureCount = this.provider.getFeatureCount();
2619 40435 jjdelcerro
        }
2620 42556 dmartinezizquierdo
        if (this.isEditing()) {
2621
            if(this.isAppending()) {
2622
                try{
2623
                    throw new IllegalStateException();
2624
                } catch(IllegalStateException e) {
2625 43840 jjdelcerro
                    LOG.info("Call DefaultFeatureStore.getFeatureCount editing in mode APPEND",e);
2626 42556 dmartinezizquierdo
                }
2627
                return -1;
2628
            } else {
2629 43215 jjdelcerro
                return featureCount
2630 42556 dmartinezizquierdo
                    + this.featureManager.getDeltaSize();
2631
            }
2632 40435 jjdelcerro
        }
2633 43215 jjdelcerro
        return featureCount;
2634 40435 jjdelcerro
    }
2635
2636
    private Long getTemporalOID() {
2637 43215 jjdelcerro
        return this.temporalOid++;
2638 40435 jjdelcerro
    }
2639
2640 43215 jjdelcerro
    @Override
2641 40435 jjdelcerro
    public FeatureType getProviderFeatureType(String featureTypeId) {
2642
        if (featureTypeId == null) {
2643
            return this.defaultFeatureType;
2644
        }
2645
        FeatureType type;
2646
        Iterator iter = this.featureTypes.iterator();
2647
        while (iter.hasNext()) {
2648
            type = (FeatureType) iter.next();
2649
            if (type.getId().equals(featureTypeId)) {
2650
                return type;
2651
            }
2652
        }
2653
        return null;
2654
    }
2655
2656 43215 jjdelcerro
    @Override
2657 40435 jjdelcerro
    public FeatureProvider getFeatureProviderFromFeature(Feature feature) {
2658
        return ((DefaultFeature) feature).getData();
2659
    }
2660
2661 43215 jjdelcerro
    @Override
2662 40435 jjdelcerro
    public DataStore getStore() {
2663
        return this;
2664
    }
2665
2666 43215 jjdelcerro
    @Override
2667 40435 jjdelcerro
    public FeatureStore getFeatureStore() {
2668
        return this;
2669
    }
2670
2671 43215 jjdelcerro
    @Override
2672 43056 jjdelcerro
    public void createCache(String name, DynObject parameters)
2673
        throws DataException {
2674
        cache = dataManager.createFeatureCacheProvider(name, parameters);
2675
        if (cache == null) {
2676
            throw new CreateException("FeaureCacheProvider", null);
2677
        }
2678
        cache.apply(this, provider);
2679
        provider = cache;
2680 40435 jjdelcerro
2681 43056 jjdelcerro
        featureCount = null;
2682
    }
2683
2684 43215 jjdelcerro
    @Override
2685 43056 jjdelcerro
    public FeatureCache getCache() {
2686
        return cache;
2687
    }
2688
2689 43215 jjdelcerro
    @Override
2690 40435 jjdelcerro
    public void clear() {
2691
        if (metadata != null) {
2692
            metadata.clear();
2693
        }
2694
    }
2695
2696 43215 jjdelcerro
    @Override
2697 40435 jjdelcerro
    public String getName() {
2698 43215 jjdelcerro
        if( this.provider != null ) {
2699
            return this.provider.getName();
2700
        }
2701
        if( this.parameters instanceof HasAFile ) {
2702
            return FilenameUtils.getName(((HasAFile)this.parameters).getFile().getName());
2703
        }
2704
        return "unknow";
2705 40435 jjdelcerro
    }
2706
2707 43215 jjdelcerro
    @Override
2708 40435 jjdelcerro
    public String getFullName() {
2709 42049 jjdelcerro
        try {
2710 43215 jjdelcerro
            if( this.provider!=null ) {
2711
                return this.provider.getFullName();
2712
            }
2713
            if( this.parameters instanceof HasAFile ) {
2714
                return (((HasAFile)this.parameters).getFile().getAbsolutePath());
2715
            }
2716
            return null;
2717 42293 jjdelcerro
        } catch(Throwable th) {
2718 42049 jjdelcerro
            return null;
2719
        }
2720 40435 jjdelcerro
    }
2721
2722 43215 jjdelcerro
    @Override
2723 40435 jjdelcerro
    public String getProviderName() {
2724 43215 jjdelcerro
        if( this.provider!=null ) {
2725
            return this.provider.getProviderName();
2726
        }
2727
        if( this.parameters != null ) {
2728
            return this.parameters.getDataStoreName();
2729
        }
2730
        return null;
2731 43270 fdiaz
2732 40435 jjdelcerro
    }
2733
2734 43215 jjdelcerro
    @Override
2735 40435 jjdelcerro
    public boolean isKnownEnvelope() {
2736
        return this.provider.isKnownEnvelope();
2737
    }
2738
2739 43215 jjdelcerro
    @Override
2740 40435 jjdelcerro
    public boolean hasRetrievedFeaturesLimit() {
2741
        return this.provider.hasRetrievedFeaturesLimit();
2742
    }
2743
2744 43215 jjdelcerro
    @Override
2745 40435 jjdelcerro
    public int getRetrievedFeaturesLimit() {
2746
        return this.provider.getRetrievedFeaturesLimit();
2747
    }
2748
2749 43215 jjdelcerro
    @Override
2750 41818 fdiaz
    public Interval getInterval() {
2751 43135 jjdelcerro
        if( this.timeSupport!=null ) {
2752
            return this.timeSupport.getInterval();
2753
        }
2754 40435 jjdelcerro
        return this.provider.getInterval();
2755
    }
2756
2757 43215 jjdelcerro
    @Override
2758 41818 fdiaz
    public Collection getTimes() {
2759 43135 jjdelcerro
        if( this.timeSupport!=null ) {
2760
            return this.timeSupport.getTimes();
2761
        }
2762 40435 jjdelcerro
        return this.provider.getTimes();
2763
    }
2764
2765 43215 jjdelcerro
    @Override
2766 41818 fdiaz
    public Collection getTimes(Interval interval) {
2767 43135 jjdelcerro
        if( this.timeSupport!=null ) {
2768
            return this.timeSupport.getTimes(interval);
2769
        }
2770 40435 jjdelcerro
        return this.provider.getTimes(interval);
2771
    }
2772 41818 fdiaz
2773 43135 jjdelcerro
    public void setTimeSupport(FeatureStoreTimeSupport timeSupport) {
2774 43610 jjdelcerro
        if( this.isEditing() ) {
2775
            throw new RuntimeException("Can't add time support over attribute '"+timeSupport.getAttributeName()+"' while store is editing.");
2776 43135 jjdelcerro
        }
2777 43610 jjdelcerro
        if( !this.transforms.isEmpty() ) {
2778
            throw new RuntimeException("Can't add time support over attribute '"+timeSupport.getAttributeName()+"' if has transforms.");
2779 43135 jjdelcerro
        }
2780 43610 jjdelcerro
        FeatureType ft = this.defaultFeatureType;
2781
        FeatureAttributeDescriptor attr = ft.getAttributeDescriptor(timeSupport.getRequiredFieldNames()[0]);
2782
        if( attr == null ) {
2783 43135 jjdelcerro
            throw new RuntimeException("Can't add time support over attribute '"+timeSupport.getAttributeName()+"', this attribute don't exists.");
2784
        }
2785 43610 jjdelcerro
        EditableFeatureType eft = ft.getEditable();
2786
        attr = eft.getAttributeDescriptor(timeSupport.getAttributeName());
2787
        if( attr != null ) {
2788
            if( !(attr.getFeatureAttributeEmulator() instanceof FeatureStoreTimeSupport) ) {
2789
                throw new RuntimeException("Can't add time support, attribute '"+timeSupport.getAttributeName()+"'already exists.");
2790
            }
2791
            eft.remove(attr.getName());
2792
        }
2793
        EditableFeatureAttributeDescriptor attrTime = eft.add(
2794
            timeSupport.getAttributeName(),
2795
            timeSupport.getDataType()
2796
        );
2797
        attrTime.setIsTime(true);
2798
        attrTime.setFeatureAttributeEmulator(timeSupport);
2799
        eft.setDefaultTimeAttributeName(timeSupport.getAttributeName());
2800
        this.defaultFeatureType = eft.getNotEditableCopy();
2801
2802 43135 jjdelcerro
        this.timeSupport = timeSupport;
2803
    }
2804 43152 fdiaz
2805 43215 jjdelcerro
    @Override
2806 43840 jjdelcerro
    @SuppressWarnings("CloneDoesntCallSuperClone")
2807 40435 jjdelcerro
    public Object clone() throws CloneNotSupportedException {
2808 41818 fdiaz
2809 40435 jjdelcerro
        DataStoreParameters dsp = getParameters();
2810 41818 fdiaz
2811 40435 jjdelcerro
        DefaultFeatureStore cloned_store = null;
2812 41818 fdiaz
2813 40435 jjdelcerro
        try {
2814
            cloned_store = (DefaultFeatureStore) DALLocator.getDataManager().
2815 42293 jjdelcerro
                openStore(this.getProviderName(), dsp);
2816 40435 jjdelcerro
            if (transforms != null) {
2817
                cloned_store.transforms = (DefaultFeatureStoreTransforms) transforms.clone();
2818 41093 jldominguez
                cloned_store.transforms.setStoreForClone(cloned_store);
2819 40435 jjdelcerro
            }
2820
        } catch (Exception e) {
2821
            throw new CloneException(e);
2822 41818 fdiaz
        }
2823 40435 jjdelcerro
        return cloned_store;
2824 41818 fdiaz
2825 40435 jjdelcerro
    }
2826 41818 fdiaz
2827 43215 jjdelcerro
    @Override
2828 41818 fdiaz
    public Feature getFeature(DynObject dynobject) {
2829 42293 jjdelcerro
        if (dynobject instanceof DynObjectFeatureFacade){
2830
            Feature f = ((DynObjectFeatureFacade)dynobject).getFeature();
2831 41818 fdiaz
            return f;
2832
        }
2833
        return null;
2834
    }
2835 42533 dmartinezizquierdo
2836 43215 jjdelcerro
    @Override
2837 42293 jjdelcerro
    public Iterator iterator() {
2838
        try {
2839
            return this.getFeatureSet().fastIterator();
2840
        } catch (DataException ex) {
2841
            throw new RuntimeException(ex);
2842
        }
2843
    }
2844 43020 jjdelcerro
2845
    @Override
2846 43521 jjdelcerro
    public ExpressionBuilder createExpressionBuilder() {
2847 43020 jjdelcerro
        if( this.provider instanceof FeatureStoreProvider_v2 ) {
2848 43088 jjdelcerro
            return ((FeatureStoreProvider_v2)this.provider).createExpression();
2849 43020 jjdelcerro
        }
2850
        return new SQLBuilderBase();
2851
    }
2852 43062 jjdelcerro
2853 43521 jjdelcerro
    @Override
2854
    public ExpressionBuilder createExpression() {
2855
        return createExpressionBuilder();
2856
    }
2857 43152 fdiaz
2858 43062 jjdelcerro
    public FeatureSet features() throws DataException {
2859
        // This is to avoid jython to create a property with this name
2860
        // to access method getFeatures.
2861
        return this.getFeatureSet();
2862
    }
2863 43152 fdiaz
2864
    @Override
2865 43190 jjdelcerro
    public DataStoreProviderFactory getProviderFactory() {
2866 43152 fdiaz
        DataStoreProviderFactory factory = dataManager.getStoreProviderFactory(parameters.getDataStoreName());
2867
        return factory;
2868
    }
2869
2870
    @Override
2871
    public void useCache(String providerName, DynObject parameters) throws DataException {
2872
        throw new UnsupportedOperationException();
2873
    }
2874 43270 fdiaz
2875 43215 jjdelcerro
    @Override
2876
    public boolean isBroken() {
2877
        return this.state.isBroken();
2878
    }
2879
2880
    @Override
2881
    public Throwable getBreakingsCause() {
2882
            return this.state.getBreakingsCause();
2883
    }
2884 43371 fdiaz
2885
    @Override
2886
    public SpatialIndex wrapSpatialIndex(SpatialIndex index) {
2887 43705 jjdelcerro
      FeatureStoreProviderFactory factory = (FeatureStoreProviderFactory) this.getProviderFactory();
2888
      if( !factory.supportNumericOID() ) {
2889
          return null;
2890
      }
2891 43371 fdiaz
      SpatialIndex wrappedIndex = new WrappedSpatialIndex(index, this);
2892
      return wrappedIndex;
2893
  }
2894 43824 jjdelcerro
2895
    @Override
2896
    public FeatureReference getFeatureReference(String code) {
2897
        FeatureReference featureReference = new DefaultFeatureReference(this, code);
2898
        return featureReference;
2899
    }
2900 42293 jjdelcerro
}