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

History | View | Annotate | Download (87.2 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.apache.commons.lang3.StringUtils;
42
import org.cresques.cts.IProjection;
43

    
44
import org.gvsig.fmap.dal.DALLocator;
45
import org.gvsig.fmap.dal.DataManager;
46
import org.gvsig.fmap.dal.DataQuery;
47
import org.gvsig.fmap.dal.DataServerExplorer;
48
import org.gvsig.fmap.dal.DataSet;
49
import org.gvsig.fmap.dal.DataStore;
50
import org.gvsig.fmap.dal.DataStoreNotification;
51
import org.gvsig.fmap.dal.DataStoreParameters;
52
import org.gvsig.fmap.dal.DataStoreProviderFactory;
53
import org.gvsig.fmap.dal.ExpressionBuilder;
54
import org.gvsig.fmap.dal.exception.CloneException;
55
import org.gvsig.fmap.dal.exception.CloseException;
56
import org.gvsig.fmap.dal.exception.CreateException;
57
import org.gvsig.fmap.dal.exception.DataException;
58
import org.gvsig.fmap.dal.exception.InitializeException;
59
import org.gvsig.fmap.dal.exception.OpenException;
60
import org.gvsig.fmap.dal.exception.ReadException;
61
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
62
import org.gvsig.fmap.dal.exception.WriteException;
63
import org.gvsig.fmap.dal.feature.EditableFeature;
64
import org.gvsig.fmap.dal.feature.EditableFeatureType;
65
import org.gvsig.fmap.dal.feature.Feature;
66
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
67
import org.gvsig.fmap.dal.feature.FeatureCache;
68
import org.gvsig.fmap.dal.feature.FeatureIndex;
69
import org.gvsig.fmap.dal.feature.FeatureIndexes;
70
import org.gvsig.fmap.dal.feature.FeatureLocks;
71
import org.gvsig.fmap.dal.feature.FeatureQuery;
72
import org.gvsig.fmap.dal.feature.FeatureReference;
73
import org.gvsig.fmap.dal.feature.FeatureReferenceSelection;
74
import org.gvsig.fmap.dal.feature.FeatureSelection;
75
import org.gvsig.fmap.dal.feature.FeatureSet;
76
import org.gvsig.fmap.dal.feature.FeatureStore;
77
import org.gvsig.fmap.dal.feature.FeatureStoreNotification;
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.SpatialIndex;
128
import org.gvsig.fmap.geom.primitive.Envelope;
129
import org.gvsig.metadata.MetadataLocator;
130
import org.gvsig.metadata.MetadataManager;
131
import org.gvsig.metadata.exceptions.MetadataException;
132
import org.gvsig.timesupport.Interval;
133
import org.gvsig.tools.ToolsLocator;
134
import org.gvsig.tools.dispose.DisposableIterator;
135
import org.gvsig.tools.dispose.impl.AbstractDisposable;
136
import org.gvsig.tools.dynobject.DelegatedDynObject;
137
import org.gvsig.tools.dynobject.DynClass;
138
import org.gvsig.tools.dynobject.DynObject;
139
import org.gvsig.tools.dynobject.DynObjectManager;
140
import org.gvsig.tools.dynobject.DynObject_v2;
141
import org.gvsig.tools.dynobject.DynStruct;
142
import org.gvsig.tools.dynobject.exception.DynFieldNotFoundException;
143
import org.gvsig.tools.dynobject.exception.DynMethodException;
144
import org.gvsig.tools.exception.BaseException;
145
import org.gvsig.tools.exception.NotYetImplemented;
146
import org.gvsig.tools.identitymanagement.SimpleIdentityManager;
147
import org.gvsig.tools.observer.Observable;
148
import org.gvsig.tools.observer.Observer;
149
import org.gvsig.tools.observer.impl.DelegateWeakReferencingObservable;
150
import org.gvsig.tools.persistence.PersistenceManager;
151
import org.gvsig.tools.persistence.Persistent;
152
import org.gvsig.tools.persistence.PersistentState;
153
import org.gvsig.tools.persistence.exception.PersistenceException;
154
import org.gvsig.tools.undo.RedoException;
155
import org.gvsig.tools.undo.UndoException;
156
import org.gvsig.tools.undo.command.Command;
157
import org.gvsig.tools.util.HasAFile;
158
import org.gvsig.tools.visitor.Visitor;
159

    
160
import org.slf4j.Logger;
161
import org.slf4j.LoggerFactory;
162

    
163
public class DefaultFeatureStore extends AbstractDisposable implements
164
    DataStoreInitializer2, FeatureStoreProviderServices, FeatureStore, Observer {
165

    
166
    private static final Logger LOG = LoggerFactory
167
        .getLogger(DefaultFeatureStore.class);
168

    
169
    private static final String PERSISTENCE_DEFINITION_NAME = "FeatureStore";
170

    
171
    private DataStoreParameters parameters = null;
172
    private FeatureSelection selection;
173
    private FeatureLocks locks;
174

    
175
    private DelegateWeakReferencingObservable delegateObservable =
176
        new DelegateWeakReferencingObservable(this);
177

    
178
    private FeatureCommandsStack commands;
179
    private FeatureTypeManager featureTypeManager;
180
    private FeatureManager featureManager;
181
    private SpatialManager spatialManager;
182

    
183
    private FeatureType defaultFeatureType = null;
184
    private List featureTypes = new ArrayList();
185

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

    
191
    private DefaultDataManager dataManager = null;
192

    
193
    private FeatureStoreProvider provider = null;
194

    
195
    private DefaultFeatureIndexes indexes;
196

    
197
    private DefaultFeatureStoreTransforms transforms;
198

    
199
    DelegatedDynObject metadata;
200

    
201
    private Set metadataChildren;
202

    
203
    private Long featureCount = null;
204

    
205
    private long temporalOid = 0;
206

    
207
    private FeatureCacheProvider cache;
208

    
209
    StateInformation state;
210

    
211
    FeatureStoreTimeSupport timeSupport;
212

    
213

    
214
    private class StateInformation extends HashMap<Object, Object> {
215

    
216
        private static final long serialVersionUID = 4109026189635185666L;
217

    
218
        private boolean broken;
219
        private Throwable breakingsCause;
220

    
221
        public StateInformation() {
222
            this.clear();
223
        }
224

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

    
232
        public boolean isBroken() {
233
            return this.broken;
234
        }
235

    
236
        public void broken() {
237
            this.broken = true;
238
        }
239

    
240
        public Throwable getBreakingsCause() {
241
            return this.breakingsCause;
242
        }
243

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

    
252

    
253

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

    
263
    public DefaultFeatureStore() {
264
        this.state = new StateInformation();
265
    }
266

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

    
271
        DynObjectManager dynManager = ToolsLocator.getDynObjectManager();
272

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

    
278
        this.dataManager = (DefaultDataManager) dataManager;
279

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

    
288
    }
289

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

    
298
    @Override
299
    public DataStoreParameters getParameters() {
300
        return parameters;
301
    }
302

    
303
    public int getMode() {
304
        return this.mode;
305
    }
306

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

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

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

    
322
    public FeatureManager getFeatureManager() {
323
        return this.featureManager;
324
    }
325

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

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

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

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

    
376
    @Override
377
    protected void doDispose() throws BaseException {
378
        if (this.mode != MODE_QUERY) {
379
            // TODO: Se puede hacer un dispose estando en edicion ?
380
            try {
381
                throw new IllegalStateException();
382
            } catch(Exception ex) {
383
                LOG.warn("Dispossing a store in editing/append mode ("+this.getFullName()+").",ex);
384
            }
385
        }
386
        this.notifyChange(DataStoreNotification.BEFORE_DISPOSE);
387
        this.disposeIndexes();
388
        if( this.provider!=null ) {
389
            this.provider.dispose();
390
        }
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
        if( theIndexes==null ) {
1151
            return;
1152
        }
1153
        for (Iterator iterator = theIndexes.iterator(); iterator.hasNext();) {
1154
            FeatureIndex index = (FeatureIndex) iterator.next();
1155
            if (index instanceof FeatureIndexProviderServices) {
1156
                FeatureIndexProviderServices indexServices =
1157
                    (FeatureIndexProviderServices) index;
1158
                indexServices.dispose();
1159
            }
1160
        }
1161
    }
1162

    
1163
    @Override
1164
    public boolean isEditing() {
1165
        return mode == MODE_FULLEDIT;
1166
    }
1167

    
1168
    @Override
1169
    public boolean isAppending() {
1170
        return mode == MODE_APPEND;
1171
    }
1172

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

    
1185
            FeatureType oldt = type.getSource().getCopy();
1186
            FeatureType newt = type.getCopy();
1187
            commands.update(newt, oldt);
1188

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

    
1198
    @Override
1199
    public void delete(Feature feature) throws DataException {
1200
        this.commands.delete(feature);
1201
    }
1202

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

    
1212
            //Update the featureManager and the spatialManager
1213
            featureManager.delete(feature.getReference());
1214
            spatialManager.deleteFeature(feature);
1215

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

    
1224
    private static EditableFeature lastChangedFeature = null;
1225

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

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

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

    
1260
    synchronized public void doInsert(EditableFeature feature)
1261
        throws DataException {
1262
        checkIsOwnFeature(feature);
1263

    
1264
        waitForIndexes();
1265

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

    
1278

    
1279
        featureManager.add(newFeature);
1280
        spatialManager.insertFeature(newFeature);
1281

    
1282
        hasStrongChanges = true;
1283
        hasInserts = true;
1284
        notifyChange(FeatureStoreNotification.AFTER_INSERT, feature);
1285
    }
1286

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

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

    
1311
            //Update the featureManager and the spatialManager
1312
            Feature newf = feature.getNotEditableCopy();
1313
            featureManager.update(newf, oldFeature);
1314
            spatialManager.updateFeature(newf, oldFeature);
1315

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

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

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

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

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

    
1371
    public synchronized FeatureCommandsStack getCommandsStack()
1372
        throws DataException {
1373
        checkInEditingMode();
1374
        return commands;
1375
    }
1376

    
1377
    @Override
1378
    synchronized public void cancelEditing() throws DataException {
1379
        spatialManager.cancelModifies();
1380
        try {
1381
            switch (mode) {
1382
            case MODE_QUERY:
1383
                throw new NeedEditingModeException(this.getName());
1384

    
1385
            case MODE_APPEND:
1386
                notifyChange(FeatureStoreNotification.BEFORE_CANCELEDITING);
1387
                provider.abortAppend();
1388
                exitEditingMode();
1389
                ((FeatureSelection) this.getSelection()).deselectAll();
1390
                updateIndexes();
1391
                notifyChange(FeatureStoreNotification.AFTER_CANCELEDITING);   
1392

    
1393
            case MODE_FULLEDIT:
1394
                boolean clearSelection = this.hasStrongChanges;
1395
                if (this.selection instanceof FeatureReferenceSelection) {
1396
                    clearSelection = this.hasInserts;
1397
                }
1398
                notifyChange(FeatureStoreNotification.BEFORE_CANCELEDITING);
1399
                exitEditingMode();
1400
                if (clearSelection) {
1401
                    ((FeatureSelection) this.getSelection()).deselectAll();
1402
                }
1403
                updateIndexes();
1404
                notifyChange(FeatureStoreNotification.AFTER_CANCELEDITING);   
1405
            }
1406
        } catch (Exception e) {
1407
            throw new StoreCancelEditingException(e, this.getName());
1408
        }
1409
    }
1410

    
1411
    @Override
1412
    synchronized public void finishEditing() throws DataException {
1413
        LOG.debug("finish editing of mode: {}", mode);
1414
        try {
1415

    
1416
            /*
1417
             * Selection needs to be cleared when editing stops
1418
             * to prevent conflicts with selection remaining from
1419
             * editing mode.
1420
             */
1421
//            ((FeatureSelection) this.getSelection()).deselectAll();
1422

    
1423
            switch (mode) {
1424
            case MODE_QUERY:
1425
                throw new NeedEditingModeException(this.getName());
1426

    
1427
            case MODE_APPEND:
1428
                if( selection!=null ) {
1429
                    selection = null;
1430
                }
1431
                notifyChange(FeatureStoreNotification.BEFORE_FINISHEDITING);
1432
                provider.endAppend();
1433
                exitEditingMode();
1434
                updateIndexes();
1435
                notifyChange(FeatureStoreNotification.AFTER_FINISHEDITING);
1436
                break;
1437

    
1438
            case MODE_FULLEDIT:
1439
                if (hasStrongChanges && !this.allowWrite()) {
1440
                    throw new WriteNotAllowedException(getName());
1441
                }
1442
                if(featureManager.isSelectionCompromised() && selection!=null ) {
1443
                    selection = null;
1444
                }
1445
                notifyChange(FeatureStoreNotification.BEFORE_FINISHEDITING);
1446
                if (hasStrongChanges) {
1447
                    validateFeatures(Feature.FINISH_EDITING);
1448

    
1449
                    /*
1450
                     * This will throw a PerformEditingExceptionif the provider
1451
                     * does not accept the changes (for example, an invalid field name)
1452
                     */
1453
                    provider.performChanges(featureManager.getDeleted(),
1454
                        featureManager.getInserted(),
1455
                        featureManager.getUpdated(),
1456
                        featureTypeManager.getFeatureTypesChanged());
1457
                }
1458
                exitEditingMode();
1459
                updateIndexes();
1460
                notifyChange(FeatureStoreNotification.AFTER_FINISHEDITING);
1461
                break;
1462
            }
1463
        } catch (PerformEditingException pee) {
1464
            throw new WriteException(provider.getSourceId().toString(), pee);
1465
        } catch (Exception e) {
1466
            throw new FinishEditingException(e);
1467
        }
1468
    }
1469

    
1470
    /**
1471
     * Save changes in the provider without leaving the edit mode.
1472
     * Do not call observers to communicate a change of ediding mode.
1473
     * The operation's history is eliminated to prevent inconsistencies
1474
     * in the data.
1475
     *
1476
     * @throws DataException
1477
     */
1478
    @Override
1479
    synchronized public void commitChanges() throws DataException {
1480
      LOG.debug("commitChanges of mode: {}", mode);
1481
      if( !canCommitChanges() ) {
1482
              throw new WriteNotAllowedException(getName());
1483
      }
1484
      try {
1485
        switch (mode) {
1486
        case MODE_QUERY:
1487
          throw new NeedEditingModeException(this.getName());
1488

    
1489
        case MODE_APPEND:
1490
          this.provider.endAppend();
1491
          exitEditingMode();
1492
          invalidateIndexes();
1493
          this.provider.beginAppend();
1494
          hasInserts = false;
1495
          break;
1496

    
1497
        case MODE_FULLEDIT:
1498
          if (hasStrongChanges && !this.allowWrite()) {
1499
            throw new WriteNotAllowedException(getName());
1500
          }
1501
          if (hasStrongChanges) {
1502
            validateFeatures(Feature.FINISH_EDITING);
1503
            provider.performChanges(featureManager.getDeleted(),
1504
              featureManager.getInserted(),
1505
              featureManager.getUpdated(),
1506
              featureTypeManager.getFeatureTypesChanged());
1507
          }
1508
          invalidateIndexes();
1509
          featureManager =
1510
            new FeatureManager(new MemoryExpansionAdapter());
1511
          featureTypeManager =
1512
            new FeatureTypeManager(this, new MemoryExpansionAdapter());
1513
          spatialManager =
1514
            new SpatialManager(this, provider.getEnvelope());
1515

    
1516
          commands =
1517
            new DefaultFeatureCommandsStack(this, featureManager,
1518
              spatialManager, featureTypeManager);
1519
          featureCount = null;
1520
          hasStrongChanges = false;
1521
          hasInserts = false;
1522
          break;
1523
        }
1524
      } catch (Exception e) {
1525
        throw new FinishEditingException(e);
1526
      }
1527
    }
1528

    
1529
    @Override
1530
    synchronized public boolean canCommitChanges() throws DataException {
1531
        if ( !this.allowWrite()) {
1532
                return false;
1533
        }
1534
            switch (mode) {
1535
            default:
1536
        case MODE_QUERY:
1537
                return false;
1538

    
1539
        case MODE_APPEND:
1540
                return true;
1541

    
1542
        case MODE_FULLEDIT:
1543
            List types = this.getFeatureTypes();
1544
            for( int i=0; i<types.size(); i++ ) {
1545
                    Object type = types.get(i);
1546
                    if( type instanceof DefaultEditableFeatureType ) {
1547
                            if( ((DefaultEditableFeatureType)type).hasStrongChanges() ) {
1548
                                    return false;
1549
                            }
1550
                    }
1551
            }
1552
            return true;
1553
            }
1554
    }
1555

    
1556
    @Override
1557
    public void beginEditingGroup(String description)
1558
        throws NeedEditingModeException {
1559
        checkInEditingMode();
1560
        commands.startComplex(description);
1561
    }
1562

    
1563
    @Override
1564
    public void endEditingGroup() throws NeedEditingModeException {
1565
        checkInEditingMode();
1566
        commands.endComplex();
1567
    }
1568

    
1569
    @Override
1570
    public boolean isAppendModeSupported() {
1571
        return this.provider.supportsAppendMode();
1572
    }
1573

    
1574
    @Override
1575
    public void export(DataServerExplorer explorer, String provider,
1576
        NewFeatureStoreParameters params) throws DataException {
1577

    
1578
        if (this.getFeatureTypes().size() != 1) {
1579
            throw new NotYetImplemented(
1580
                "export whith more than one type not yet implemented");
1581
        }
1582
        FeatureSelection featureSelection = (FeatureSelection) getSelection();
1583
        FeatureStore target = null;
1584
        FeatureSet features = null;
1585
        DisposableIterator iterator = null;
1586
        try {
1587
            FeatureType type = this.getDefaultFeatureType();
1588
            if ((params.getDefaultFeatureType() == null)
1589
                || (params.getDefaultFeatureType().size() == 0)) {
1590
                params.setDefaultFeatureType(type.getEditable());
1591

    
1592
            }
1593
            explorer.add(provider, params, true);
1594

    
1595
            DataManager manager = DALLocator.getDataManager();
1596
            target = (FeatureStore) manager.openStore(provider, params);
1597
            FeatureType targetType = target.getDefaultFeatureType();
1598

    
1599
            target.edit(MODE_APPEND);
1600
            FeatureAttributeDescriptor[] pk = type.getPrimaryKey();
1601
            if (featureSelection.getSize() > 0) {
1602
                features = this.getFeatureSelection();
1603
            } else {
1604
                if ((pk != null) && (pk.length > 0)) {
1605
                    FeatureQuery query = createFeatureQuery();
1606
                    for (int i = 0; i < pk.length; i++) {
1607
                        query.getOrder().add(pk[i].getName(), true);
1608
                    }
1609
                    features = this.getFeatureSet(query);
1610
                } else {
1611
                    features = this.getFeatureSet();
1612
                }
1613
            }
1614
            iterator = features.fastIterator();
1615
            while (iterator.hasNext()) {
1616
                DefaultFeature feature = (DefaultFeature) iterator.next();
1617
                target.insert(target.createNewFeature(targetType, feature));
1618
            }
1619
            target.finishEditing();
1620
            target.dispose();
1621
        } catch (Exception e) {
1622
            throw new DataExportException(e, params.toString());
1623
        } finally {
1624
            dispose(iterator);
1625
            dispose(features);
1626
            dispose(target);
1627
        }
1628
    }
1629

    
1630
    //
1631
    // ====================================================================
1632
    // Obtencion de datos
1633
    // getDataCollection, getFeatureCollection
1634
    //
1635

    
1636
    @Override
1637
    public DataSet getDataSet() throws DataException {
1638
        checkNotInAppendMode();
1639
        FeatureQuery query =
1640
            new DefaultFeatureQuery(this.getDefaultFeatureType());
1641
        return new DefaultFeatureSet(this, query);
1642
    }
1643

    
1644
    @Override
1645
    public DataSet getDataSet(DataQuery dataQuery) throws DataException {
1646
        checkNotInAppendMode();
1647
        return new DefaultFeatureSet(this, (FeatureQuery) dataQuery);
1648
    }
1649

    
1650
    @Override
1651
    public void getDataSet(Observer observer) throws DataException {
1652
        checkNotInAppendMode();
1653
        this.getFeatureSet(null, observer);
1654
    }
1655

    
1656
    @Override
1657
    public void getDataSet(DataQuery dataQuery, Observer observer)
1658
        throws DataException {
1659
        checkNotInAppendMode();
1660
        this.getFeatureSet((FeatureQuery) dataQuery, observer);
1661
    }
1662

    
1663
    @Override
1664
    public FeatureSet getFeatureSet() throws DataException {
1665
        return this.getFeatureSet((FeatureQuery)null);
1666
    }
1667

    
1668
    @Override
1669
    public FeatureSet getFeatureSet(FeatureQuery featureQuery)
1670
        throws DataException {
1671
        checkNotInAppendMode();
1672
        if( featureQuery==null ) {
1673
            featureQuery = new DefaultFeatureQuery(this.getDefaultFeatureType());
1674
        }
1675
        return new DefaultFeatureSet(this, featureQuery);
1676
    }
1677

    
1678
    @Override
1679
    public FeatureSet getFeatureSet(String filter) throws DataException {
1680
        return this.getFeatureSet(filter, null, true);
1681
    }
1682

    
1683
    @Override
1684
    public FeatureSet getFeatureSet(String filter, String sortBy) throws DataException {
1685
        return this.getFeatureSet(filter, sortBy, true);
1686
    }
1687

    
1688
    @Override
1689
    public FeatureSet getFeatureSet(String filter, String sortBy, boolean asc) throws DataException {
1690
        FeatureQuery query = this.createFeatureQuery();
1691
        if( !StringUtils.isEmpty(filter) ) {
1692
            query.setFilter(filter);
1693
        }
1694
        if( !StringUtils.isEmpty(sortBy) ) {
1695
            query.getOrder().add(sortBy, asc);
1696
        }
1697
        return this.getFeatureSet(query);
1698
    }
1699

    
1700
    @Override
1701
    public List<Feature> getFeatures(FeatureQuery query, int pageSize)  {
1702
        try {
1703
            FeaturePagingHelper pager = this.dataManager.createFeaturePagingHelper(this, query, pageSize);
1704
            return pager.asList();
1705
        } catch (BaseException ex) {
1706
            throw new RuntimeException("Can't create the list of features.", ex);
1707
        }
1708
    }
1709

    
1710
    @Override
1711
    public List<Feature> getFeatures() {
1712
        return this.getFeatures(null, 500);
1713
    }
1714

    
1715
    @Override
1716
    public void accept(Visitor visitor) throws BaseException {
1717
        FeatureSet set = getFeatureSet();
1718
        try {
1719
            set.accept(visitor);
1720
        } finally {
1721
            set.dispose();
1722
        }
1723
    }
1724

    
1725
    @Override
1726
    public void accept(Visitor visitor, DataQuery dataQuery)
1727
        throws BaseException {
1728
        FeatureSet set = getFeatureSet((FeatureQuery) dataQuery);
1729
        try {
1730
            set.accept(visitor);
1731
        } finally {
1732
            set.dispose();
1733
        }
1734
    }
1735

    
1736
    public FeatureType getFeatureType(FeatureQuery featureQuery)
1737
        throws DataException {
1738
        DefaultFeatureType fType =
1739
            (DefaultFeatureType) this.getFeatureType(featureQuery
1740
                .getFeatureTypeId());
1741
        if( featureQuery.hasAttributeNames() || featureQuery.hasConstantsAttributeNames() ) {
1742
            return fType.getSubtype(featureQuery.getAttributeNames(), featureQuery.getConstantsAttributeNames() );
1743
        }
1744
        return fType;
1745
    }
1746

    
1747
    @Override
1748
    public void getFeatureSet(Observer observer) throws DataException {
1749
        checkNotInAppendMode();
1750
        this.getFeatureSet(null, observer);
1751
    }
1752

    
1753
    @Override
1754
    public void getFeatureSet(FeatureQuery query, Observer observer)
1755
        throws DataException {
1756
        class LoadInBackGround implements Runnable {
1757

    
1758
            private final FeatureStore store;
1759
            private final FeatureQuery query;
1760
            private final Observer observer;
1761

    
1762
            public LoadInBackGround(FeatureStore store, FeatureQuery query,
1763
                Observer observer) {
1764
                this.store = store;
1765
                this.query = query;
1766
                this.observer = observer;
1767
            }
1768

    
1769
            void notify(FeatureStoreNotification theNotification) {
1770
                observer.update(store, theNotification);
1771
            }
1772

    
1773
            @Override
1774
            public void run() {
1775
                FeatureSet set = null;
1776
                try {
1777
                    set = store.getFeatureSet(query);
1778
                    notify(new DefaultFeatureStoreNotification(store,
1779
                        FeatureStoreNotification.LOAD_FINISHED, set));
1780
                } catch (Exception e) {
1781
                    notify(new DefaultFeatureStoreNotification(store,
1782
                        FeatureStoreNotification.LOAD_FINISHED, e));
1783
                } finally {
1784
                    dispose(set);
1785
                }
1786
            }
1787
        }
1788

    
1789
        checkNotInAppendMode();
1790
        if (query == null) {
1791
            query = new DefaultFeatureQuery(this.getDefaultFeatureType());
1792
        }
1793
        LoadInBackGround task = new LoadInBackGround(this, query, observer);
1794
        Thread thread = new Thread(task, "Load Feature Set in background");
1795
        thread.start();
1796
    }
1797

    
1798
    @Override
1799
    public Feature getFeatureByReference(FeatureReference reference)
1800
        throws DataException {
1801
        checkNotInAppendMode();
1802
        DefaultFeatureReference ref = (DefaultFeatureReference) reference;
1803
        FeatureType featureType;
1804
        if (ref.getFeatureTypeId() == null) {
1805
            featureType = this.getDefaultFeatureType();
1806
        } else {
1807
            featureType = this.getFeatureType(ref.getFeatureTypeId());
1808
        }
1809
        return this.getFeatureByReference(reference, featureType);
1810
    }
1811

    
1812
    @Override
1813
    public Feature getFeatureByReference(FeatureReference reference,
1814
        FeatureType featureType) throws DataException {
1815
        checkNotInAppendMode();
1816
        featureType = fixFeatureType((DefaultFeatureType) featureType);
1817
        if (this.mode == MODE_FULLEDIT) {
1818
            Feature f = featureManager.get(reference, this, featureType);
1819
            if (f != null) {
1820
                return f;
1821
            }
1822
        }
1823

    
1824
        FeatureType sourceFeatureType = featureType;
1825
        if (!this.transforms.isEmpty()) {
1826
            sourceFeatureType = this.transforms.getSourceFeatureTypeFrom(featureType);
1827
        }
1828
        // TODO comprobar que el id es de este store
1829

    
1830
        DefaultFeature feature =
1831
            new DefaultFeature(this,
1832
                this.provider.getFeatureProviderByReference(
1833
                    (FeatureReferenceProviderServices) reference, sourceFeatureType));
1834

    
1835
        if (!this.transforms.isEmpty()) {
1836
            return this.transforms.applyTransform(feature, featureType);
1837
        }
1838
        return feature;
1839
    }
1840

    
1841
    //
1842
    // ====================================================================
1843
    // Gestion de features
1844
    //
1845

    
1846
    private FeatureType fixFeatureType(DefaultFeatureType type)
1847
        throws DataException {
1848
        FeatureType original = this.getDefaultFeatureType();
1849

    
1850
        if ((type == null) || type.equals(original)) {
1851
            return original;
1852
        } else {
1853
            if (!type.isSubtypeOf(original)) {
1854
                Iterator iter = this.getFeatureTypes().iterator();
1855
                FeatureType tmpType;
1856
                boolean found = false;
1857
                while (iter.hasNext()) {
1858
                    tmpType = (FeatureType) iter.next();
1859
                    if (type.equals(tmpType)) {
1860
                        return type;
1861

    
1862
                    } else
1863
                        if (type.isSubtypeOf(tmpType)) {
1864
                            found = true;
1865
                            original = tmpType;
1866
                            break;
1867
                        }
1868

    
1869
                }
1870
                if (!found) {
1871
                    throw new IllegalFeatureTypeException(getName());
1872
                }
1873
            }
1874
        }
1875

    
1876
        // Checks that type has all fields of pk
1877
        // else add the missing attributes at the end.
1878
        if (!original.hasOID()) {
1879
            // Gets original pk attributes
1880
            DefaultEditableFeatureType edOriginal =
1881
                (DefaultEditableFeatureType) original.getEditable();
1882
            FeatureAttributeDescriptor orgAttr;
1883
            Iterator edOriginalIter = edOriginal.iterator();
1884
            while (edOriginalIter.hasNext()) {
1885
                orgAttr = (FeatureAttributeDescriptor) edOriginalIter.next();
1886
                if (!orgAttr.isPrimaryKey()) {
1887
                    edOriginalIter.remove();
1888
                }
1889
            }
1890

    
1891
            // Checks if all pk attributes are in type
1892
            Iterator typeIterator;
1893
            edOriginalIter = edOriginal.iterator();
1894
            FeatureAttributeDescriptor attr;
1895
            while (edOriginalIter.hasNext()) {
1896
                orgAttr = (FeatureAttributeDescriptor) edOriginalIter.next();
1897
                typeIterator = type.iterator();
1898
                while (typeIterator.hasNext()) {
1899
                    attr = (FeatureAttributeDescriptor) typeIterator.next();
1900
                    if (attr.getName().equals(orgAttr.getName())) {
1901
                        edOriginalIter.remove();
1902
                        break;
1903
                    }
1904
                }
1905
            }
1906

    
1907
            // add missing pk attributes if any
1908
            if (edOriginal.size() > 0) {
1909
                boolean isEditable = type instanceof DefaultEditableFeatureType;
1910
                DefaultEditableFeatureType edType =
1911
                    (DefaultEditableFeatureType) original.getEditable();
1912
                edType.clear();
1913
                edType.addAll(type);
1914
                edType.addAll(edOriginal);
1915
                if (!isEditable) {
1916
                    type = (DefaultFeatureType) edType.getNotEditableCopy();
1917
                }
1918
            }
1919

    
1920
        }
1921

    
1922
        return type;
1923
    }
1924

    
1925
    @Override
1926
    public void validateFeatures(int mode) throws DataException {
1927
        FeatureSet collection = null;
1928
        DisposableIterator iter = null;
1929
        try {
1930
            checkNotInAppendMode();
1931
            collection = this.getFeatureSet();
1932
            iter = collection.fastIterator();
1933
            long previousVersionOfUpdate = currentVersionOfUpdate();
1934
            while (iter.hasNext()) {
1935
                ((DefaultFeature) iter.next()).validate(mode);
1936
                if (previousVersionOfUpdate != currentVersionOfUpdate()) {
1937
                    throw new ConcurrentDataModificationException(getName());
1938
                }
1939
            }
1940
        } catch (Exception e) {
1941
            throw new ValidateFeaturesException(e, getName());
1942
        } finally {
1943
            dispose(iter);
1944
            dispose(collection);
1945
        }
1946
    }
1947

    
1948
    @Override
1949
    public FeatureType getDefaultFeatureType() throws DataException {
1950
        try {
1951

    
1952
            if (isEditing()) {
1953
                FeatureType auxFeatureType =
1954
                    featureTypeManager.getType(defaultFeatureType.getId());
1955
                if (auxFeatureType != null) {
1956
                    return avoidEditable(auxFeatureType);
1957
                }
1958
            }
1959
            FeatureType type = this.transforms.getDefaultFeatureType();
1960
            if (type != null) {
1961
                return avoidEditable(type);
1962
            }
1963

    
1964
            return avoidEditable(defaultFeatureType);
1965

    
1966
        } catch (Exception e) {
1967
            throw new GetFeatureTypeException(e, getName());
1968
        }
1969
    }
1970

    
1971
    private FeatureType avoidEditable(FeatureType ft) {
1972
        if (ft instanceof EditableFeatureType) {
1973
            return ((EditableFeatureType) ft).getNotEditableCopy();
1974
        } else {
1975
            return ft;
1976
        }
1977
    }
1978

    
1979
    @Override
1980
    public FeatureType getFeatureType(String featureTypeId)
1981
        throws DataException {
1982
        if (featureTypeId == null) {
1983
            return this.getDefaultFeatureType();
1984
        }
1985
        try {
1986
            if (isEditing()) {
1987
                FeatureType auxFeatureType =
1988
                    featureTypeManager.getType(featureTypeId);
1989
                if (auxFeatureType != null) {
1990
                    return auxFeatureType;
1991
                }
1992
            }
1993
            FeatureType type = this.transforms.getFeatureType(featureTypeId);
1994
            if (type != null) {
1995
                return type;
1996
            }
1997
            Iterator iter = this.featureTypes.iterator();
1998
            while (iter.hasNext()) {
1999
                type = (FeatureType) iter.next();
2000
                if (type.getId().equals(featureTypeId)) {
2001
                    return type;
2002
                }
2003
            }
2004
            return null;
2005
        } catch (Exception e) {
2006
            throw new GetFeatureTypeException(e, getName());
2007
        }
2008
    }
2009

    
2010
    public FeatureType getProviderDefaultFeatureType() {
2011
        return defaultFeatureType;
2012
    }
2013

    
2014
    @Override
2015
    public List getFeatureTypes() throws DataException {
2016
        try {
2017
            List types;
2018
            if (isEditing()) {
2019
                types = new ArrayList();
2020
                Iterator it = featureTypes.iterator();
2021
                while (it.hasNext()) {
2022
                    FeatureType type = (FeatureType) it.next();
2023
                    FeatureType typeaux =
2024
                        featureTypeManager.getType(type.getId());
2025
                    if (typeaux != null) {
2026
                        types.add(typeaux);
2027
                    } else {
2028
                        types.add(type);
2029
                    }
2030
                }
2031
                it = featureTypeManager.newsIterator();
2032
                while (it.hasNext()) {
2033
                    FeatureType type = (FeatureType) it.next();
2034
                    types.add(type);
2035
                }
2036
            } else {
2037
                types = this.transforms.getFeatureTypes();
2038
                if (types == null) {
2039
                    types = featureTypes;
2040
                }
2041
            }
2042
            return Collections.unmodifiableList(types);
2043
        } catch (Exception e) {
2044
            throw new GetFeatureTypeException(e, getName());
2045
        }
2046
    }
2047

    
2048
    public List getProviderFeatureTypes() throws DataException {
2049
        return Collections.unmodifiableList(this.featureTypes);
2050
    }
2051

    
2052
    @Override
2053
    public Feature createFeature(FeatureProvider data) throws DataException {
2054
        DefaultFeature feature = new DefaultFeature(this, data);
2055
        return feature;
2056
    }
2057

    
2058
    public Feature createFeature(FeatureProvider data, FeatureType type)
2059
        throws DataException {
2060
        // FIXME: falta por implementar
2061
        // Comprobar si es un subtipo del feature de data
2062
        // y construir un feature usando el subtipo.
2063
        // Probablemente requiera generar una copia del data.
2064
        throw new NotYetImplemented();
2065
    }
2066

    
2067
    @Override
2068
    public EditableFeature createNewFeature(FeatureType type,
2069
        Feature defaultValues) throws DataException {
2070
        try {
2071
            FeatureProvider data = createNewFeatureProvider(type);
2072
            DefaultEditableFeature feature =
2073
                new DefaultEditableFeature(this, data);
2074
            feature.initializeValues(defaultValues);
2075
            data.setNew(true);
2076

    
2077
            return feature;
2078
        } catch (Exception e) {
2079
            throw new CreateFeatureException(e, getName());
2080
        }
2081
    }
2082

    
2083
    private FeatureProvider createNewFeatureProvider(FeatureType type)
2084
        throws DataException {
2085
        type = this.fixFeatureType((DefaultFeatureType) type);
2086
        FeatureProvider data = this.provider.createFeatureProvider(type);
2087
        data.setNew(true);
2088
        if (type.hasOID() && (data.getOID() == null)) {
2089
            data.setOID(this.provider.createNewOID());
2090
        } else {
2091
            data.setOID(this.getTemporalOID());
2092
        }
2093
        return data;
2094

    
2095
    }
2096

    
2097
    @Override
2098
    public EditableFeature createNewFeature(FeatureType type,
2099
        boolean defaultValues) throws DataException {
2100
        try {
2101
            FeatureProvider data = createNewFeatureProvider(type);
2102
            DefaultEditableFeature feature =
2103
                new DefaultEditableFeature(this, data);
2104
            if (defaultValues) {
2105
                feature.initializeValues();
2106
            }
2107
            return feature;
2108
        } catch (Exception e) {
2109
            throw new CreateFeatureException(e, getName());
2110
        }
2111
    }
2112

    
2113
    @Override
2114
    public EditableFeature createNewFeature(boolean defaultValues)
2115
        throws DataException {
2116
        return this.createNewFeature(this.getDefaultFeatureType(),
2117
            defaultValues);
2118
    }
2119

    
2120
    @Override
2121
    public EditableFeature createNewFeature() throws DataException {
2122
        return this.createNewFeature(this.getDefaultFeatureType(), true);
2123
    }
2124

    
2125
    @Override
2126
    public EditableFeature createNewFeature(Feature defaultValues) throws DataException {
2127
        FeatureType ft = this.getDefaultFeatureType();
2128
        EditableFeature f = this.createNewFeature(ft, false);
2129
                for( FeatureAttributeDescriptor desc : ft ) {
2130
                        try {
2131
                                f.set(desc.getName(), defaultValues.get(desc.getName()));
2132
                        } catch(Throwable th) {
2133
                                // Ignore
2134
                        }
2135
                }
2136
        return f;
2137
    }
2138

    
2139
    @Override
2140
    public EditableFeatureType createFeatureType() {
2141
        EditableFeatureType ftype = this.dataManager.createFeatureType();
2142
        return ftype;
2143
    }
2144

    
2145
    @Override
2146
    public EditableFeatureType createFeatureType(String id) {
2147
        DefaultEditableFeatureType ftype = new DefaultEditableFeatureType(id);
2148
        return ftype;
2149
    }
2150

    
2151
    //
2152
    // ====================================================================
2153
    // Index related methods
2154
    //
2155

    
2156
    @Override
2157
    public FeatureIndexes getIndexes() {
2158
        return this.indexes;
2159
    }
2160

    
2161
    @Override
2162
    public FeatureIndex createIndex(FeatureType featureType,
2163
        String attributeName, String indexName) throws DataException {
2164
        return createIndex(null, featureType, attributeName, indexName);
2165
    }
2166

    
2167
    @Override
2168
    public FeatureIndex createIndex(String indexTypeName,
2169
        FeatureType featureType, String attributeName, String indexName)
2170
        throws DataException {
2171

    
2172
        return createIndex(indexTypeName, featureType, attributeName,
2173
            indexName, false, null);
2174
    }
2175

    
2176
    @Override
2177
    public FeatureIndex createIndex(FeatureType featureType,
2178
        String attributeName, String indexName, Observer observer)
2179
        throws DataException {
2180
        return createIndex(null, featureType, attributeName, indexName,
2181
            observer);
2182
    }
2183

    
2184
    @Override
2185
    public FeatureIndex createIndex(String indexTypeName,
2186
        FeatureType featureType, String attributeName, String indexName,
2187
        final Observer observer) throws DataException {
2188

    
2189
        return createIndex(indexTypeName, featureType, attributeName,
2190
            indexName, true, observer);
2191
    }
2192

    
2193
    private FeatureIndex createIndex(String indexTypeName,
2194
        FeatureType featureType, String attributeName, String indexName,
2195
        boolean background, final Observer observer) throws DataException {
2196

    
2197
        checkNotInAppendMode();
2198
        FeatureIndexProviderServices index;
2199
        index = dataManager.createFeatureIndexProvider(indexTypeName, this,
2200
                featureType, indexName,
2201
                featureType.getAttributeDescriptor(attributeName));
2202

    
2203
        try {
2204
            index.fill(background, observer);
2205
        } catch (FeatureIndexException e) {
2206
            throw new InitializeException(index.getName(), e);
2207
        }
2208

    
2209
        ((DefaultFeatureIndexes) getIndexes()).addIndex(index);
2210
        return index;
2211
    }
2212

    
2213
    //
2214
    // ====================================================================
2215
    // Transforms related methods
2216
    //
2217

    
2218
    @Override
2219
    public FeatureStoreTransforms getTransforms() {
2220
        return this.transforms;
2221
    }
2222

    
2223
    @Override
2224
    public FeatureQuery createFeatureQuery() {
2225
        return new DefaultFeatureQuery();
2226
    }
2227

    
2228
    @Override
2229
    public DataQuery createQuery() {
2230
        return createFeatureQuery();
2231
    }
2232

    
2233
    //
2234
    // ====================================================================
2235
    // UndoRedo related methods
2236
    //
2237

    
2238
    @Override
2239
    public boolean canRedo() {
2240
        return commands.canRedo();
2241
    }
2242

    
2243
    @Override
2244
    public boolean canUndo() {
2245
        return commands.canUndo();
2246
    }
2247

    
2248
    @Override
2249
    public void redo(int num) throws RedoException {
2250
        for (int i = 0; i < num; i++) {
2251
            redo();
2252
        }
2253
    }
2254

    
2255
    @Override
2256
    public void undo(int num) throws UndoException {
2257
        for (int i = 0; i < num; i++) {
2258
            undo();
2259
        }
2260
    }
2261

    
2262
    //
2263
    // ====================================================================
2264
    // Metadata related methods
2265
    //
2266

    
2267
    @Override
2268
    public Object getMetadataID() {
2269
        return this.provider.getSourceId();
2270
    }
2271

    
2272
    @Override
2273
    public void delegate(DynObject dynObject) {
2274
        this.metadata.delegate(dynObject);
2275
    }
2276

    
2277
    @Override
2278
    public DynClass getDynClass() {
2279
        return this.metadata.getDynClass();
2280
    }
2281

    
2282
    @Override
2283
        public Object getDynValue(String name) throws DynFieldNotFoundException {
2284
                if( this.transforms.hasDynValue(name) ) {
2285
                        return this.transforms.getDynValue(name);
2286
                }
2287
                if (this.metadata.hasDynValue(name)) {
2288
                        return this.metadata.getDynValue(name);
2289
                }
2290
                if (METADATA_PROVIDER.equalsIgnoreCase(name)) {
2291
                        return this.provider.getProviderName();
2292
                } else if (METADATA_CONTAINERNAME.equalsIgnoreCase(name)) {
2293
                        return this.provider.getSourceId();
2294
                } else if (METADATA_FEATURETYPE.equalsIgnoreCase(name)) {
2295
                        try {
2296
                                return this.getDefaultFeatureType();
2297
                        } catch (DataException e) {
2298
                                return null;
2299
                        }
2300
                }
2301
                return this.metadata.getDynValue(name);
2302
        }
2303

    
2304
    @Override
2305
    public boolean hasDynValue(String name) {
2306
                if( this.transforms.hasDynValue(name) ) {
2307
                        return true;
2308
                }
2309
        return this.metadata.hasDynValue(name);
2310
    }
2311

    
2312
    @Override
2313
    public boolean hasDynMethod(String name) {
2314
        return ((DynObject_v2)this.metadata).hasDynMethod(name);
2315
    }
2316

    
2317
    @Override
2318
    public void implement(DynClass dynClass) {
2319
        this.metadata.implement(dynClass);
2320
    }
2321

    
2322
    @Override
2323
    public Object invokeDynMethod(String name, Object[] args)
2324
        throws DynMethodException {
2325
        return this.metadata.invokeDynMethod(this, name, args);
2326
    }
2327

    
2328
    @Override
2329
    public Object invokeDynMethod(int code, Object[] args)
2330
        throws DynMethodException {
2331
        return this.metadata.invokeDynMethod(this, code, args);
2332
    }
2333

    
2334
    @Override
2335
    public void setDynValue(String name, Object value)
2336
        throws DynFieldNotFoundException {
2337
                if( this.transforms.hasDynValue(name) ) {
2338
                        this.transforms.setDynValue(name, value);
2339
                        return;
2340
                }
2341
        this.metadata.setDynValue(name, value);
2342

    
2343
    }
2344

    
2345
    /*
2346
     * (non-Javadoc)
2347
     *
2348
     * @see org.gvsig.metadata.Metadata#getMetadataChildren()
2349
     */
2350
    @Override
2351
    public Set getMetadataChildren() {
2352
        return this.metadataChildren;
2353
    }
2354

    
2355
    /*
2356
     * (non-Javadoc)
2357
     *
2358
     * @see org.gvsig.metadata.Metadata#getMetadataName()
2359
     */
2360
    @Override
2361
    public String getMetadataName() {
2362
        return this.provider.getProviderName();
2363
    }
2364

    
2365
    public FeatureTypeManager getFeatureTypeManager() {
2366
        return this.featureTypeManager;
2367
    }
2368

    
2369
    @Override
2370
    public long getFeatureCount() throws DataException {
2371
        if (featureCount == null) {
2372
            featureCount = this.provider.getFeatureCount();
2373
        }
2374
        if (this.isEditing()) {
2375
            if(this.isAppending()) {
2376
                try{
2377
                    throw new IllegalStateException();
2378
                } catch(IllegalStateException e) {
2379
                    LOG.info("Call DefaultFeatureStore.getFeatureCount editing in mode APPEND");
2380
                    e.printStackTrace();
2381
                }
2382
                return -1;
2383
            } else {
2384
                return featureCount
2385
                    + this.featureManager.getDeltaSize();
2386
            }
2387
        }
2388
        return featureCount;
2389
    }
2390

    
2391
    private Long getTemporalOID() {
2392
        return this.temporalOid++;
2393
    }
2394

    
2395
    @Override
2396
    public FeatureType getProviderFeatureType(String featureTypeId) {
2397
        if (featureTypeId == null) {
2398
            return this.defaultFeatureType;
2399
        }
2400
        FeatureType type;
2401
        Iterator iter = this.featureTypes.iterator();
2402
        while (iter.hasNext()) {
2403
            type = (FeatureType) iter.next();
2404
            if (type.getId().equals(featureTypeId)) {
2405
                return type;
2406
            }
2407
        }
2408
        return null;
2409
    }
2410

    
2411
    @Override
2412
    public FeatureProvider getFeatureProviderFromFeature(Feature feature) {
2413
        return ((DefaultFeature) feature).getData();
2414
    }
2415

    
2416
    @Override
2417
    public DataStore getStore() {
2418
        return this;
2419
    }
2420

    
2421
    @Override
2422
    public FeatureStore getFeatureStore() {
2423
        return this;
2424
    }
2425

    
2426
    @Override
2427
    public void createCache(String name, DynObject parameters)
2428
        throws DataException {
2429
        cache = dataManager.createFeatureCacheProvider(name, parameters);
2430
        if (cache == null) {
2431
            throw new CreateException("FeaureCacheProvider", null);
2432
        }
2433
        cache.apply(this, provider);
2434
        provider = cache;
2435

    
2436
        featureCount = null;
2437
    }
2438

    
2439
    @Override
2440
    public FeatureCache getCache() {
2441
        return cache;
2442
    }
2443

    
2444
    @Override
2445
    public void clear() {
2446
        if (metadata != null) {
2447
            metadata.clear();
2448
        }
2449
    }
2450

    
2451
    @Override
2452
    public String getName() {
2453
        if( this.provider != null ) {
2454
            return this.provider.getName();
2455
        }
2456
        if( this.parameters instanceof HasAFile ) {
2457
            return FilenameUtils.getName(((HasAFile)this.parameters).getFile().getName());
2458
        }
2459
        return "unknow";
2460
    }
2461

    
2462
    @Override
2463
    public String getFullName() {
2464
        try {
2465
            if( this.provider!=null ) {
2466
                return this.provider.getFullName();
2467
            }
2468
            if( this.parameters instanceof HasAFile ) {
2469
                return (((HasAFile)this.parameters).getFile().getAbsolutePath());
2470
            }
2471
            return null;
2472
        } catch(Throwable th) {
2473
            return null;
2474
        }
2475
    }
2476

    
2477
    @Override
2478
    public String getProviderName() {
2479
        if( this.provider!=null ) {
2480
            return this.provider.getProviderName();
2481
        }
2482
        if( this.parameters != null ) {
2483
            return this.parameters.getDataStoreName();
2484
        }
2485
        return null;
2486

    
2487
    }
2488

    
2489
    @Override
2490
    public boolean isKnownEnvelope() {
2491
        return this.provider.isKnownEnvelope();
2492
    }
2493

    
2494
    @Override
2495
    public boolean hasRetrievedFeaturesLimit() {
2496
        return this.provider.hasRetrievedFeaturesLimit();
2497
    }
2498

    
2499
    @Override
2500
    public int getRetrievedFeaturesLimit() {
2501
        return this.provider.getRetrievedFeaturesLimit();
2502
    }
2503

    
2504
    @Override
2505
    public Interval getInterval() {
2506
        if( this.timeSupport!=null ) {
2507
            return this.timeSupport.getInterval();
2508
        }
2509
        return this.provider.getInterval();
2510
    }
2511

    
2512
    @Override
2513
    public Collection getTimes() {
2514
        if( this.timeSupport!=null ) {
2515
            return this.timeSupport.getTimes();
2516
        }
2517
        return this.provider.getTimes();
2518
    }
2519

    
2520
    @Override
2521
    public Collection getTimes(Interval interval) {
2522
        if( this.timeSupport!=null ) {
2523
            return this.timeSupport.getTimes(interval);
2524
        }
2525
        return this.provider.getTimes(interval);
2526
    }
2527

    
2528
    public void setTimeSupport(FeatureStoreTimeSupport timeSupport) {
2529
        FeatureAttributeDescriptor attr;
2530
        DefaultFeatureType ft;
2531
        try {
2532
            ft = (DefaultFeatureType) this.getDefaultFeatureType();
2533
        } catch (DataException ex) {
2534
            throw new RuntimeException("Can't add time support, can't get the default feature type.", ex);
2535
        }
2536
        attr = ft.getAttributeDescriptor(timeSupport.getAttributeName());
2537
        if( attr != null ) {
2538
            throw new RuntimeException("Can't add time support, attribute '"+timeSupport.getAttributeName()+"'already exists.");
2539
        }
2540
        attr = ft.getAttributeDescriptor(timeSupport.getRequiredFieldNames()[0]);
2541
        if( attr != null ) {
2542
            throw new RuntimeException("Can't add time support over attribute '"+timeSupport.getAttributeName()+"', this attribute don't exists.");
2543
        }
2544
        DefaultEditableFeatureAttributeDescriptor attr2 = new DefaultEditableFeatureAttributeDescriptor();
2545
        attr2.setDataType(timeSupport.getDataType());
2546
        attr2.setIsTime(true);
2547
        attr2.setFeatureAttributeEmulator(timeSupport);
2548
        ft.add(attr2);
2549

    
2550
        this.timeSupport = timeSupport;
2551
    }
2552

    
2553
    @Override
2554
    public Object clone() throws CloneNotSupportedException {
2555

    
2556
        DataStoreParameters dsp = getParameters();
2557

    
2558
        DefaultFeatureStore cloned_store = null;
2559

    
2560
        try {
2561
            cloned_store = (DefaultFeatureStore) DALLocator.getDataManager().
2562
                openStore(this.getProviderName(), dsp);
2563
            if (transforms != null) {
2564
                cloned_store.transforms = (DefaultFeatureStoreTransforms) transforms.clone();
2565
                cloned_store.transforms.setStoreForClone(cloned_store);
2566
            }
2567
        } catch (Exception e) {
2568
            throw new CloneException(e);
2569
        }
2570
        return cloned_store;
2571

    
2572
    }
2573

    
2574
    @Override
2575
    public Feature getFeature(DynObject dynobject) {
2576
        if (dynobject instanceof DynObjectFeatureFacade){
2577
            Feature f = ((DynObjectFeatureFacade)dynobject).getFeature();
2578
            return f;
2579
        }
2580
        return null;
2581
    }
2582

    
2583
    @Override
2584
    public Iterator iterator() {
2585
        try {
2586
            return this.getFeatureSet().fastIterator();
2587
        } catch (DataException ex) {
2588
            throw new RuntimeException(ex);
2589
        }
2590
    }
2591

    
2592
    @Override
2593
    public ExpressionBuilder createExpressionBuilder() {
2594
        if( this.provider instanceof FeatureStoreProvider_v2 ) {
2595
            return ((FeatureStoreProvider_v2)this.provider).createExpression();
2596
        }
2597
        return new SQLBuilderBase();
2598
    }
2599

    
2600
    @Override
2601
    public ExpressionBuilder createExpression() {
2602
        return createExpressionBuilder();
2603
    }
2604

    
2605
    public FeatureSet features() throws DataException {
2606
        // This is to avoid jython to create a property with this name
2607
        // to access method getFeatures.
2608
        return this.getFeatureSet();
2609
    }
2610

    
2611
    @Override
2612
    public DataStoreProviderFactory getProviderFactory() {
2613
        DataStoreProviderFactory factory = dataManager.getStoreProviderFactory(parameters.getDataStoreName());
2614
        return factory;
2615
    }
2616

    
2617
    @Override
2618
    public void useCache(String providerName, DynObject parameters) throws DataException {
2619
        throw new UnsupportedOperationException();
2620
    }
2621

    
2622
    @Override
2623
    public boolean isBroken() {
2624
        return this.state.isBroken();
2625
    }
2626

    
2627
    @Override
2628
    public Throwable getBreakingsCause() {
2629
            return this.state.getBreakingsCause();
2630
    }
2631

    
2632
    @Override
2633
    public SpatialIndex wrapSpatialIndex(SpatialIndex index) {
2634
//      FeatureStoreProviderFactory factory = (FeatureStoreProviderFactory) this.getProviderFactory();
2635
//      if( !factory.supportNumericOID() ) {
2636
//          return null;
2637
//      }
2638
      SpatialIndex wrappedIndex = new WrappedSpatialIndex(index, this);
2639
      return wrappedIndex;
2640
  }
2641
}