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

History | View | Annotate | Download (85.8 KB)

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

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

    
27
import org.gvsig.fmap.dal.feature.spi.SQLBuilderBase;
28

    
29
import java.util.ArrayList;
30
import java.util.Collection;
31
import java.util.Collections;
32
import java.util.HashMap;
33
import java.util.HashSet;
34
import java.util.Iterator;
35
import java.util.List;
36
import java.util.Map;
37
import java.util.Map.Entry;
38
import java.util.Set;
39

    
40
import org.apache.commons.io.FilenameUtils;
41
import org.cresques.cts.IProjection;
42

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

    
162
import org.slf4j.Logger;
163
import org.slf4j.LoggerFactory;
164

    
165
public class DefaultFeatureStore extends AbstractDisposable implements
166
    DataStoreInitializer2, FeatureStoreProviderServices, FeatureStore, Observer {
167

    
168
    private static final Logger LOG = LoggerFactory
169
        .getLogger(DefaultFeatureStore.class);
170

    
171
    private static final String PERSISTENCE_DEFINITION_NAME = "FeatureStore";
172

    
173
    private DataStoreParameters parameters = null;
174
    private FeatureSelection selection;
175
    private FeatureLocks locks;
176

    
177
    private DelegateWeakReferencingObservable delegateObservable =
178
        new DelegateWeakReferencingObservable(this);
179

    
180
    private FeatureCommandsStack commands;
181
    private FeatureTypeManager featureTypeManager;
182
    private FeatureManager featureManager;
183
    private SpatialManager spatialManager;
184

    
185
    private FeatureType defaultFeatureType = null;
186
    private List featureTypes = new ArrayList();
187

    
188
    private int mode = MODE_QUERY;
189
    private long versionOfUpdate = 0;
190
    private boolean hasStrongChanges = true;
191
    private boolean hasInserts = true;
192

    
193
    private DefaultDataManager dataManager = null;
194

    
195
    private FeatureStoreProvider provider = null;
196

    
197
    private DefaultFeatureIndexes indexes;
198

    
199
    private DefaultFeatureStoreTransforms transforms;
200

    
201
    DelegatedDynObject metadata;
202

    
203
    private Set metadataChildren;
204

    
205
    private Long featureCount = null;
206

    
207
    private long temporalOid = 0;
208

    
209
    private FeatureCacheProvider cache;
210

    
211
    StateInformation state;
212

    
213
    FeatureStoreTimeSupport timeSupport;
214

    
215

    
216
    private class StateInformation extends HashMap<Object, Object> {
217

    
218
        private static final long serialVersionUID = 4109026189635185666L;
219

    
220
        private boolean broken;
221
        private Throwable breakingsCause;
222

    
223
        public StateInformation() {
224
            this.clear();
225
        }
226

    
227
        @Override
228
        public void clear() {
229
            this.broken = false;
230
            this.breakingsCause = null;
231
            super.clear();
232
        }
233

    
234
        public boolean isBroken() {
235
            return this.broken;
236
        }
237

    
238
        public void broken() {
239
            this.broken = true;
240
        }
241

    
242
        public Throwable getBreakingsCause() {
243
            return this.breakingsCause;
244
        }
245

    
246
        public void setBreakingsCause(Throwable cause) {
247
            if( this.breakingsCause==null ) {
248
                this.breakingsCause = cause;
249
            }
250
            this.broken = true;
251
        }
252
    }
253

    
254

    
255

    
256
    /*
257
     * TODO:
258
     *
259
     * - Comprobar que solo se pueden a?adir reglas de validacion sobre un
260
     * EditableFeatureType. - Comprobar que solo se puede hacer un update con un
261
     * featureType al que se le han cambiado las reglas de validacion cuando
262
     * hasStrongChanges=false.
263
     */
264

    
265
    public DefaultFeatureStore() {
266
        this.state = new StateInformation();
267
    }
268

    
269
    @Override
270
    public void intialize(DataManager dataManager,
271
        DataStoreParameters parameters) throws InitializeException {
272

    
273
        DynObjectManager dynManager = ToolsLocator.getDynObjectManager();
274

    
275
        this.metadata = (DelegatedDynObject) dynManager.createDynObject(
276
            FeatureStore.METADATA_DEFINITION_NAME,
277
            MetadataManager.METADATA_NAMESPACE
278
        );
279

    
280
        this.dataManager = (DefaultDataManager) dataManager;
281

    
282
        this.parameters = parameters;
283
        this.transforms = new DefaultFeatureStoreTransforms(this);
284
        try {
285
            indexes = new DefaultFeatureIndexes(this);
286
        } catch (DataException e) {
287
            throw new InitializeException(e);
288
        }
289

    
290
    }
291

    
292
    @Override
293
    public void setProvider(org.gvsig.fmap.dal.DataStoreProvider provider) {
294
        this.provider = (FeatureStoreProvider) provider;
295
        this.delegate((DynObject) provider);
296
        this.metadataChildren = new HashSet();
297
        this.metadataChildren.add(provider);
298
    }
299

    
300
    @Override
301
    public DataStoreParameters getParameters() {
302
        return parameters;
303
    }
304

    
305
    public int getMode() {
306
        return this.mode;
307
    }
308

    
309
    @Override
310
    public DataManager getManager() {
311
        return this.dataManager;
312
    }
313

    
314
    @Override
315
    public Iterator getChildren() {
316
        return this.provider.getChilds();
317
    }
318

    
319
    @Override
320
    public FeatureStoreProvider getProvider() {
321
        return this.provider;
322
    }
323

    
324
    public FeatureManager getFeatureManager() {
325
        return this.featureManager;
326
    }
327

    
328
    @Override
329
    public void setFeatureTypes(List types, FeatureType defaultType) {
330
        this.featureTypes = types;
331
        this.defaultFeatureType = defaultType;
332
    }
333

    
334
    public void open() throws OpenException {
335
        if (this.mode != MODE_QUERY) {
336
            // TODO: Se puede hacer un open estando en edicion ?
337
            try {
338
                throw new IllegalStateException();
339
            } catch(Exception ex) {
340
                LOG.warn("Opening a store in editing/append mode ("+this.getFullName()+").",ex);
341
            }
342
        }
343
        this.notifyChange(DataStoreNotification.BEFORE_OPEN);
344
        this.provider.open();
345
        this.notifyChange(DataStoreNotification.AFTER_OPEN);
346
    }
347

    
348
    @Override
349
    public void refresh() throws OpenException, InitializeException {
350
        if (this.mode != MODE_QUERY) {
351
            throw new IllegalStateException();
352
        }
353
        this.notifyChange(FeatureStoreNotification.BEFORE_REFRESH);
354
        if( state.isBroken() ) {
355
            this.load(state);
356
        } else {
357
            this.featureCount = null;
358
            this.provider.refresh();
359
        }
360
        this.notifyChange(FeatureStoreNotification.AFTER_REFRESH);
361
    }
362

    
363
    public void close() throws CloseException {
364
        if (this.mode != MODE_QUERY) {
365
            // TODO: Se puede hacer un close estando en edicion ?
366
            try {
367
                throw new IllegalStateException();
368
            } catch(Exception ex) {
369
                LOG.warn("Clossing a store in editing/append mode ("+this.getFullName()+").",ex);
370
            }
371
        }
372
        this.notifyChange(DataStoreNotification.BEFORE_CLOSE);
373
        this.featureCount = null;
374
        this.provider.close();
375
        this.notifyChange(DataStoreNotification.AFTER_CLOSE);
376
    }
377

    
378
    @Override
379
    protected void doDispose() throws BaseException {
380
        if (this.mode != MODE_QUERY) {
381
            // TODO: Se puede hacer un dispose estando en edicion ?
382
            try {
383
                throw new IllegalStateException();
384
            } catch(Exception ex) {
385
                LOG.warn("Dispossing a store in editing/append mode ("+this.getFullName()+").",ex);
386
            }
387
        }
388
        this.notifyChange(DataStoreNotification.BEFORE_DISPOSE);
389
        this.disposeIndexes();
390
        this.provider.dispose();
391
        if (this.selection != null) {
392
            this.selection.dispose();
393
            this.selection = null;
394
        }
395
        this.commands = null;
396
        this.featureCount = null;
397
        if (this.locks != null) {
398
            // this.locks.dispose();
399
            this.locks = null;
400
        }
401

    
402
        if (this.featureTypeManager != null) {
403
            this.featureTypeManager.dispose();
404
            this.featureTypeManager = null;
405
        }
406

    
407
        this.featureManager = null;
408
        this.spatialManager = null;
409

    
410
        this.parameters = null;
411
        this.notifyChange(DataStoreNotification.AFTER_DISPOSE);
412
        if (delegateObservable != null) {
413
            this.delegateObservable.deleteObservers();
414
            this.delegateObservable = null;
415
        }
416
    }
417

    
418
    @Override
419
    public boolean allowWrite() {
420
        SimpleIdentityManager identityManager = ToolsLocator.getIdentityManager();
421
        if( ! identityManager.getCurrentIdentity().isAuthorized(DataManager.WRITE_STORE_AUTHORIZATION,this.getParameters(), this.getName()) ) {
422
            return false;
423
        }
424
        return this.provider.allowWrite();
425
    }
426

    
427
    @Override
428
    public boolean canWriteGeometry(int geometryType) throws DataException {
429
        return this.provider.canWriteGeometry(geometryType, 0);
430
    }
431

    
432
    @Override
433
    public DataServerExplorer getExplorer() throws ReadException,
434
        ValidateDataParametersException {
435
        if( this.state.isBroken() ) {
436
            try {
437
                return this.provider.getExplorer();
438
            } catch(Throwable th) {
439
                return null;
440
            }
441
        } else {
442
            return this.provider.getExplorer();
443
        }
444
    }
445

    
446
    /*
447
     * public Metadata getMetadata() throws MetadataNotFoundException {
448
     * // TODO:
449
     * // Si el provider devuelbe null habria que ver de construir aqui
450
     * // los metadatos basicos, como el Envelope y el SRS.
451
     *
452
     * // TODO: Estando en edicion el Envelope deberia de
453
     * // actualizarse usando el spatialManager
454
     * return this.provider.getMetadata();
455
     * }
456
     */
457

    
458
    @Override
459
    public Envelope getEnvelope() throws DataException {
460
        if (this.mode == MODE_FULLEDIT) {
461
                // Just in case another thread tries to write in the store
462
                synchronized (this) {
463
                        return this.spatialManager.getEnvelope();
464
                        }
465
        }
466
        if (hasDynValue(DataStore.METADATA_ENVELOPE)){
467
            return (Envelope)getDynValue(DataStore.METADATA_ENVELOPE);
468
        }
469
        return this.provider.getEnvelope();
470
    }
471

    
472
    /**
473
     * @deprecated use getDefaultFeatureType().getDefaultSRS()
474
     */
475
    @Override
476
    public IProjection getSRSDefaultGeometry() throws DataException {
477
        return this.getDefaultFeatureType().getDefaultSRS();
478
    }
479

    
480
    @Override
481
    public FeatureSelection createDefaultFeatureSelection()
482
        throws DataException {
483
        return new DefaultFeatureSelection(this);
484
    }
485

    
486
    @Override
487
    public FeatureProvider createDefaultFeatureProvider(FeatureType type)
488
        throws DataException {
489
        if (type.hasOID()) {
490
            return new DefaultFeatureProvider(type,
491
                this.provider.createNewOID());
492
        }
493
        return new DefaultFeatureProvider(type);
494
    }
495

    
496
    @Override
497
    public void saveToState(PersistentState state) throws PersistenceException {
498
        /*if (this.mode != FeatureStore.MODE_QUERY) {
499
            throw new PersistenceException(new IllegalStateException(
500
                this.getName()));
501
        }*/
502
        state.set("dataStoreName", this.getName());
503
        state.set("parameters", this.parameters);
504
        state.set("selection", this.selection);
505
        state.set("transforms", this.transforms);
506
        // TODO locks persistence
507
        // state.set("locks", this.locks);
508
        // TODO indexes persistence
509
        // state.set("indexes", this.indexes);
510
        Map evaluatedAttr = new HashMap(1);
511
        Iterator iterType = featureTypes.iterator();
512
        Iterator iterAttr;
513
        FeatureType type;
514
        DefaultFeatureAttributeDescriptor attr;
515
        List attrs;
516
        while (iterType.hasNext()) {
517
            type = (FeatureType) iterType.next();
518
            attrs = new ArrayList();
519
            iterAttr = type.iterator();
520
            while (iterAttr.hasNext()) {
521
                attr = (DefaultFeatureAttributeDescriptor) iterAttr.next();
522
                if ((attr.getEvaluator() != null)
523
                    && (attr.getEvaluator() instanceof Persistent)) {
524
                    attrs.add(attr);
525
                }
526
            }
527
            if (!attrs.isEmpty()) {
528
                evaluatedAttr.put(type.getId(), attrs);
529
            }
530

    
531
        }
532

    
533
        if (evaluatedAttr.isEmpty()) {
534
            evaluatedAttr = null;
535
        }
536

    
537
        state.set("evaluatedAttributes", evaluatedAttr);
538
        state.set("defaultFeatureTypeId", defaultFeatureType.getId());
539

    
540
    }
541

    
542
    @Override
543
    public void loadFromState(final PersistentState persistentState)
544
        throws PersistenceException {
545
        if (this.provider != null) {
546
            throw new PersistenceStoreAlreadyLoadedException(this.getName());
547
        }
548
        if (this.getManager() == null) {
549
            this.dataManager = (DefaultDataManager) DALLocator.getDataManager();
550
        }
551
        state.clear();
552
        try {
553
            state.put("parameters", persistentState.get("parameters"));
554
        } catch(Throwable th) {
555
            state.setBreakingsCause(th);
556
        }
557
        try {
558
            state.put("selection", persistentState.get("selection"));
559
        } catch(Throwable th) {
560
            state.setBreakingsCause(th);
561
        }
562
        try {
563
            state.put("transforms",  persistentState.get("transforms"));
564
        } catch(Throwable th) {
565
            state.setBreakingsCause(th);
566
        }
567
        try {
568
            state.put("evaluatedAttributes",  persistentState.get("evaluatedAttributes"));
569
        } catch(Throwable th) {
570
            state.setBreakingsCause(th);
571
        }
572
        try {
573
            state.put("defaultFeatureTypeId", persistentState.getString("defaultFeatureTypeId"));
574
        } catch(Throwable th) {
575
            state.setBreakingsCause(th);
576
        }
577
        load(state);
578
    }
579

    
580
    private void load(StateInformation state) {
581
        this.featureTypes = new ArrayList();
582
        this.defaultFeatureType = null;
583
        this.featureCount = null;
584

    
585
        DataStoreParameters params = (DataStoreParameters) state.get("parameters");
586
        try {
587
            intialize(dataManager, params);
588
        } catch(Throwable th) {
589
            state.setBreakingsCause(th);
590
        }
591

    
592
        try {
593
            DataStoreProvider prov = dataManager.createProvider(
594
                getStoreProviderServices(),
595
                params
596
            );
597
            setProvider(prov);
598
        } catch(Throwable th) {
599
            state.setBreakingsCause(th);
600
        }
601

    
602
        try {
603
            selection = (FeatureSelection) state.get("selection");
604
        } catch(Throwable th) {
605
            state.setBreakingsCause(th);
606
        }
607

    
608
        try {
609
            this.transforms = (DefaultFeatureStoreTransforms) state.get("transforms");
610
            this.transforms.setFeatureStore(this);
611
            for( FeatureStoreTransform transform : this.transforms ) {
612
                try {
613
                    transform.setUp();
614
                } catch(Throwable th) {
615
                    state.setBreakingsCause(th);
616
                }
617
            }
618
        } catch(Throwable th) {
619
            state.setBreakingsCause(th);
620
        }
621

    
622
        try {
623
            Map evaluatedAttributes = (Map) state.get("evaluatedAttributes");
624
            if ((evaluatedAttributes != null) && !evaluatedAttributes.isEmpty()) {
625
                    Iterator iterEntries = evaluatedAttributes.entrySet().iterator();
626
                    while (iterEntries.hasNext()) {
627
                            Entry entry = (Entry) iterEntries.next();
628
                            List attrs = (List) entry.getValue();
629
                            if (attrs.isEmpty()) {
630
                                    continue;
631
                            }
632
                            int fTypePos = -1;
633
                            DefaultFeatureType type = null;
634
                            for (int i = 0; i < featureTypes.size(); i++) {
635
                                    type = (DefaultFeatureType) featureTypes.get(i);
636
                                    if (type.getId().equals(entry.getKey())) {
637
                                            fTypePos = i;
638
                                            break;
639
                                    }
640
                            }
641
                            if (type == null) {
642
                                    throw new PersistenceCantFindFeatureTypeException(
643
                                            getName(), (String) entry.getKey());
644
                            }
645
                            DefaultEditableFeatureType eType = (DefaultEditableFeatureType) type.getEditable();
646
                            Iterator<FeatureAttributeDescriptor> iterAttr = attrs.iterator();
647
                            while (iterAttr.hasNext()) {
648
                                    FeatureAttributeDescriptor attr = iterAttr.next();
649
                                    eType.addLike(attr);
650
                            }
651
                            featureTypes.set(fTypePos, eType.getNotEditableCopy());
652

    
653
                    }
654

    
655
            }
656
        } catch(Throwable th) {
657
            state.setBreakingsCause(th);
658
        }
659

    
660

    
661
        try {
662
            String defaultFeatureTypeId = (String) state.get("defaultFeatureTypeId");
663
            FeatureType ftype;
664

    
665
            if (defaultFeatureType == null ||
666
                    defaultFeatureType.getId() == null ||
667
                    !defaultFeatureType.getId().equals(defaultFeatureTypeId)) {
668

    
669
                    ftype = getFeatureType(defaultFeatureTypeId);
670
                    if (ftype == null) {
671
                            /*
672
                             * Un error en el m?todo de PostgreSQL getName(), hace que
673
                             * el nombre del featureType sea valor retornado por el getProviderName()
674
                             * De momento se pone este parche para apa?arlo y poder mantener compatibilidad
675
                             * con proyectos antiguos (2.1 y 2.2)
676
                             */
677
                            ftype = getFeatureType(getName());
678
                            if(ftype == null ) {
679
                                    throw new RuntimeException("Can't locate feature type");
680
                            }
681
                    }
682
                    defaultFeatureType = ftype;
683
            }
684
        } catch(Throwable th) {
685
            state.setBreakingsCause(th);
686
        }
687

    
688
        LOG.info("load() broken:{}, {}, {}.",
689
                new Object[] { state.isBroken(), this.getProviderName(), params }
690
        );
691
    }
692

    
693
        public DataStoreProviderServices getStoreProviderServices() {
694
                return this;
695
        }
696

    
697
    public static void registerPersistenceDefinition() {
698
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
699
        if (manager.getDefinition(PERSISTENCE_DEFINITION_NAME) == null) {
700
            DynStruct definition =
701
                manager.addDefinition(DefaultFeatureStore.class,
702
                    PERSISTENCE_DEFINITION_NAME, PERSISTENCE_DEFINITION_NAME
703
                        + " Persistent definition", null, null);
704
            definition.addDynFieldString("dataStoreName").setMandatory(true)
705
                .setPersistent(true);
706

    
707
            definition.addDynFieldObject("parameters")
708
                .setClassOfValue(DynObject.class).setMandatory(true)
709
                .setPersistent(true);
710

    
711
            definition.addDynFieldObject("selection")
712
                .setClassOfValue(FeatureSelection.class).setMandatory(false)
713
                .setPersistent(true);
714

    
715
            definition.addDynFieldObject("transforms")
716
                .setClassOfValue(DefaultFeatureStoreTransforms.class)
717
                .setMandatory(true).setPersistent(true);
718

    
719
            definition.addDynFieldMap("evaluatedAttributes")
720
                .setClassOfItems(List.class) // List<DefaultFeatureAttributeDescriptor>
721
                .setMandatory(false).setPersistent(true);
722

    
723
            definition.addDynFieldString("defaultFeatureTypeId")
724
                .setMandatory(true).setPersistent(true);
725
        }
726
    }
727

    
728
    public static void registerMetadataDefinition() throws MetadataException {
729
        MetadataManager manager = MetadataLocator.getMetadataManager();
730
        if (manager.getDefinition(FeatureStore.METADATA_DEFINITION_NAME) == null) {
731
            DynStruct metadataDefinition =
732
                manager.addDefinition(FeatureStore.METADATA_DEFINITION_NAME, null);
733
            metadataDefinition.extend(manager
734
                .getDefinition(DataStore.METADATA_DEFINITION_NAME));
735
        }
736
    }
737

    
738
    //
739
    // ====================================================================
740
    // Gestion de la seleccion
741
    //
742

    
743
    @Override
744
    public void setSelection(DataSet selection) throws DataException {
745
        this.setSelection((FeatureSet) selection);
746
    }
747

    
748
    @Override
749
    public DataSet createSelection() throws DataException {
750
        return createFeatureSelection();
751
    }
752

    
753
    @Override
754
    public DataSet getSelection() throws DataException {
755
        return this.getFeatureSelection();
756
    }
757

    
758
    @Override
759
    public void setSelection(FeatureSet selection) throws DataException {
760
        setSelection(selection, true);
761
    }
762

    
763
    public void setSelection(FeatureSet selection, boolean undoable)
764
        throws DataException {
765
        if (selection == null) {
766
            if (undoable) {
767
                throw new SelectionNotAllowedException(getName());
768
            }
769

    
770
        } else {
771
            if (selection.equals(this.selection)) {
772
                return;
773
            }
774
            if (!selection.isFromStore(this)) {
775
                throw new SelectionNotAllowedException(getName());
776
            }
777
        }
778

    
779
        if (this.selection != null) {
780
            this.selection.deleteObserver(this);
781
        }
782
        if (selection == null) {
783
            if (this.selection != null) {
784
                this.selection.dispose();
785
            }
786
            this.selection = null;
787
            return;
788
        }
789
        if (selection instanceof FeatureSelection) {
790
            if (undoable && isEditing()) {
791
                commands.selectionSet(this, this.selection,
792
                    (FeatureSelection) selection);
793
            }
794
            if (this.selection != null) {
795
                this.selection.dispose();
796
            }
797
            this.selection = (FeatureSelection) selection;
798
        } else {
799
            if (undoable && isEditing()) {
800
                commands.startComplex("_selectionSet");
801
            }
802
            if (selection instanceof DefaultFeatureSelection) {
803
                DefaultFeatureSelection defSelection =
804
                    (DefaultFeatureSelection) selection;
805
                defSelection.deselectAll(undoable);
806
                defSelection.select(selection, undoable);
807
            } else {
808
                this.selection.deselectAll();
809
                this.selection.select(selection);
810
            }
811
            if (undoable && isEditing()) {
812
                commands.endComplex();
813
            }
814
        }
815
        this.selection.addObserver(this);
816

    
817
        this.notifyChange(DataStoreNotification.SELECTION_CHANGE);
818
    }
819

    
820
    @Override
821
    public FeatureSelection createFeatureSelection() throws DataException {
822
        return this.provider.createFeatureSelection();
823
    }
824

    
825
    @Override
826
    public FeatureSelection getFeatureSelection() throws DataException {
827
        if (selection == null) {
828
            this.selection = createFeatureSelection();
829
            this.selection.addObserver(this);
830
        }
831
        return selection;
832
    }
833

    
834
    //
835
    // ====================================================================
836
    // Gestion de notificaciones
837
    //
838

    
839
    @Override
840
    public void notifyChange(FeatureStoreNotification storeNotification) {
841
        try {
842
            delegateObservable.notifyObservers(storeNotification);
843
        } catch (Throwable ex) {
844
            LOG.warn("Problems notifying changes in the store '"+this.getName()+" ("+storeNotification.getType()+").",ex);
845
        }
846
    }
847

    
848
    @Override
849
    public void notifyChange(String notification) {
850
        if (delegateObservable != null) {
851
            notifyChange(new DefaultFeatureStoreNotification(this, notification));
852
        }
853

    
854
    }
855

    
856
    @Override
857
    public void notifyChange(String notification, FeatureProvider data) {
858
        Feature f = null;
859
        try {
860
            f = createFeature(data);
861
        } catch (Throwable ex) {
862
            LOG.warn("Problems creating a feature to notifying changes in the store '"+this.getName()+" ("+notification+").",ex);
863
        }
864
        notifyChange(notification, f);
865
    }
866

    
867
    public void notifyChange(String notification, Feature feature) {
868
        notifyChange(new DefaultFeatureStoreNotification(this, notification,
869
            feature));
870
    }
871

    
872
    public void notifyChange(String notification, Command command) {
873
        notifyChange(new DefaultFeatureStoreNotification(this, notification,
874
            command));
875
    }
876

    
877
    public void notifyChange(String notification, EditableFeatureType type) {
878
        notifyChange(new DefaultFeatureStoreNotification(this, notification,
879
            type));
880
    }
881

    
882
    @Override
883
    public void notifyChange(String notification, Resource resource) {
884
        notifyChange(new DefaultFeatureStoreNotification(this,
885
            DataStoreNotification.RESOURCE_CHANGED));
886
    }
887

    
888
    //
889
    // ====================================================================
890
    // Gestion de bloqueos
891
    //
892

    
893
    @Override
894
    public boolean isLocksSupported() {
895
        return this.provider.isLocksSupported();
896
    }
897

    
898
    @Override
899
    public FeatureLocks getLocks() throws DataException {
900
        if (!this.provider.isLocksSupported()) {
901
            LOG.warn("Locks not supported");
902
            return null;
903
        }
904
        if (locks == null) {
905
            this.locks = this.provider.createFeatureLocks();
906
        }
907
        return locks;
908
    }
909

    
910
    //
911
    // ====================================================================
912
    // Interface Observable
913
    //
914

    
915
    @Override
916
    public void disableNotifications() {
917
        this.delegateObservable.disableNotifications();
918

    
919
    }
920

    
921
    @Override
922
    public void enableNotifications() {
923
        this.delegateObservable.enableNotifications();
924
    }
925

    
926
    @Override
927
    public void beginComplexNotification() {
928
        this.delegateObservable.beginComplexNotification();
929

    
930
    }
931

    
932
    @Override
933
    public void endComplexNotification() {
934
        this.delegateObservable.endComplexNotification();
935

    
936
    }
937

    
938
    @Override
939
    public void addObserver(Observer observer) {
940
        if (delegateObservable != null) {
941
            this.delegateObservable.addObserver(observer);
942
        }
943
    }
944

    
945
    @Override
946
    public void deleteObserver(Observer observer) {
947
        if (delegateObservable != null) {
948
            this.delegateObservable.deleteObserver(observer);
949
        }
950
    }
951

    
952
    @Override
953
    public void deleteObservers() {
954
        this.delegateObservable.deleteObservers();
955

    
956
    }
957

    
958
    //
959
    // ====================================================================
960
    // Interface Observer
961
    //
962
    // Usado para observar:
963
    // - su seleccion
964
    // - sus bloqueos
965
    // - sus recursos
966
    //
967

    
968
    @Override
969
    public void update(Observable observable, Object notification) {
970
        if (observable instanceof FeatureSet) {
971
            if (observable == this.selection) {
972
                this.notifyChange(DataStoreNotification.SELECTION_CHANGE);
973
            } else if (observable == this.locks) {
974
                this.notifyChange(FeatureStoreNotification.LOCKS_CHANGE);
975
            }
976

    
977
        } else if (observable instanceof FeatureStoreProvider) {
978
            if (observable == this.provider) {
979

    
980
            }
981
        } else if (observable instanceof FeatureReferenceSelection) {
982
            if(notification instanceof String){
983
                    this.notifyChange((String)notification);
984
            }
985
        }
986
    }
987

    
988
    //
989
    // ====================================================================
990
    // Edicion
991
    //
992

    
993
    private void newVersionOfUpdate() {
994
        this.versionOfUpdate++;
995
    }
996

    
997
    private long currentVersionOfUpdate() {
998
        return this.versionOfUpdate;
999
    }
1000

    
1001
    private void checkInEditingMode() throws NeedEditingModeException {
1002
        if (mode != MODE_FULLEDIT) {
1003
            throw new NeedEditingModeException(this.getName());
1004
        }
1005
    }
1006

    
1007
    private void checkNotInAppendMode() throws IllegalStateException {
1008
        if (mode == MODE_APPEND) {
1009
                        throw new IllegalStateException("Error: store "
1010
                                        + this.getFullName() + " is in append mode");
1011
        }
1012
    }
1013

    
1014
    private void checkIsOwnFeature(Feature feature)
1015
        throws IllegalFeatureException {
1016
        if (((DefaultFeature) feature).getStore() != this) {
1017
            throw new IllegalFeatureException(this.getName());
1018
        }
1019
        // FIXME: fixFeatureType no vale para el checkIsOwnFeature
1020
        // fixFeatureType((DefaultFeatureType) feature.getType());
1021
    }
1022

    
1023
    private void exitEditingMode() {
1024
        if (commands != null) {
1025
            commands.clear();
1026
            commands = null;
1027
        }
1028

    
1029
        if (featureTypeManager != null) {
1030
            featureTypeManager.dispose();
1031
            featureTypeManager = null;
1032

    
1033
        }
1034

    
1035
        // TODO implementar un dispose para estos dos
1036
        featureManager = null;
1037
        spatialManager = null;
1038

    
1039
        featureCount = null;
1040

    
1041
        mode = MODE_QUERY;
1042
        hasStrongChanges = true; // Lo deja a true por si las moscas
1043
        hasInserts = true;
1044
    }
1045

    
1046
    @Override
1047
    synchronized public void edit() throws DataException {
1048
        edit(MODE_FULLEDIT);
1049
    }
1050

    
1051
    @Override
1052
    synchronized public void edit(int mode) throws DataException {
1053
        LOG.debug("Starting editing in mode: {}", mode);
1054
        try {
1055
            if (this.mode != MODE_QUERY) {
1056
                throw new AlreadyEditingException(this.getName());
1057
            }
1058
            if (!this.provider.supportsAppendMode()) {
1059
                mode = MODE_FULLEDIT;
1060
            }
1061
            switch (mode) {
1062
            case MODE_QUERY:
1063
                throw new IllegalStateException(this.getName());
1064

    
1065
            case MODE_FULLEDIT:
1066
                if (!this.transforms.isEmpty()) {
1067
                    throw new IllegalStateException(this.getName());
1068
                }
1069
                notifyChange(FeatureStoreNotification.BEFORE_STARTEDITING);
1070
                invalidateIndexes();
1071
                featureManager =
1072
                    new FeatureManager(new MemoryExpansionAdapter());
1073
                featureTypeManager =
1074
                    new FeatureTypeManager(this, new MemoryExpansionAdapter());
1075
                spatialManager =
1076
                    new SpatialManager(this, provider.getEnvelope());
1077

    
1078
                commands =
1079
                    new DefaultFeatureCommandsStack(this, featureManager,
1080
                        spatialManager, featureTypeManager);
1081
                this.mode = MODE_FULLEDIT;
1082
                hasStrongChanges = false;
1083
                hasInserts = false;
1084
                notifyChange(FeatureStoreNotification.AFTER_STARTEDITING);
1085
                break;
1086
            case MODE_APPEND:
1087
                if (!this.transforms.isEmpty()) {
1088
                    throw new IllegalStateException(this.getName());
1089
                }
1090
                notifyChange(FeatureStoreNotification.BEFORE_STARTEDITING);
1091
                invalidateIndexes();
1092
                this.provider.beginAppend();
1093
                this.mode = MODE_APPEND;
1094
                hasInserts = false;
1095
                notifyChange(FeatureStoreNotification.AFTER_STARTEDITING);
1096
                break;
1097
            }
1098
        } catch (Exception e) {
1099
            throw new StoreEditException(e, this.getName());
1100
        }
1101
    }
1102

    
1103
    private void invalidateIndexes() {
1104
        setIndexesValidStatus(false);
1105
    }
1106

    
1107
    private void setIndexesValidStatus(boolean valid) {
1108
        FeatureIndexes theIndexes = getIndexes();
1109
        LOG.debug("Setting the store indexes to valid status {}: {}", (valid
1110
            ? Boolean.TRUE : Boolean.FALSE), theIndexes);
1111
        for (Iterator iterator = theIndexes.iterator(); iterator.hasNext();) {
1112
            FeatureIndex index = (FeatureIndex) iterator.next();
1113
            if (index instanceof FeatureIndexProviderServices) {
1114
                FeatureIndexProviderServices indexServices =
1115
                    (FeatureIndexProviderServices) index;
1116
                indexServices.setValid(valid);
1117
            }
1118
        }
1119
    }
1120

    
1121
    private void updateIndexes() throws FeatureIndexException {
1122
        FeatureIndexes theIndexes = getIndexes();
1123
        LOG.debug("Refilling indexes: {}", theIndexes);
1124
        for (Iterator iterator = theIndexes.iterator(); iterator.hasNext();) {
1125
            FeatureIndex index = (FeatureIndex) iterator.next();
1126
            if (index instanceof FeatureIndexProviderServices) {
1127
                FeatureIndexProviderServices indexServices =
1128
                    (FeatureIndexProviderServices) index;
1129
                indexServices.fill(true, null);
1130
            }
1131
        }
1132
    }
1133

    
1134
    private void waitForIndexes() {
1135
        FeatureIndexes theIndexes = getIndexes();
1136
        LOG.debug("Waiting for indexes to finish filling: {}", theIndexes);
1137
        for (Iterator iterator = theIndexes.iterator(); iterator.hasNext();) {
1138
            FeatureIndex index = (FeatureIndex) iterator.next();
1139
            if (index instanceof FeatureIndexProviderServices) {
1140
                FeatureIndexProviderServices indexServices =
1141
                    (FeatureIndexProviderServices) index;
1142
                indexServices.waitForIndex();
1143
            }
1144
        }
1145
    }
1146

    
1147
    private void disposeIndexes() {
1148
        FeatureIndexes theIndexes = getIndexes();
1149
        LOG.debug("Disposing indexes: {}", theIndexes);
1150
        for (Iterator iterator = theIndexes.iterator(); iterator.hasNext();) {
1151
            FeatureIndex index = (FeatureIndex) iterator.next();
1152
            if (index instanceof FeatureIndexProviderServices) {
1153
                FeatureIndexProviderServices indexServices =
1154
                    (FeatureIndexProviderServices) index;
1155
                indexServices.dispose();
1156
            }
1157
        }
1158
    }
1159

    
1160
    @Override
1161
    public boolean isEditing() {
1162
        return mode == MODE_FULLEDIT;
1163
    }
1164

    
1165
    @Override
1166
    public boolean isAppending() {
1167
        return mode == MODE_APPEND;
1168
    }
1169

    
1170
    @Override
1171
    synchronized public void update(EditableFeatureType type)
1172
        throws DataException {
1173
        try {
1174
            checkInEditingMode();
1175
            if (type == null) {
1176
                throw new NullFeatureTypeException(getName());
1177
            }
1178
            // FIXME: Comprobar que es un featureType aceptable.
1179
            notifyChange(FeatureStoreNotification.BEFORE_UPDATE_TYPE, type);
1180
            newVersionOfUpdate();
1181

    
1182
            FeatureType oldt = type.getSource().getCopy();
1183
            FeatureType newt = type.getCopy();
1184
            commands.update(newt, oldt);
1185

    
1186
            if (((DefaultEditableFeatureType) type).hasStrongChanges()) {
1187
                hasStrongChanges = true;
1188
            }
1189
            notifyChange(FeatureStoreNotification.AFTER_UPDATE_TYPE, type);
1190
        } catch (Exception e) {
1191
            throw new StoreUpdateFeatureTypeException(e, this.getName());
1192
        }
1193
    }
1194

    
1195
    @Override
1196
    public void delete(Feature feature) throws DataException {
1197
        this.commands.delete(feature);
1198
    }
1199

    
1200
    synchronized public void doDelete(Feature feature) throws DataException {
1201
        try {
1202
            checkInEditingMode();
1203
            checkIsOwnFeature(feature);
1204
            if (feature instanceof EditableFeature) {
1205
                throw new StoreDeleteEditableFeatureException(getName());
1206
            }
1207
            notifyChange(FeatureStoreNotification.BEFORE_DELETE, feature);
1208

    
1209
            //Update the featureManager and the spatialManager
1210
            featureManager.delete(feature.getReference());
1211
            spatialManager.deleteFeature(feature);
1212

    
1213
            newVersionOfUpdate();
1214
            hasStrongChanges = true;
1215
            notifyChange(FeatureStoreNotification.AFTER_DELETE, feature);
1216
        } catch (Exception e) {
1217
            throw new StoreDeleteFeatureException(e, this.getName());
1218
        }
1219
    }
1220

    
1221
    private static EditableFeature lastChangedFeature = null;
1222

    
1223
    @Override
1224
    public synchronized void insert(EditableFeature feature)
1225
        throws DataException {
1226
        LOG.debug("In editing mode {}, insert feature: {}", mode, feature);
1227
        try {
1228
            switch (mode) {
1229
            case MODE_QUERY:
1230
                throw new NeedEditingModeException(this.getName());
1231

    
1232
            case MODE_APPEND:
1233
                checkIsOwnFeature(feature);
1234
                if (feature.getSource() != null) {
1235
                    throw new NoNewFeatureInsertException(this.getName());
1236
                }
1237
                this.featureCount = null;
1238
                notifyChange(FeatureStoreNotification.BEFORE_INSERT, feature);
1239
                feature.validate(Feature.UPDATE);
1240
                provider.append(((DefaultEditableFeature) feature).getData());
1241
                hasStrongChanges = true;
1242
                hasInserts = true;
1243
                notifyChange(FeatureStoreNotification.AFTER_INSERT, feature);
1244
                break;
1245

    
1246
            case MODE_FULLEDIT:
1247
                if (feature.getSource() != null) {
1248
                    throw new NoNewFeatureInsertException(this.getName());
1249
                }
1250
                commands.insert(feature);
1251
            }
1252
        } catch (Exception e) {
1253
            throw new StoreInsertFeatureException(e, this.getName());
1254
        }
1255
    }
1256

    
1257
    synchronized public void doInsert(EditableFeature feature)
1258
        throws DataException {
1259
        checkIsOwnFeature(feature);
1260

    
1261
        waitForIndexes();
1262

    
1263
        notifyChange(FeatureStoreNotification.BEFORE_INSERT, feature);
1264
        newVersionOfUpdate();
1265
        if ((lastChangedFeature == null)
1266
            || (lastChangedFeature.getSource() != feature.getSource())) {
1267
            lastChangedFeature = feature;
1268
            feature.validate(Feature.UPDATE);
1269
            lastChangedFeature = null;
1270
        }
1271
        //Update the featureManager and the spatialManager
1272
        ((DefaultEditableFeature) feature).setInserted(true);
1273
        DefaultFeature newFeature = (DefaultFeature) feature.getNotEditableCopy();
1274

    
1275

    
1276
        featureManager.add(newFeature);
1277
        spatialManager.insertFeature(newFeature);
1278

    
1279
        hasStrongChanges = true;
1280
        hasInserts = true;
1281
        notifyChange(FeatureStoreNotification.AFTER_INSERT, feature);
1282
    }
1283

    
1284
    @Override
1285
    public void update(EditableFeature feature)
1286
    throws DataException {
1287
        if ((feature).getSource() == null) {
1288
            insert(feature);
1289
            return;
1290
        }
1291
        commands.update(feature, feature.getSource());
1292
    }
1293

    
1294
    synchronized public void doUpdate(EditableFeature feature, Feature oldFeature)
1295
        throws DataException {
1296
        try {
1297
            checkInEditingMode();
1298
            checkIsOwnFeature(feature);
1299
            notifyChange(FeatureStoreNotification.BEFORE_UPDATE, feature);
1300
            newVersionOfUpdate();
1301
            if ((lastChangedFeature == null)
1302
                || (lastChangedFeature.getSource() != feature.getSource())) {
1303
                lastChangedFeature = feature;
1304
                feature.validate(Feature.UPDATE);
1305
                lastChangedFeature = null;
1306
            }
1307

    
1308
            //Update the featureManager and the spatialManager
1309
            Feature newf = feature.getNotEditableCopy();
1310
            featureManager.update(newf, oldFeature);
1311
            spatialManager.updateFeature(newf, oldFeature);
1312

    
1313
            hasStrongChanges = true;
1314
            notifyChange(FeatureStoreNotification.AFTER_UPDATE, feature);
1315
        } catch (Exception e) {
1316
            throw new StoreUpdateFeatureException(e, this.getName());
1317
        }
1318
    }
1319

    
1320
    @Override
1321
    synchronized public void redo() throws RedoException {
1322
        Command redo = commands.getNextRedoCommand();
1323
        try {
1324
            checkInEditingMode();
1325
        } catch (NeedEditingModeException ex) {
1326
            throw new RedoException(redo, ex);
1327
        }
1328
        notifyChange(FeatureStoreNotification.BEFORE_REDO, redo);
1329
        newVersionOfUpdate();
1330
        commands.redo();
1331
        hasStrongChanges = true;
1332
        notifyChange(FeatureStoreNotification.AFTER_REDO, redo);
1333
    }
1334

    
1335
    @Override
1336
    synchronized public void undo() throws UndoException {
1337
        Command undo = commands.getNextUndoCommand();
1338
        try {
1339
            checkInEditingMode();
1340
        } catch (NeedEditingModeException ex) {
1341
            throw new UndoException(undo, ex);
1342
        }
1343
        notifyChange(FeatureStoreNotification.BEFORE_UNDO, undo);
1344
        newVersionOfUpdate();
1345
        commands.undo();
1346
        hasStrongChanges = true;
1347
        notifyChange(FeatureStoreNotification.AFTER_UNDO, undo);
1348
    }
1349

    
1350
    @Override
1351
    public List getRedoInfos() {
1352
        if (isEditing() && (commands != null)) {
1353
            return commands.getRedoInfos();
1354
        } else {
1355
            return null;
1356
        }
1357
    }
1358

    
1359
    @Override
1360
    public List getUndoInfos() {
1361
        if (isEditing() && (commands != null)) {
1362
            return commands.getUndoInfos();
1363
        } else {
1364
            return null;
1365
        }
1366
    }
1367

    
1368
    public synchronized FeatureCommandsStack getCommandsStack()
1369
        throws DataException {
1370
        checkInEditingMode();
1371
        return commands;
1372
    }
1373

    
1374
    @Override
1375
    synchronized public void cancelEditing() throws DataException {
1376
        spatialManager.cancelModifies();
1377
        try {
1378
            checkInEditingMode();
1379

    
1380
            boolean clearSelection = this.hasStrongChanges;
1381
            if (this.selection instanceof FeatureReferenceSelection) {
1382
                clearSelection = this.hasInserts;
1383
            }
1384
            notifyChange(FeatureStoreNotification.BEFORE_CANCELEDITING);
1385
            exitEditingMode();
1386
            if (clearSelection) {
1387
                ((FeatureSelection) this.getSelection()).deselectAll();
1388
            }
1389
            updateIndexes();
1390
            notifyChange(FeatureStoreNotification.AFTER_CANCELEDITING);
1391
        } catch (Exception e) {
1392
            throw new StoreCancelEditingException(e, this.getName());
1393
        }
1394
    }
1395

    
1396
    @Override
1397
    synchronized public void finishEditing() throws DataException {
1398
        LOG.debug("finish editing of mode: {}", mode);
1399
        try {
1400

    
1401
            /*
1402
             * Selection needs to be cleared when editing stops
1403
             * to prevent conflicts with selection remaining from
1404
             * editing mode.
1405
             */
1406
//            ((FeatureSelection) this.getSelection()).deselectAll();
1407

    
1408
            switch (mode) {
1409
            case MODE_QUERY:
1410
                throw new NeedEditingModeException(this.getName());
1411

    
1412
            case MODE_APPEND:
1413
                ((FeatureSelection) this.getSelection()).deselectAll();
1414
                notifyChange(FeatureStoreNotification.BEFORE_FINISHEDITING);
1415
                provider.endAppend();
1416
                exitEditingMode();
1417
                updateIndexes();
1418
                notifyChange(FeatureStoreNotification.AFTER_FINISHEDITING);
1419
                break;
1420

    
1421
            case MODE_FULLEDIT:
1422
                if (hasStrongChanges && !this.allowWrite()) {
1423
                    throw new WriteNotAllowedException(getName());
1424
                }
1425

    
1426
                if(featureManager.isSelectionCompromised()) {
1427
                    ((FeatureSelection) this.getSelection()).deselectAll();
1428
                };
1429

    
1430
                notifyChange(FeatureStoreNotification.BEFORE_FINISHEDITING);
1431
                if (hasStrongChanges) {
1432
                    validateFeatures(Feature.FINISH_EDITING);
1433

    
1434
                    /*
1435
                     * This will throw a PerformEditingExceptionif the provider
1436
                     * does not accept the changes (for example, an invalid field name)
1437
                     */
1438
                    provider.performChanges(featureManager.getDeleted(),
1439
                        featureManager.getInserted(),
1440
                        featureManager.getUpdated(),
1441
                        featureTypeManager.getFeatureTypesChanged());
1442
                }
1443
                exitEditingMode();
1444
                updateIndexes();
1445
                notifyChange(FeatureStoreNotification.AFTER_FINISHEDITING);
1446
                break;
1447
            }
1448
        } catch (PerformEditingException pee) {
1449
            throw new WriteException(provider.getSourceId().toString(), pee);
1450
        } catch (Exception e) {
1451
            throw new FinishEditingException(e);
1452
        }
1453
    }
1454

    
1455
    /**
1456
     * Save changes in the provider without leaving the edit mode.
1457
     * Do not call observers to communicate a change of ediding mode.
1458
     * The operation's history is eliminated to prevent inconsistencies
1459
     * in the data.
1460
     *
1461
     * @throws DataException
1462
     */
1463
    @Override
1464
    synchronized public void commitChanges() throws DataException {
1465
      LOG.debug("commitChanges of mode: {}", mode);
1466
      if( !canCommitChanges() ) {
1467
              throw new WriteNotAllowedException(getName());
1468
      }
1469
      try {
1470
        switch (mode) {
1471
        case MODE_QUERY:
1472
          throw new NeedEditingModeException(this.getName());
1473

    
1474
        case MODE_APPEND:
1475
          this.provider.endAppend();
1476
          exitEditingMode();
1477
          invalidateIndexes();
1478
          this.provider.beginAppend();
1479
          hasInserts = false;
1480
          break;
1481

    
1482
        case MODE_FULLEDIT:
1483
          if (hasStrongChanges && !this.allowWrite()) {
1484
            throw new WriteNotAllowedException(getName());
1485
          }
1486
          if (hasStrongChanges) {
1487
            validateFeatures(Feature.FINISH_EDITING);
1488
            provider.performChanges(featureManager.getDeleted(),
1489
              featureManager.getInserted(),
1490
              featureManager.getUpdated(),
1491
              featureTypeManager.getFeatureTypesChanged());
1492
          }
1493
          invalidateIndexes();
1494
          featureManager =
1495
            new FeatureManager(new MemoryExpansionAdapter());
1496
          featureTypeManager =
1497
            new FeatureTypeManager(this, new MemoryExpansionAdapter());
1498
          spatialManager =
1499
            new SpatialManager(this, provider.getEnvelope());
1500

    
1501
          commands =
1502
            new DefaultFeatureCommandsStack(this, featureManager,
1503
              spatialManager, featureTypeManager);
1504
          featureCount = null;
1505
          hasStrongChanges = false;
1506
          hasInserts = false;
1507
          break;
1508
        }
1509
      } catch (Exception e) {
1510
        throw new FinishEditingException(e);
1511
      }
1512
    }
1513

    
1514
    @Override
1515
    synchronized public boolean canCommitChanges() throws DataException {
1516
        if ( !this.allowWrite()) {
1517
                return false;
1518
        }
1519
            switch (mode) {
1520
            default:
1521
        case MODE_QUERY:
1522
                return false;
1523

    
1524
        case MODE_APPEND:
1525
                return true;
1526

    
1527
        case MODE_FULLEDIT:
1528
            List types = this.getFeatureTypes();
1529
            for( int i=0; i<types.size(); i++ ) {
1530
                    Object type = types.get(i);
1531
                    if( type instanceof DefaultEditableFeatureType ) {
1532
                            if( ((DefaultEditableFeatureType)type).hasStrongChanges() ) {
1533
                                    return false;
1534
                            }
1535
                    }
1536
            }
1537
            return true;
1538
            }
1539
    }
1540

    
1541
    @Override
1542
    public void beginEditingGroup(String description)
1543
        throws NeedEditingModeException {
1544
        checkInEditingMode();
1545
        commands.startComplex(description);
1546
    }
1547

    
1548
    @Override
1549
    public void endEditingGroup() throws NeedEditingModeException {
1550
        checkInEditingMode();
1551
        commands.endComplex();
1552
    }
1553

    
1554
    @Override
1555
    public boolean isAppendModeSupported() {
1556
        return this.provider.supportsAppendMode();
1557
    }
1558

    
1559
    @Override
1560
    public void export(DataServerExplorer explorer, String provider,
1561
        NewFeatureStoreParameters params) throws DataException {
1562

    
1563
        if (this.getFeatureTypes().size() != 1) {
1564
            throw new NotYetImplemented(
1565
                "export whith more than one type not yet implemented");
1566
        }
1567
        FeatureSelection featureSelection = (FeatureSelection) getSelection();
1568
        FeatureStore target = null;
1569
        FeatureSet features = null;
1570
        DisposableIterator iterator = null;
1571
        try {
1572
            FeatureType type = this.getDefaultFeatureType();
1573
            if ((params.getDefaultFeatureType() == null)
1574
                || (params.getDefaultFeatureType().size() == 0)) {
1575
                params.setDefaultFeatureType(type.getEditable());
1576

    
1577
            }
1578
            explorer.add(provider, params, true);
1579

    
1580
            DataManager manager = DALLocator.getDataManager();
1581
            target = (FeatureStore) manager.openStore(provider, params);
1582
            FeatureType targetType = target.getDefaultFeatureType();
1583

    
1584
            target.edit(MODE_APPEND);
1585
            FeatureAttributeDescriptor[] pk = type.getPrimaryKey();
1586
            if (featureSelection.getSize() > 0) {
1587
                features = this.getFeatureSelection();
1588
            } else {
1589
                if ((pk != null) && (pk.length > 0)) {
1590
                    FeatureQuery query = createFeatureQuery();
1591
                    for (int i = 0; i < pk.length; i++) {
1592
                        query.getOrder().add(pk[i].getName(), true);
1593
                    }
1594
                    features = this.getFeatureSet(query);
1595
                } else {
1596
                    features = this.getFeatureSet();
1597
                }
1598
            }
1599
            iterator = features.fastIterator();
1600
            while (iterator.hasNext()) {
1601
                DefaultFeature feature = (DefaultFeature) iterator.next();
1602
                target.insert(target.createNewFeature(targetType, feature));
1603
            }
1604
            target.finishEditing();
1605
            target.dispose();
1606
        } catch (Exception e) {
1607
            throw new DataExportException(e, params.toString());
1608
        } finally {
1609
            dispose(iterator);
1610
            dispose(features);
1611
            dispose(target);
1612
        }
1613
    }
1614

    
1615
    //
1616
    // ====================================================================
1617
    // Obtencion de datos
1618
    // getDataCollection, getFeatureCollection
1619
    //
1620

    
1621
    @Override
1622
    public DataSet getDataSet() throws DataException {
1623
        checkNotInAppendMode();
1624
        FeatureQuery query =
1625
            new DefaultFeatureQuery(this.getDefaultFeatureType());
1626
        return new DefaultFeatureSet(this, query);
1627
    }
1628

    
1629
    @Override
1630
    public DataSet getDataSet(DataQuery dataQuery) throws DataException {
1631
        checkNotInAppendMode();
1632
        return new DefaultFeatureSet(this, (FeatureQuery) dataQuery);
1633
    }
1634

    
1635
    @Override
1636
    public void getDataSet(Observer observer) throws DataException {
1637
        checkNotInAppendMode();
1638
        this.getFeatureSet(null, observer);
1639
    }
1640

    
1641
    @Override
1642
    public void getDataSet(DataQuery dataQuery, Observer observer)
1643
        throws DataException {
1644
        checkNotInAppendMode();
1645
        this.getFeatureSet((FeatureQuery) dataQuery, observer);
1646
    }
1647

    
1648
    @Override
1649
    public FeatureSet getFeatureSet() throws DataException {
1650
        return this.getFeatureSet((FeatureQuery)null);
1651
    }
1652

    
1653
    @Override
1654
    public FeatureSet getFeatureSet(FeatureQuery featureQuery)
1655
        throws DataException {
1656
        checkNotInAppendMode();
1657
        if( featureQuery==null ) {
1658
            featureQuery = new DefaultFeatureQuery(this.getDefaultFeatureType());
1659
        }
1660
        return new DefaultFeatureSet(this, featureQuery);
1661
    }
1662

    
1663
    @Override
1664
    public List<Feature> getFeatures(FeatureQuery query, int pageSize)  {
1665
        try {
1666
            FeaturePagingHelper pager = this.dataManager.createFeaturePagingHelper(this, query, pageSize);
1667
            return pager.asList();
1668
        } catch (BaseException ex) {
1669
            throw new RuntimeException("Can't create the list of features.", ex);
1670
        }
1671
    }
1672

    
1673
    @Override
1674
    public List<Feature> getFeatures() {
1675
        return this.getFeatures(null, 500);
1676
    }
1677

    
1678
    @Override
1679
    public void accept(Visitor visitor) throws BaseException {
1680
        FeatureSet set = getFeatureSet();
1681
        try {
1682
            set.accept(visitor);
1683
        } finally {
1684
            set.dispose();
1685
        }
1686
    }
1687

    
1688
    @Override
1689
    public void accept(Visitor visitor, DataQuery dataQuery)
1690
        throws BaseException {
1691
        FeatureSet set = getFeatureSet((FeatureQuery) dataQuery);
1692
        try {
1693
            set.accept(visitor);
1694
        } finally {
1695
            set.dispose();
1696
        }
1697
    }
1698

    
1699
    public FeatureType getFeatureType(FeatureQuery featureQuery)
1700
        throws DataException {
1701
        DefaultFeatureType fType =
1702
            (DefaultFeatureType) this.getFeatureType(featureQuery
1703
                .getFeatureTypeId());
1704
        if( featureQuery.hasAttributeNames() || featureQuery.hasConstantsAttributeNames() ) {
1705
            return fType.getSubtype(featureQuery.getAttributeNames(), featureQuery.getConstantsAttributeNames() );
1706
        }
1707
        return fType;
1708
    }
1709

    
1710
    @Override
1711
    public void getFeatureSet(Observer observer) throws DataException {
1712
        checkNotInAppendMode();
1713
        this.getFeatureSet(null, observer);
1714
    }
1715

    
1716
    @Override
1717
    public void getFeatureSet(FeatureQuery query, Observer observer)
1718
        throws DataException {
1719
        class LoadInBackGround implements Runnable {
1720

    
1721
            private final FeatureStore store;
1722
            private final FeatureQuery query;
1723
            private final Observer observer;
1724

    
1725
            public LoadInBackGround(FeatureStore store, FeatureQuery query,
1726
                Observer observer) {
1727
                this.store = store;
1728
                this.query = query;
1729
                this.observer = observer;
1730
            }
1731

    
1732
            void notify(FeatureStoreNotification theNotification) {
1733
                observer.update(store, theNotification);
1734
            }
1735

    
1736
            @Override
1737
            public void run() {
1738
                FeatureSet set = null;
1739
                try {
1740
                    set = store.getFeatureSet(query);
1741
                    notify(new DefaultFeatureStoreNotification(store,
1742
                        FeatureStoreNotification.LOAD_FINISHED, set));
1743
                } catch (Exception e) {
1744
                    notify(new DefaultFeatureStoreNotification(store,
1745
                        FeatureStoreNotification.LOAD_FINISHED, e));
1746
                } finally {
1747
                    dispose(set);
1748
                }
1749
            }
1750
        }
1751

    
1752
        checkNotInAppendMode();
1753
        if (query == null) {
1754
            query = new DefaultFeatureQuery(this.getDefaultFeatureType());
1755
        }
1756
        LoadInBackGround task = new LoadInBackGround(this, query, observer);
1757
        Thread thread = new Thread(task, "Load Feature Set in background");
1758
        thread.start();
1759
    }
1760

    
1761
    @Override
1762
    public Feature getFeatureByReference(FeatureReference reference)
1763
        throws DataException {
1764
        checkNotInAppendMode();
1765
        DefaultFeatureReference ref = (DefaultFeatureReference) reference;
1766
        FeatureType featureType;
1767
        if (ref.getFeatureTypeId() == null) {
1768
            featureType = this.getDefaultFeatureType();
1769
        } else {
1770
            featureType = this.getFeatureType(ref.getFeatureTypeId());
1771
        }
1772
        return this.getFeatureByReference(reference, featureType);
1773
    }
1774

    
1775
    @Override
1776
    public Feature getFeatureByReference(FeatureReference reference,
1777
        FeatureType featureType) throws DataException {
1778
        checkNotInAppendMode();
1779
        featureType = fixFeatureType((DefaultFeatureType) featureType);
1780
        if (this.mode == MODE_FULLEDIT) {
1781
            Feature f = featureManager.get(reference, this, featureType);
1782
            if (f != null) {
1783
                return f;
1784
            }
1785
        }
1786

    
1787
        FeatureType sourceFeatureType = featureType;
1788
        if (!this.transforms.isEmpty()) {
1789
            sourceFeatureType = this.transforms.getSourceFeatureTypeFrom(featureType);
1790
        }
1791
        // TODO comprobar que el id es de este store
1792

    
1793
        DefaultFeature feature =
1794
            new DefaultFeature(this,
1795
                this.provider.getFeatureProviderByReference(
1796
                    (FeatureReferenceProviderServices) reference, sourceFeatureType));
1797

    
1798
        if (!this.transforms.isEmpty()) {
1799
            return this.transforms.applyTransform(feature, featureType);
1800
        }
1801
        return feature;
1802
    }
1803

    
1804
    //
1805
    // ====================================================================
1806
    // Gestion de features
1807
    //
1808

    
1809
    private FeatureType fixFeatureType(DefaultFeatureType type)
1810
        throws DataException {
1811
        FeatureType original = this.getDefaultFeatureType();
1812

    
1813
        if ((type == null) || type.equals(original)) {
1814
            return original;
1815
        } else {
1816
            if (!type.isSubtypeOf(original)) {
1817
                Iterator iter = this.getFeatureTypes().iterator();
1818
                FeatureType tmpType;
1819
                boolean found = false;
1820
                while (iter.hasNext()) {
1821
                    tmpType = (FeatureType) iter.next();
1822
                    if (type.equals(tmpType)) {
1823
                        return type;
1824

    
1825
                    } else
1826
                        if (type.isSubtypeOf(tmpType)) {
1827
                            found = true;
1828
                            original = tmpType;
1829
                            break;
1830
                        }
1831

    
1832
                }
1833
                if (!found) {
1834
                    throw new IllegalFeatureTypeException(getName());
1835
                }
1836
            }
1837
        }
1838

    
1839
        // Checks that type has all fields of pk
1840
        // else add the missing attributes at the end.
1841
        if (!original.hasOID()) {
1842
            // Gets original pk attributes
1843
            DefaultEditableFeatureType edOriginal =
1844
                (DefaultEditableFeatureType) original.getEditable();
1845
            FeatureAttributeDescriptor orgAttr;
1846
            Iterator edOriginalIter = edOriginal.iterator();
1847
            while (edOriginalIter.hasNext()) {
1848
                orgAttr = (FeatureAttributeDescriptor) edOriginalIter.next();
1849
                if (!orgAttr.isPrimaryKey()) {
1850
                    edOriginalIter.remove();
1851
                }
1852
            }
1853

    
1854
            // Checks if all pk attributes are in type
1855
            Iterator typeIterator;
1856
            edOriginalIter = edOriginal.iterator();
1857
            FeatureAttributeDescriptor attr;
1858
            while (edOriginalIter.hasNext()) {
1859
                orgAttr = (FeatureAttributeDescriptor) edOriginalIter.next();
1860
                typeIterator = type.iterator();
1861
                while (typeIterator.hasNext()) {
1862
                    attr = (FeatureAttributeDescriptor) typeIterator.next();
1863
                    if (attr.getName().equals(orgAttr.getName())) {
1864
                        edOriginalIter.remove();
1865
                        break;
1866
                    }
1867
                }
1868
            }
1869

    
1870
            // add missing pk attributes if any
1871
            if (edOriginal.size() > 0) {
1872
                boolean isEditable = type instanceof DefaultEditableFeatureType;
1873
                DefaultEditableFeatureType edType =
1874
                    (DefaultEditableFeatureType) original.getEditable();
1875
                edType.clear();
1876
                edType.addAll(type);
1877
                edType.addAll(edOriginal);
1878
                if (!isEditable) {
1879
                    type = (DefaultFeatureType) edType.getNotEditableCopy();
1880
                }
1881
            }
1882

    
1883
        }
1884

    
1885
        return type;
1886
    }
1887

    
1888
    @Override
1889
    public void validateFeatures(int mode) throws DataException {
1890
        FeatureSet collection = null;
1891
        DisposableIterator iter = null;
1892
        try {
1893
            checkNotInAppendMode();
1894
            collection = this.getFeatureSet();
1895
            iter = collection.fastIterator();
1896
            long previousVersionOfUpdate = currentVersionOfUpdate();
1897
            while (iter.hasNext()) {
1898
                ((DefaultFeature) iter.next()).validate(mode);
1899
                if (previousVersionOfUpdate != currentVersionOfUpdate()) {
1900
                    throw new ConcurrentDataModificationException(getName());
1901
                }
1902
            }
1903
        } catch (Exception e) {
1904
            throw new ValidateFeaturesException(e, getName());
1905
        } finally {
1906
            dispose(iter);
1907
            dispose(collection);
1908
        }
1909
    }
1910

    
1911
    @Override
1912
    public FeatureType getDefaultFeatureType() throws DataException {
1913
        try {
1914

    
1915
            if (isEditing()) {
1916
                FeatureType auxFeatureType =
1917
                    featureTypeManager.getType(defaultFeatureType.getId());
1918
                if (auxFeatureType != null) {
1919
                    return avoidEditable(auxFeatureType);
1920
                }
1921
            }
1922
            FeatureType type = this.transforms.getDefaultFeatureType();
1923
            if (type != null) {
1924
                return avoidEditable(type);
1925
            }
1926

    
1927
            return avoidEditable(defaultFeatureType);
1928

    
1929
        } catch (Exception e) {
1930
            throw new GetFeatureTypeException(e, getName());
1931
        }
1932
    }
1933

    
1934
    private FeatureType avoidEditable(FeatureType ft) {
1935
        if (ft instanceof EditableFeatureType) {
1936
            return ((EditableFeatureType) ft).getNotEditableCopy();
1937
        } else {
1938
            return ft;
1939
        }
1940
    }
1941

    
1942
    @Override
1943
    public FeatureType getFeatureType(String featureTypeId)
1944
        throws DataException {
1945
        if (featureTypeId == null) {
1946
            return this.getDefaultFeatureType();
1947
        }
1948
        try {
1949
            if (isEditing()) {
1950
                FeatureType auxFeatureType =
1951
                    featureTypeManager.getType(featureTypeId);
1952
                if (auxFeatureType != null) {
1953
                    return auxFeatureType;
1954
                }
1955
            }
1956
            FeatureType type = this.transforms.getFeatureType(featureTypeId);
1957
            if (type != null) {
1958
                return type;
1959
            }
1960
            Iterator iter = this.featureTypes.iterator();
1961
            while (iter.hasNext()) {
1962
                type = (FeatureType) iter.next();
1963
                if (type.getId().equals(featureTypeId)) {
1964
                    return type;
1965
                }
1966
            }
1967
            return null;
1968
        } catch (Exception e) {
1969
            throw new GetFeatureTypeException(e, getName());
1970
        }
1971
    }
1972

    
1973
    public FeatureType getProviderDefaultFeatureType() {
1974
        return defaultFeatureType;
1975
    }
1976

    
1977
    @Override
1978
    public List getFeatureTypes() throws DataException {
1979
        try {
1980
            List types;
1981
            if (isEditing()) {
1982
                types = new ArrayList();
1983
                Iterator it = featureTypes.iterator();
1984
                while (it.hasNext()) {
1985
                    FeatureType type = (FeatureType) it.next();
1986
                    FeatureType typeaux =
1987
                        featureTypeManager.getType(type.getId());
1988
                    if (typeaux != null) {
1989
                        types.add(typeaux);
1990
                    } else {
1991
                        types.add(type);
1992
                    }
1993
                }
1994
                it = featureTypeManager.newsIterator();
1995
                while (it.hasNext()) {
1996
                    FeatureType type = (FeatureType) it.next();
1997
                    types.add(type);
1998
                }
1999
            } else {
2000
                types = this.transforms.getFeatureTypes();
2001
                if (types == null) {
2002
                    types = featureTypes;
2003
                }
2004
            }
2005
            return Collections.unmodifiableList(types);
2006
        } catch (Exception e) {
2007
            throw new GetFeatureTypeException(e, getName());
2008
        }
2009
    }
2010

    
2011
    public List getProviderFeatureTypes() throws DataException {
2012
        return Collections.unmodifiableList(this.featureTypes);
2013
    }
2014

    
2015
    @Override
2016
    public Feature createFeature(FeatureProvider data) throws DataException {
2017
        DefaultFeature feature = new DefaultFeature(this, data);
2018
        return feature;
2019
    }
2020

    
2021
    public Feature createFeature(FeatureProvider data, FeatureType type)
2022
        throws DataException {
2023
        // FIXME: falta por implementar
2024
        // Comprobar si es un subtipo del feature de data
2025
        // y construir un feature usando el subtipo.
2026
        // Probablemente requiera generar una copia del data.
2027
        throw new NotYetImplemented();
2028
    }
2029

    
2030
    @Override
2031
    public EditableFeature createNewFeature(FeatureType type,
2032
        Feature defaultValues) throws DataException {
2033
        try {
2034
            FeatureProvider data = createNewFeatureProvider(type);
2035
            DefaultEditableFeature feature =
2036
                new DefaultEditableFeature(this, data);
2037
            feature.initializeValues(defaultValues);
2038
            data.setNew(true);
2039

    
2040
            return feature;
2041
        } catch (Exception e) {
2042
            throw new CreateFeatureException(e, getName());
2043
        }
2044
    }
2045

    
2046
    private FeatureProvider createNewFeatureProvider(FeatureType type)
2047
        throws DataException {
2048
        type = this.fixFeatureType((DefaultFeatureType) type);
2049
        FeatureProvider data = this.provider.createFeatureProvider(type);
2050
        data.setNew(true);
2051
        if (type.hasOID() && (data.getOID() == null)) {
2052
            data.setOID(this.provider.createNewOID());
2053
        } else {
2054
            data.setOID(this.getTemporalOID());
2055
        }
2056
        return data;
2057

    
2058
    }
2059

    
2060
    @Override
2061
    public EditableFeature createNewFeature(FeatureType type,
2062
        boolean defaultValues) throws DataException {
2063
        try {
2064
            FeatureProvider data = createNewFeatureProvider(type);
2065
            DefaultEditableFeature feature =
2066
                new DefaultEditableFeature(this, data);
2067
            if (defaultValues) {
2068
                feature.initializeValues();
2069
            }
2070
            return feature;
2071
        } catch (Exception e) {
2072
            throw new CreateFeatureException(e, getName());
2073
        }
2074
    }
2075

    
2076
    @Override
2077
    public EditableFeature createNewFeature(boolean defaultValues)
2078
        throws DataException {
2079
        return this.createNewFeature(this.getDefaultFeatureType(),
2080
            defaultValues);
2081
    }
2082

    
2083
    @Override
2084
    public EditableFeature createNewFeature() throws DataException {
2085
        return this.createNewFeature(this.getDefaultFeatureType(), true);
2086
    }
2087

    
2088
    @Override
2089
    public EditableFeature createNewFeature(Feature defaultValues) throws DataException {
2090
        FeatureType ft = this.getDefaultFeatureType();
2091
        EditableFeature f = this.createNewFeature(ft, false);
2092
                for( FeatureAttributeDescriptor desc : ft ) {
2093
                        try {
2094
                                f.set(desc.getName(), defaultValues.get(desc.getName()));
2095
                        } catch(Throwable th) {
2096
                                // Ignore
2097
                        }
2098
                }
2099
        return f;
2100
    }
2101

    
2102
    @Override
2103
    public EditableFeatureType createFeatureType() {
2104
        DefaultEditableFeatureType ftype = new DefaultEditableFeatureType();
2105
        return ftype;
2106
    }
2107

    
2108
    @Override
2109
    public EditableFeatureType createFeatureType(String id) {
2110
        DefaultEditableFeatureType ftype = new DefaultEditableFeatureType(id);
2111
        return ftype;
2112
    }
2113

    
2114
    //
2115
    // ====================================================================
2116
    // Index related methods
2117
    //
2118

    
2119
    @Override
2120
    public FeatureIndexes getIndexes() {
2121
        return this.indexes;
2122
    }
2123

    
2124
    @Override
2125
    public FeatureIndex createIndex(FeatureType featureType,
2126
        String attributeName, String indexName) throws DataException {
2127
        return createIndex(null, featureType, attributeName, indexName);
2128
    }
2129

    
2130
    @Override
2131
    public FeatureIndex createIndex(String indexTypeName,
2132
        FeatureType featureType, String attributeName, String indexName)
2133
        throws DataException {
2134

    
2135
        return createIndex(indexTypeName, featureType, attributeName,
2136
            indexName, false, null);
2137
    }
2138

    
2139
    @Override
2140
    public FeatureIndex createIndex(FeatureType featureType,
2141
        String attributeName, String indexName, Observer observer)
2142
        throws DataException {
2143
        return createIndex(null, featureType, attributeName, indexName,
2144
            observer);
2145
    }
2146

    
2147
    @Override
2148
    public FeatureIndex createIndex(String indexTypeName,
2149
        FeatureType featureType, String attributeName, String indexName,
2150
        final Observer observer) throws DataException {
2151

    
2152
        return createIndex(indexTypeName, featureType, attributeName,
2153
            indexName, true, observer);
2154
    }
2155

    
2156
    private FeatureIndex createIndex(String indexTypeName,
2157
        FeatureType featureType, String attributeName, String indexName,
2158
        boolean background, final Observer observer) throws DataException {
2159

    
2160
        checkNotInAppendMode();
2161
        FeatureIndexProviderServices index;
2162
        index = dataManager.createFeatureIndexProvider(indexTypeName, this,
2163
                featureType, indexName,
2164
                featureType.getAttributeDescriptor(attributeName));
2165

    
2166
        try {
2167
            index.fill(background, observer);
2168
        } catch (FeatureIndexException e) {
2169
            throw new InitializeException(index.getName(), e);
2170
        }
2171

    
2172
        ((DefaultFeatureIndexes) getIndexes()).addIndex(index);
2173
        return index;
2174
    }
2175

    
2176
    //
2177
    // ====================================================================
2178
    // Transforms related methods
2179
    //
2180

    
2181
    @Override
2182
    public FeatureStoreTransforms getTransforms() {
2183
        return this.transforms;
2184
    }
2185

    
2186
    @Override
2187
    public FeatureQuery createFeatureQuery() {
2188
        return new DefaultFeatureQuery();
2189
    }
2190

    
2191
    @Override
2192
    public DataQuery createQuery() {
2193
        return createFeatureQuery();
2194
    }
2195

    
2196
    //
2197
    // ====================================================================
2198
    // UndoRedo related methods
2199
    //
2200

    
2201
    @Override
2202
    public boolean canRedo() {
2203
        return commands.canRedo();
2204
    }
2205

    
2206
    @Override
2207
    public boolean canUndo() {
2208
        return commands.canUndo();
2209
    }
2210

    
2211
    @Override
2212
    public void redo(int num) throws RedoException {
2213
        for (int i = 0; i < num; i++) {
2214
            redo();
2215
        }
2216
    }
2217

    
2218
    @Override
2219
    public void undo(int num) throws UndoException {
2220
        for (int i = 0; i < num; i++) {
2221
            undo();
2222
        }
2223
    }
2224

    
2225
    //
2226
    // ====================================================================
2227
    // Metadata related methods
2228
    //
2229

    
2230
    @Override
2231
    public Object getMetadataID() {
2232
        return this.provider.getSourceId();
2233
    }
2234

    
2235
    @Override
2236
    public void delegate(DynObject dynObject) {
2237
        this.metadata.delegate(dynObject);
2238
    }
2239

    
2240
    @Override
2241
    public DynClass getDynClass() {
2242
        return this.metadata.getDynClass();
2243
    }
2244

    
2245
    @Override
2246
        public Object getDynValue(String name) throws DynFieldNotFoundException {
2247
                if( this.transforms.hasDynValue(name) ) {
2248
                        return this.transforms.getDynValue(name);
2249
                }
2250
                if (this.metadata.hasDynValue(name)) {
2251
                        return this.metadata.getDynValue(name);
2252
                }
2253
                if (METADATA_PROVIDER.equalsIgnoreCase(name)) {
2254
                        return this.provider.getProviderName();
2255
                } else if (METADATA_CONTAINERNAME.equalsIgnoreCase(name)) {
2256
                        return this.provider.getSourceId();
2257
                } else if (METADATA_FEATURETYPE.equalsIgnoreCase(name)) {
2258
                        try {
2259
                                return this.getDefaultFeatureType();
2260
                        } catch (DataException e) {
2261
                                return null;
2262
                        }
2263
                }
2264
                return this.metadata.getDynValue(name);
2265
        }
2266

    
2267
    @Override
2268
    public boolean hasDynValue(String name) {
2269
                if( this.transforms.hasDynValue(name) ) {
2270
                        return true;
2271
                }
2272
        return this.metadata.hasDynValue(name);
2273
    }
2274

    
2275
    @Override
2276
    public boolean hasDynMethod(String name) {
2277
        return ((DynObject_v2)this.metadata).hasDynMethod(name);
2278
    }
2279

    
2280
    @Override
2281
    public void implement(DynClass dynClass) {
2282
        this.metadata.implement(dynClass);
2283
    }
2284

    
2285
    @Override
2286
    public Object invokeDynMethod(String name, Object[] args)
2287
        throws DynMethodException {
2288
        return this.metadata.invokeDynMethod(this, name, args);
2289
    }
2290

    
2291
    @Override
2292
    public Object invokeDynMethod(int code, Object[] args)
2293
        throws DynMethodException {
2294
        return this.metadata.invokeDynMethod(this, code, args);
2295
    }
2296

    
2297
    @Override
2298
    public void setDynValue(String name, Object value)
2299
        throws DynFieldNotFoundException {
2300
                if( this.transforms.hasDynValue(name) ) {
2301
                        this.transforms.setDynValue(name, value);
2302
                        return;
2303
                }
2304
        this.metadata.setDynValue(name, value);
2305

    
2306
    }
2307

    
2308
    /*
2309
     * (non-Javadoc)
2310
     *
2311
     * @see org.gvsig.metadata.Metadata#getMetadataChildren()
2312
     */
2313
    @Override
2314
    public Set getMetadataChildren() {
2315
        return this.metadataChildren;
2316
    }
2317

    
2318
    /*
2319
     * (non-Javadoc)
2320
     *
2321
     * @see org.gvsig.metadata.Metadata#getMetadataName()
2322
     */
2323
    @Override
2324
    public String getMetadataName() {
2325
        return this.provider.getProviderName();
2326
    }
2327

    
2328
    public FeatureTypeManager getFeatureTypeManager() {
2329
        return this.featureTypeManager;
2330
    }
2331

    
2332
    @Override
2333
    public long getFeatureCount() throws DataException {
2334
        if (featureCount == null) {
2335
            featureCount = this.provider.getFeatureCount();
2336
        }
2337
        if (this.isEditing()) {
2338
            if(this.isAppending()) {
2339
                try{
2340
                    throw new IllegalStateException();
2341
                } catch(IllegalStateException e) {
2342
                    LOG.info("Call DefaultFeatureStore.getFeatureCount editing in mode APPEND");
2343
                    e.printStackTrace();
2344
                }
2345
                return -1;
2346
            } else {
2347
                return featureCount
2348
                    + this.featureManager.getDeltaSize();
2349
            }
2350
        }
2351
        return featureCount;
2352
    }
2353

    
2354
    private Long getTemporalOID() {
2355
        return this.temporalOid++;
2356
    }
2357

    
2358
    @Override
2359
    public FeatureType getProviderFeatureType(String featureTypeId) {
2360
        if (featureTypeId == null) {
2361
            return this.defaultFeatureType;
2362
        }
2363
        FeatureType type;
2364
        Iterator iter = this.featureTypes.iterator();
2365
        while (iter.hasNext()) {
2366
            type = (FeatureType) iter.next();
2367
            if (type.getId().equals(featureTypeId)) {
2368
                return type;
2369
            }
2370
        }
2371
        return null;
2372
    }
2373

    
2374
    @Override
2375
    public FeatureProvider getFeatureProviderFromFeature(Feature feature) {
2376
        return ((DefaultFeature) feature).getData();
2377
    }
2378

    
2379
    @Override
2380
    public DataStore getStore() {
2381
        return this;
2382
    }
2383

    
2384
    @Override
2385
    public FeatureStore getFeatureStore() {
2386
        return this;
2387
    }
2388

    
2389
    @Override
2390
    public void createCache(String name, DynObject parameters)
2391
        throws DataException {
2392
        cache = dataManager.createFeatureCacheProvider(name, parameters);
2393
        if (cache == null) {
2394
            throw new CreateException("FeaureCacheProvider", null);
2395
        }
2396
        cache.apply(this, provider);
2397
        provider = cache;
2398

    
2399
        featureCount = null;
2400
    }
2401

    
2402
    @Override
2403
    public FeatureCache getCache() {
2404
        return cache;
2405
    }
2406

    
2407
    @Override
2408
    public void clear() {
2409
        if (metadata != null) {
2410
            metadata.clear();
2411
        }
2412
    }
2413

    
2414
    @Override
2415
    public String getName() {
2416
        if( this.provider != null ) {
2417
            return this.provider.getName();
2418
        }
2419
        if( this.parameters instanceof HasAFile ) {
2420
            return FilenameUtils.getName(((HasAFile)this.parameters).getFile().getName());
2421
        }
2422
        return "unknow";
2423
    }
2424

    
2425
    @Override
2426
    public String getFullName() {
2427
        try {
2428
            if( this.provider!=null ) {
2429
                return this.provider.getFullName();
2430
            }
2431
            if( this.parameters instanceof HasAFile ) {
2432
                return (((HasAFile)this.parameters).getFile().getAbsolutePath());
2433
            }
2434
            return null;
2435
        } catch(Throwable th) {
2436
            return null;
2437
        }
2438
    }
2439

    
2440
    @Override
2441
    public String getProviderName() {
2442
        if( this.provider!=null ) {
2443
            return this.provider.getProviderName();
2444
        }
2445
        if( this.parameters != null ) {
2446
            return this.parameters.getDataStoreName();
2447
        }
2448
        return null;
2449

    
2450
    }
2451

    
2452
    @Override
2453
    public boolean isKnownEnvelope() {
2454
        return this.provider.isKnownEnvelope();
2455
    }
2456

    
2457
    @Override
2458
    public boolean hasRetrievedFeaturesLimit() {
2459
        return this.provider.hasRetrievedFeaturesLimit();
2460
    }
2461

    
2462
    @Override
2463
    public int getRetrievedFeaturesLimit() {
2464
        return this.provider.getRetrievedFeaturesLimit();
2465
    }
2466

    
2467
    @Override
2468
    public Interval getInterval() {
2469
        if( this.timeSupport!=null ) {
2470
            return this.timeSupport.getInterval();
2471
        }
2472
        return this.provider.getInterval();
2473
    }
2474

    
2475
    @Override
2476
    public Collection getTimes() {
2477
        if( this.timeSupport!=null ) {
2478
            return this.timeSupport.getTimes();
2479
        }
2480
        return this.provider.getTimes();
2481
    }
2482

    
2483
    @Override
2484
    public Collection getTimes(Interval interval) {
2485
        if( this.timeSupport!=null ) {
2486
            return this.timeSupport.getTimes(interval);
2487
        }
2488
        return this.provider.getTimes(interval);
2489
    }
2490

    
2491
    public void setTimeSupport(FeatureStoreTimeSupport timeSupport) {
2492
        FeatureAttributeDescriptor attr;
2493
        DefaultFeatureType ft;
2494
        try {
2495
            ft = (DefaultFeatureType) this.getDefaultFeatureType();
2496
        } catch (DataException ex) {
2497
            throw new RuntimeException("Can't add time support, can't get the default feature type.", ex);
2498
        }
2499
        attr = ft.getAttributeDescriptor(timeSupport.getAttributeName());
2500
        if( attr != null ) {
2501
            throw new RuntimeException("Can't add time support, attribute '"+timeSupport.getAttributeName()+"'already exists.");
2502
        }
2503
        attr = ft.getAttributeDescriptor(timeSupport.getRequiredFieldNames()[0]);
2504
        if( attr != null ) {
2505
            throw new RuntimeException("Can't add time support over attribute '"+timeSupport.getAttributeName()+"', this attribute don't exists.");
2506
        }
2507
        DefaultEditableFeatureAttributeDescriptor attr2 = new DefaultEditableFeatureAttributeDescriptor();
2508
        attr2.setDataType(timeSupport.getDataType());
2509
        attr2.setIsTime(true);
2510
        attr2.setFeatureAttributeEmulator(timeSupport);
2511
        ft.add(attr2);
2512

    
2513
        this.timeSupport = timeSupport;
2514
    }
2515

    
2516
    @Override
2517
    public Object clone() throws CloneNotSupportedException {
2518

    
2519
        DataStoreParameters dsp = getParameters();
2520

    
2521
        DefaultFeatureStore cloned_store = null;
2522

    
2523
        try {
2524
            cloned_store = (DefaultFeatureStore) DALLocator.getDataManager().
2525
                openStore(this.getProviderName(), dsp);
2526
            if (transforms != null) {
2527
                cloned_store.transforms = (DefaultFeatureStoreTransforms) transforms.clone();
2528
                cloned_store.transforms.setStoreForClone(cloned_store);
2529
            }
2530
        } catch (Exception e) {
2531
            throw new CloneException(e);
2532
        }
2533
        return cloned_store;
2534

    
2535
    }
2536

    
2537
    @Override
2538
    public Feature getFeature(DynObject dynobject) {
2539
        if (dynobject instanceof DynObjectFeatureFacade){
2540
            Feature f = ((DynObjectFeatureFacade)dynobject).getFeature();
2541
            return f;
2542
        }
2543
        return null;
2544
    }
2545

    
2546
    @Override
2547
    public Iterator iterator() {
2548
        try {
2549
            return this.getFeatureSet().fastIterator();
2550
        } catch (DataException ex) {
2551
            throw new RuntimeException(ex);
2552
        }
2553
    }
2554

    
2555
    @Override
2556
    public ExpressionEvaluator createExpression() {
2557
        if( this.provider instanceof FeatureStoreProvider_v2 ) {
2558
            return ((FeatureStoreProvider_v2)this.provider).createExpression();
2559
        }
2560
        return new SQLBuilderBase();
2561
    }
2562

    
2563

    
2564
    public FeatureSet features() throws DataException {
2565
        // This is to avoid jython to create a property with this name
2566
        // to access method getFeatures.
2567
        return this.getFeatureSet();
2568
    }
2569

    
2570
    @Override
2571
    public DataStoreProviderFactory getProviderFactory() {
2572
        DataStoreProviderFactory factory = dataManager.getStoreProviderFactory(parameters.getDataStoreName());
2573
        return factory;
2574
    }
2575

    
2576
    @Override
2577
    public void useCache(String providerName, DynObject parameters) throws DataException {
2578
        throw new UnsupportedOperationException();
2579
    }
2580

    
2581
    @Override
2582
    public boolean isBroken() {
2583
        return this.state.isBroken();
2584
    }
2585

    
2586
    @Override
2587
    public Throwable getBreakingsCause() {
2588
            return this.state.getBreakingsCause();
2589
    }
2590

    
2591
    @Override
2592
    public SpatialIndex wrapSpatialIndex(SpatialIndex index) {
2593
//      FeatureStoreProviderFactory factory = (FeatureStoreProviderFactory) this.getProviderFactory();
2594
//      if( !factory.supportNumericOID() ) {
2595
//          return null;
2596
//      }
2597
      SpatialIndex wrappedIndex = new WrappedSpatialIndex(index, this);
2598
      return wrappedIndex;
2599
  }
2600
}