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 / DefaultFeatureType.java @ 44505

History | View | Annotate | Download (37 KB)

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

    
26
import java.lang.ref.WeakReference;
27
import java.util.ArrayList;
28
import java.util.Arrays;
29
import java.util.Collections;
30
import java.util.Date;
31
import java.util.HashSet;
32
import java.util.Iterator;
33
import java.util.LinkedHashSet;
34
import java.util.List;
35
import java.util.Set;
36
import java.util.function.Predicate;
37
import java.util.zip.CRC32;
38
import org.apache.commons.lang3.ArrayUtils;
39
import org.apache.commons.lang3.StringUtils;
40

    
41
import org.cresques.cts.IProjection;
42

    
43
import org.gvsig.fmap.dal.DataTypes;
44
import org.gvsig.fmap.dal.exception.DataException;
45
import org.gvsig.fmap.dal.feature.EditableFeatureType;
46
import org.gvsig.fmap.dal.feature.Feature;
47
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
48
import org.gvsig.fmap.dal.feature.FeatureAttributeEmulator;
49
import org.gvsig.fmap.dal.feature.FeatureRules;
50
import org.gvsig.fmap.dal.feature.FeatureStore;
51
import org.gvsig.fmap.dal.feature.FeatureType;
52
import org.gvsig.tools.ToolsLocator;
53
import org.gvsig.tools.dynobject.DynClass;
54
import org.gvsig.tools.dynobject.DynField;
55
import org.gvsig.tools.dynobject.DynMethod;
56
import org.gvsig.tools.dynobject.DynObject;
57
import org.gvsig.tools.dynobject.DynObjectValueItem;
58
import org.gvsig.tools.dynobject.DynStruct;
59
import org.gvsig.tools.dynobject.DynStruct_v2;
60
import org.gvsig.tools.dynobject.Tags;
61
import org.gvsig.tools.dynobject.exception.DynMethodException;
62
import org.gvsig.tools.dynobject.exception.DynObjectValidateException;
63
import org.gvsig.tools.dynobject.impl.DefaultTags;
64
import org.gvsig.tools.i18n.I18nManager;
65
import org.gvsig.tools.persistence.PersistenceManager;
66
import org.gvsig.tools.persistence.Persistent;
67
import org.gvsig.tools.persistence.PersistentState;
68
import org.gvsig.tools.persistence.exception.PersistenceException;
69

    
70
public class DefaultFeatureType
71
        extends ArrayList<FeatureAttributeDescriptor>
72
        implements
73
        FeatureType,
74
        Persistent,
75
        DynClass,
76
        DynStruct_v2,
77
        org.gvsig.tools.lang.Cloneable {
78

    
79
    /**
80
     *
81
     */
82
    private static final long serialVersionUID = -7988721447349282215L;
83

    
84
    public static final RecentUsedsAttributesImpl RECENTS_USEDS = new RecentUsedsAttributesImpl();
85

    
86
    private DefaultFeatureRules rules;
87
    protected boolean hasEvaluators;
88
    protected boolean hasEmulators;
89
    protected String defaultGeometryAttributeName;
90
    protected String defaultTimeAttributeName;
91
    protected int defaultGeometryAttributeIndex;
92
    protected int defaultTimeAttributeIndex;
93
    private String id;
94
    protected boolean hasOID;
95
    protected boolean allowAtomaticValues;
96
    protected FeatureAttributeDescriptor[] pk = null;
97
    protected String internalID = null;
98

    
99
    private List srsList = null;
100
    private WeakReference storeRef;
101
    private boolean requiredFields;
102

    
103
    private String description;
104
    private String label;
105
    private Tags tags;
106

    
107
    public DefaultFeatureType() {
108
        // Usado en la persistencia.
109
        this.internalID = Integer.toHexString((int) (Math.random() * 100000)).toUpperCase();
110
        this.id = id = "default";
111
        this.rules = new DefaultFeatureRules();
112
        this.hasEvaluators = false;
113
        this.hasEmulators = false;
114
        this.defaultGeometryAttributeName = null;
115
        this.defaultTimeAttributeName = null;
116
        this.defaultGeometryAttributeIndex = -1;
117
        this.defaultTimeAttributeIndex = -1;
118
        this.allowAtomaticValues = false;
119
        this.tags = new DefaultTags();
120
    }
121

    
122
    protected DefaultFeatureType(FeatureStore store, String id) {
123
        this();
124
        if (StringUtils.isEmpty(id)) {
125
            id = "default";
126
        }
127
        this.id = id;
128
        setStore(store);
129
    }
130

    
131
    protected DefaultFeatureType(FeatureStore store) {
132
        this(store, (String) null);
133
    }
134

    
135
    protected DefaultFeatureType(DefaultFeatureType other) {
136
        this(other.getStore(), (String) null);
137
        copyFrom(other, true);
138
    }
139

    
140
    protected DefaultFeatureType(DefaultFeatureType other,
141
            boolean copyAttributes) {
142
        this(other.getStore(), (String) null);
143
        this.copyFrom(other, copyAttributes);
144
    }
145

    
146
    @Override
147
    public void copyFrom(FeatureType other) {
148
        String internalIDSaved = this.internalID;
149
        String idSaved = this.id;
150
        copyFrom((DefaultFeatureType) other, true);
151
        this.id = idSaved;
152
        this.internalID = internalIDSaved;
153
    }
154
    
155
    protected void addAll(FeatureType attributes) {
156
        for (FeatureAttributeDescriptor attribute : attributes) {
157
            DefaultFeatureAttributeDescriptor copy = this.getCopyAttributeDescriptor((DefaultFeatureAttributeDescriptor) attribute);
158
            super.add(copy);
159
        }
160
        DefaultFeatureType ft = (DefaultFeatureType) attributes; 
161
        this.pk = null;
162
        this.defaultGeometryAttributeName = ft.defaultGeometryAttributeName;
163
        this.defaultTimeAttributeName = ft.defaultTimeAttributeName;
164
        this.defaultGeometryAttributeIndex = ft.defaultGeometryAttributeIndex;
165
        this.defaultTimeAttributeIndex = ft.defaultTimeAttributeIndex;
166
    }
167
    
168
    protected void copyFrom(DefaultFeatureType other, boolean copyAttributes) {
169
        this.id = other.getId();
170
        if (copyAttributes) {
171
            this.addAll((FeatureType)other);
172
        }
173

    
174
        this.hasEvaluators = other.hasEvaluators;
175
        this.hasEmulators = other.hasEmulators;
176
        this.rules = (DefaultFeatureRules) other.rules.getCopy();
177
        this.hasOID = other.hasOID;
178
        this.id = other.id; // XXX ???? copiar o no esto????
179
        this.internalID = other.internalID;
180
        this.label = other.label;
181
        this.description = other.description;
182
        try {
183
            this.tags = (Tags) other.tags.clone();
184
        } catch (CloneNotSupportedException ex) {
185
            
186
        }
187
    }
188
    
189
    protected DefaultFeatureAttributeDescriptor getCopyAttributeDescriptor(DefaultFeatureAttributeDescriptor src) {
190
        DefaultFeatureAttributeDescriptor copy = new DefaultFeatureAttributeDescriptor(src);
191
        copy.setFeatureType(this);
192
        return copy;
193
    }
194

    
195
    @Override
196
    public String getId() {
197
        return this.id;
198
    }
199

    
200
    @Override
201
    public Object get(String name) {
202
        FeatureAttributeDescriptor attr;
203
        Iterator iter = this.iterator();
204
        while (iter.hasNext()) {
205
            attr = (FeatureAttributeDescriptor) iter.next();
206
            if (attr.getName().equalsIgnoreCase(name)) {
207
                return attr;
208
            }
209
        }
210
        return null;
211
    }
212

    
213
    @Override
214
    public FeatureAttributeDescriptor getAttributeDescriptor(String name) {
215
        FeatureAttributeDescriptor attr;
216
        Iterator iter = this.iterator();
217
        while (iter.hasNext()) {
218
            attr = (FeatureAttributeDescriptor) iter.next();
219
            if (attr.getName().equalsIgnoreCase(name)) {
220
                return attr;
221
            }
222
        }
223
        return null;
224
    }
225

    
226
    @Override
227
    public FeatureAttributeDescriptor getAttributeDescriptor(int index) {
228
        return (FeatureAttributeDescriptor) super.get(index);
229
    }
230

    
231
    @Override
232
    public FeatureType getCopy() {
233
        return new DefaultFeatureType(this);
234
    }
235

    
236
    @Override
237
    public Object clone() {
238
        return this.getCopy();
239
    }
240

    
241
    public int getDefaultGeometryAttributeIndex() {
242
        return this.defaultGeometryAttributeIndex;
243
    }
244

    
245
    public String getDefaultGeometryAttributeName() {
246
        return this.defaultGeometryAttributeName;
247
    }
248

    
249
    public int getDefaultTimeAttributeIndex() {
250
        return this.defaultTimeAttributeIndex;
251
    }
252

    
253
    public String getDefaultTimeAttributeName() {
254
        return this.defaultTimeAttributeName;
255
    }
256

    
257
    public EditableFeatureType getEditable() {
258
        return new DefaultEditableFeatureType(this);
259
    }
260

    
261
    public int getIndex(String name) {
262
        FeatureAttributeDescriptor attr;
263
        Iterator iter = this.iterator();
264
        while (iter.hasNext()) {
265
            attr = (FeatureAttributeDescriptor) iter.next();
266
            if (attr.getName().equalsIgnoreCase(name)) {
267
                return attr.getIndex();
268
            }
269
        }
270
        return -1;
271
    }
272

    
273
    public FeatureRules getRules() {
274
        return this.rules;
275
    }
276

    
277
    public boolean hasEvaluators() {
278
        return this.hasEvaluators;
279
    }
280

    
281
    public boolean hasEmulators() {
282
        return this.hasEmulators;
283
    }
284

    
285
    public boolean hasRequiredFields() {
286
        return this.requiredFields;
287
    }
288

    
289
    public List getSRSs() {
290
        if (this.srsList == null) {
291
            ArrayList tmp = new ArrayList();
292
            Iterator iter = iterator();
293
            Iterator tmpIter;
294
            boolean allreadyHave;
295
            IProjection tmpSRS;
296
            FeatureAttributeDescriptor attr;
297
            while (iter.hasNext()) {
298
                attr = (FeatureAttributeDescriptor) iter.next();
299
                if (attr.getDataType().getType() == DataTypes.GEOMETRY
300
                        && attr.getSRS() != null) {
301
                    allreadyHave = false;
302
                    tmpIter = tmp.iterator();
303
                    while (tmpIter.hasNext()) {
304
                        tmpSRS = (IProjection) tmpIter.next();
305
                        if (tmpSRS.getAbrev().equals(attr.getSRS().getAbrev())) {
306
                            allreadyHave = true;
307
                            break;
308
                        }
309
                    }
310
                    if (!allreadyHave) {
311
                        tmp.add(attr.getSRS());
312
                    }
313
                }
314
            }
315
            this.srsList = Collections.unmodifiableList(tmp);
316
        }
317
        return this.srsList;
318
    }
319

    
320
    public IProjection getDefaultSRS() {
321
        if (this.getDefaultGeometryAttributeIndex() < 0) {
322
            return null;
323
        }
324
        return this.getAttributeDescriptor(
325
                this.getDefaultGeometryAttributeIndex()).getSRS();
326
    }
327

    
328
    public void validateFeature(Feature feature, int mode) throws DataException {
329
        DefaultFeatureRules rules = (DefaultFeatureRules) this.getRules();
330
        rules.validate(feature, mode);
331
    }
332

    
333
    public FeatureType getSubtype() throws DataException {
334
        return new SubtypeFeatureType(this, null, null, true);
335
    }
336

    
337
    public FeatureType getSubtype(String[] names) throws DataException {
338
        return this.getSubtype(names, null, true);
339
    }
340

    
341
    public FeatureType getSubtype(String[] names, String[] constantsNames) throws DataException {
342
        return this.getSubtype(names, constantsNames, true);
343
    }
344

    
345
    public FeatureType getSubtype(String[] names, String[] constantsNames, boolean includePk) throws DataException {
346
        if (ArrayUtils.isEmpty(names) && ArrayUtils.isEmpty(constantsNames)) {
347
            return (FeatureType) this.clone();
348
        }
349
        return new SubtypeFeatureType(this, names, constantsNames,includePk);
350
    }
351

    
352
    public boolean isSubtypeOf(FeatureType featureType) {
353
        return false;
354
    }
355

    
356
    @Override
357
    public List<FeatureAttributeDescriptor> toList() {
358
        return Collections.unmodifiableList(this);
359
    }
360

    
361
    @Override
362
    public Tags getTags() {
363
        return this.tags;
364
    }
365

    
366
    @Override
367
    public String getLabel() {
368
        return this.label;
369
    }
370

    
371
    @Override
372
    public void setLabel(String label) {
373
        this.label = label;
374
    }
375

    
376
    @Override
377
    public DynField addDynField(String name, int type) {
378
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
379
    }
380

    
381
    class SubtypeFeatureType extends DefaultFeatureType {
382

    
383
        /**
384
         *
385
         */
386
        private static final long serialVersionUID = 6913732960073922540L;
387
        WeakReference parent;
388

    
389
        SubtypeFeatureType(DefaultFeatureType parent, String[] names, String[] constantsNames, boolean includePk)
390
                throws DataException {
391
            super(parent, false);
392
            DefaultFeatureAttributeDescriptor attrcopy;
393
            Set<String> attrnames = new LinkedHashSet<>();
394
            Set<String> requiredAttrnames = new HashSet<>();
395

    
396
            if (ArrayUtils.isEmpty(names)) {
397
                for (FeatureAttributeDescriptor attrdesc : parent) {
398
                    attrnames.add(attrdesc.getName().toLowerCase());
399
                }
400
            } else { 
401
                attrnames.addAll(Arrays.asList(names));
402
                requiredAttrnames.addAll(Arrays.asList(names));
403
            }
404
            // Add required fields for emulated fields
405
            if (parent.hasEmulators) {
406
                // Ojo, este bucle falla cuando hay un campo calculado que depende
407
                // de otro campo calculado.
408
                for (FeatureAttributeDescriptor attrdesc : parent) {
409
                    FeatureAttributeEmulator emulator = attrdesc.getFeatureAttributeEmulator();
410
                    if (emulator != null && attrnames.contains(attrdesc.getName().toLowerCase())) {
411
                        String theNames[] = emulator.getRequiredFieldNames();
412
                        if (names != null) {
413
                            for (String name : theNames) {
414
                                name = name.toLowerCase();
415
                                attrnames.add(name);
416
                                requiredAttrnames.add(name);
417
                            }
418
                        }
419
                    }
420
                }
421
            }
422
            // Add missing pk fiels
423
            if (includePk && !parent.hasOID()) {
424
                for (FeatureAttributeDescriptor attrdesc : parent) {
425
                    if (attrdesc.isPrimaryKey()) {
426
                        String name = attrdesc.getName().toLowerCase();
427
                        attrnames.add(name);
428
                        requiredAttrnames.add(name);
429
                    }
430
                }
431
            }
432

    
433
            // Copy attributes
434
            int i = 0;
435
            for (String name : attrnames) {
436
                DefaultFeatureAttributeDescriptor attr = (DefaultFeatureAttributeDescriptor) parent.get(name);
437
                if (attr == null) {
438
                    throw new SubtypeFeatureTypeNameException(name, parent.getId());
439
                }
440
                attrcopy = new DefaultFeatureAttributeDescriptor(attr);
441
                this.add(attrcopy);
442
                attrcopy.index = i++;
443
            }
444

    
445
            // Set the constants attributes.
446
            if (!ArrayUtils.isEmpty(constantsNames)) {
447
                for (String name : constantsNames) {
448
                    if (!requiredAttrnames.contains(name)) {
449
                        DefaultFeatureAttributeDescriptor attr = (DefaultFeatureAttributeDescriptor) this.get(name);
450
                        attr.setConstantValue(true);
451
                    }
452
                }
453
            }
454

    
455
            this.defaultGeometryAttributeIndex = this.getIndex(this.defaultGeometryAttributeName);
456
            if (this.defaultGeometryAttributeIndex < 0) {
457
                this.defaultGeometryAttributeName = null;
458
            }
459
            this.defaultTimeAttributeIndex = this.getIndex(this.defaultTimeAttributeName);
460
            if (this.defaultTimeAttributeIndex < 0) {
461
                this.defaultTimeAttributeName = null;
462
            }
463
            this.parent = new WeakReference(parent);
464
        }
465

    
466
        public FeatureType getSubtype(String[] names, boolean includePk) throws DataException {
467
            return new SubtypeFeatureType((DefaultFeatureType) this.parent
468
                    .get(), names, null, includePk);
469
        }
470

    
471
        public boolean isSubtypeOf(FeatureType featureType) {
472
            if (featureType == null) {
473
                return false;
474
            }
475
            FeatureType parent = (FeatureType) this.parent.get();
476
            return featureType.equals(parent);
477
        }
478

    
479
        public EditableFeatureType getEditable() {
480
            throw new UnsupportedOperationException();
481
        }
482
    }
483

    
484
    public class SubtypeFeatureTypeNameException extends DataException {
485

    
486
        /**
487
         *
488
         */
489
        private static final long serialVersionUID = -4414242486723260101L;
490
        private final static String MESSAGE_FORMAT = "Attribute name '%(name)' not found in type (%(type)).";
491
        private final static String MESSAGE_KEY = "_SubtypeFeatureTypeNameException";
492

    
493
        public SubtypeFeatureTypeNameException(String name, String type) {
494
            super(MESSAGE_FORMAT, MESSAGE_KEY, serialVersionUID);
495
            setValue("name", name);
496
            setValue("type", type);
497
        }
498
    }
499

    
500
    public boolean hasOID() {
501
        return hasOID;
502
    }
503

    
504
    public String toString() {
505
        StringBuffer s = new StringBuffer();
506
        s.append(this.getId());
507
        s.append(":[");
508
        String attName;
509
        for (int i = 0; i < size(); i++) {
510
            attName = ((FeatureAttributeDescriptor) get(i)).getName().toString();
511
            s.append(attName);
512
            if (i < size() - 1) {
513
                s.append(',');
514
            }
515
        }
516
        s.append(']');
517
        return s.toString();
518
    }
519

    
520
    public Iterator<FeatureAttributeDescriptor> iterator() {
521
        return getIterator(super.iterator());
522
    }
523

    
524
    protected Iterator getIterator(Iterator iter) {
525
        return new DelegatedIterator(iter);
526
    }
527

    
528
    protected class DelegatedIterator implements Iterator {
529

    
530
        protected Iterator iterator;
531

    
532
        public DelegatedIterator(Iterator iter) {
533
            this.iterator = iter;
534
        }
535

    
536
        public boolean hasNext() {
537
            return iterator.hasNext();
538
        }
539

    
540
        public Object next() {
541
            return iterator.next();
542
        }
543

    
544
        public void remove() {
545
            throw new UnsupportedOperationException();
546
        }
547

    
548
    }
549

    
550
    public boolean allowAutomaticValues() {
551
        return this.allowAtomaticValues;
552
    }
553

    
554
    public FeatureAttributeDescriptor[] getAttributeDescriptors() {
555
        return (FeatureAttributeDescriptor[]) super
556
                .toArray(new FeatureAttributeDescriptor[super.size()]);
557
    }
558

    
559
    @Override
560
    public boolean hasPrimaryKey() {
561
        if( pk!=null ) {
562
            return pk.length>0;
563
        }
564
        for (FeatureAttributeDescriptor attr : this) {
565
            if( attr.isPrimaryKey() ) {
566
                return true;
567
            }
568
        }
569
        return false;
570
    }
571

    
572
    @Override
573
    public boolean supportReferences() {
574
        return this.hasOID() || this.hasPrimaryKey();
575
    }
576
    
577
    @Override
578
    public FeatureAttributeDescriptor[] getPrimaryKey() {
579
        if (pk == null) {
580
            List pks = new ArrayList();
581
            Iterator iter = super.iterator();
582
            FeatureAttributeDescriptor attr;
583
            while (iter.hasNext()) {
584
                attr = (FeatureAttributeDescriptor) iter.next();
585
                if (attr.isPrimaryKey()) {
586
                    pks.add(attr);
587
                }
588
            }
589
            if (pks.isEmpty()) {
590
                pk = new FeatureAttributeDescriptor[0];
591
            } else {
592
                pk = (FeatureAttributeDescriptor[]) pks.toArray(new FeatureAttributeDescriptor[pks.size()]);
593
            }
594
        }
595
        return pk;
596
    }
597

    
598
    public FeatureAttributeDescriptor getDefaultGeometryAttribute() {
599
        if (this.defaultGeometryAttributeIndex < 0) {
600
            return null;
601
        }
602
        return (FeatureAttributeDescriptor) super
603
                .get(this.defaultGeometryAttributeIndex);
604
    }
605

    
606
    public boolean equals(Object o) {
607
        if (this == o) {
608
            return true;
609
        }
610
        if (!(o instanceof DefaultFeatureType)) {
611
            return false;
612
        }
613
        DefaultFeatureType other = (DefaultFeatureType) o;
614
        if (!this.id.equals(other.id)) {
615
            return false;
616
        }
617
        if (this.size() != other.size()) {
618
            return false;
619
        }
620
        FeatureAttributeDescriptor attr, attrOther;
621
        Iterator iter, iterOther;
622
        iter = this.iterator();
623
        iterOther = other.iterator();
624
        while (iter.hasNext()) {
625
            attr = (FeatureAttributeDescriptor) iter.next();
626
            attrOther = (FeatureAttributeDescriptor) iterOther.next();
627
            if (!attr.equals(attrOther)) {
628
                return false;
629
            }
630
        }
631

    
632
        if (!StringUtils.equals(defaultGeometryAttributeName, other.defaultGeometryAttributeName)) {
633
            return false;
634
        }
635
        if (!StringUtils.equals(defaultTimeAttributeName, other.defaultTimeAttributeName)) {
636
            return false;
637
        }
638
        return true;
639

    
640
    }
641

    
642
    /**
643
     * Start of DynClass interface implementation READONLY
644
     */
645
    public DynField addDynField(String name) {
646
        throw new UnsupportedOperationException();
647
    }
648

    
649
    public DynField getDeclaredDynField(String name) {
650
        return (DynField) getAttributeDescriptor(name);
651
    }
652

    
653
    public DynField[] getDeclaredDynFields() {
654
        return (DynField[]) getAttributeDescriptors();
655
    }
656

    
657
    public String getDescription() {
658
        return this.description;
659
    }
660

    
661
    public DynField getDynField(String name) {
662
        return (DynField) getAttributeDescriptor(name);
663
    }
664

    
665
    public DynField[] getDynFields() {
666
        return (DynField[]) getAttributeDescriptors();
667
    }
668

    
669
    public String getName() {
670
        return this.id + "_" + internalID;
671
    }
672

    
673
    public void removeDynField(String name) {
674
        throw new UnsupportedOperationException();
675

    
676
    }
677

    
678
    public void addDynMethod(DynMethod dynMethod) {
679
        throw new UnsupportedOperationException();
680

    
681
    }
682

    
683
    public void extend(DynClass dynClass) {
684
        throw new UnsupportedOperationException();
685

    
686
    }
687

    
688
    public void extend(String dynClassName) {
689
        throw new UnsupportedOperationException();
690

    
691
    }
692

    
693
    public void extend(String namespace, String dynClassName) {
694
        throw new UnsupportedOperationException();
695

    
696
    }
697

    
698
    public DynMethod getDeclaredDynMethod(String name)
699
            throws DynMethodException {
700
        return null;
701
    }
702

    
703
    public DynMethod[] getDeclaredDynMethods() throws DynMethodException {
704
        return null;
705
    }
706

    
707
    public DynMethod getDynMethod(String name) throws DynMethodException {
708
        return null;
709
    }
710

    
711
    public DynMethod getDynMethod(int code) throws DynMethodException {
712
        return null;
713
    }
714

    
715
    public DynMethod[] getDynMethods() throws DynMethodException {
716
        return null;
717
    }
718

    
719
    public DynClass[] getSuperDynClasses() {
720
        return null;
721
    }
722

    
723
    public boolean isInstance(DynObject dynObject) {
724
        if (dynObject.getDynClass().getName() == getName()) {
725
            return true;
726
        }
727
        return false;
728
    }
729

    
730
    public DynObject newInstance() {
731

    
732
        throw new UnsupportedOperationException();
733
    }
734

    
735
    public void removeDynMethod(String name) {
736
        throw new UnsupportedOperationException();
737

    
738
    }
739

    
740
    public DynField addDynFieldChoice(String name, int type,
741
            Object defaultValue, DynObjectValueItem[] values,
742
            boolean mandatory, boolean persistent) {
743
        throw new UnsupportedOperationException();
744
    }
745

    
746
    public DynField addDynFieldRange(String name, int type,
747
            Object defaultValue, Object min, Object max, boolean mandatory,
748
            boolean persistent) {
749
        throw new UnsupportedOperationException();
750
    }
751

    
752
    public DynField addDynFieldSingle(String name, int type,
753
            Object defaultValue, boolean mandatory, boolean persistent) {
754
        throw new UnsupportedOperationException();
755
    }
756

    
757
    public void validate(DynObject object) throws DynObjectValidateException {
758
        //FIXME: not sure it's the correct code
759
        if (object instanceof Feature) {
760
            Feature fea = (Feature) object;
761
            if (fea.getType().equals(this)) {
762
                return;
763
            }
764
        }
765
        throw new DynObjectValidateException(this.id);
766
    }
767

    
768
    public DynField addDynFieldLong(String name) {
769
        throw new UnsupportedOperationException();
770
    }
771

    
772
    public DynField addDynFieldChoice(String name, int type,
773
            Object defaultValue, DynObjectValueItem[] values) {
774
        throw new UnsupportedOperationException();
775
    }
776

    
777
    public DynField addDynFieldRange(String name, int type,
778
            Object defaultValue, Object min, Object max) {
779
        throw new UnsupportedOperationException();
780
    }
781

    
782
    public DynField addDynFieldSingle(String name, int type, Object defaultValue) {
783
        throw new UnsupportedOperationException();
784
    }
785

    
786
    public DynField addDynFieldString(String name) {
787
        throw new UnsupportedOperationException();
788
    }
789

    
790
    public DynField addDynFieldInt(String name) {
791
        throw new UnsupportedOperationException();
792
    }
793

    
794
    public DynField addDynFieldDouble(String name) {
795
        throw new UnsupportedOperationException();
796
    }
797

    
798
    public DynField addDynFieldFloat(String name) {
799
        throw new UnsupportedOperationException();
800
    }
801

    
802
    public DynField addDynFieldBoolean(String name) {
803
        throw new UnsupportedOperationException();
804
    }
805

    
806
    public DynField addDynFieldList(String name) {
807
        throw new UnsupportedOperationException();
808
    }
809

    
810
    public DynField addDynFieldMap(String name) {
811
        throw new UnsupportedOperationException();
812
    }
813

    
814
    public DynField addDynFieldObject(String name) {
815
        throw new UnsupportedOperationException();
816
    }
817

    
818
    public DynField addDynFieldSet(String name) {
819
        throw new UnsupportedOperationException();
820
    }
821

    
822
    public DynField addDynFieldArray(String name) {
823
        throw new UnsupportedOperationException();
824
    }
825

    
826
    public DynField addDynFieldDate(String name) {
827
        throw new UnsupportedOperationException();
828
    }
829

    
830
    public void extend(DynStruct struct) {
831
        throw new UnsupportedOperationException();
832
    }
833

    
834
    public String getFullName() {
835
        // TODO: usar el DynClassName
836
        return this.id;
837
    }
838

    
839
    public String getNamespace() {
840
        return "DALFeature";
841
    }
842

    
843
    public DynStruct[] getSuperDynStructs() {
844
        return null;
845
    }
846

    
847
    public void setDescription(String description) {
848
        this.description = description;
849
    }
850

    
851
    public void setNamespace(String namespace) {
852
        throw new UnsupportedOperationException();
853
    }
854

    
855
    public DynField addDynFieldFile(String name) {
856
        throw new UnsupportedOperationException();
857
    }
858

    
859
    public DynField addDynFieldFolder(String name) {
860
        throw new UnsupportedOperationException();
861
    }
862

    
863
    public DynField addDynFieldURL(String name) {
864
        throw new UnsupportedOperationException();
865
    }
866

    
867
    public DynField addDynFieldURI(String name) {
868
        throw new UnsupportedOperationException();
869
    }
870

    
871
    public boolean isExtendable(DynStruct dynStruct) {
872
        return false;
873
    }
874

    
875
    public void extend(DynStruct[] structs) {
876
        // TODO Auto-generated method stub
877

    
878
    }
879

    
880
    public void remove(DynStruct superDynStruct) {
881
        // TODO Auto-generated method stub
882

    
883
    }
884

    
885
    public void removeAll(DynStruct[] superDynStruct) {
886
        // TODO Auto-generated method stub
887

    
888
    }
889

    
890
    public FeatureAttributeDescriptor getDefaultTimeAttribute() {
891
        if (this.defaultTimeAttributeIndex < 0) {
892
            return null;
893
        }
894
        return (FeatureAttributeDescriptor) super
895
                .get(this.defaultTimeAttributeIndex);
896
    }
897

    
898
    public void setDefaultTimeAttributeName(String name) {
899
        if (name == null || name.length() == 0) {
900
            this.defaultTimeAttributeIndex = -1;
901
            return;
902
        }
903
        DefaultFeatureAttributeDescriptor attr = (DefaultFeatureAttributeDescriptor) this.get(name);
904
        if (attr == null) {
905
            throw new IllegalArgumentException("Attribute '" + name + "' not found.");
906
        }
907
        if (attr.getIndex() < 0) {
908
            fixAll();
909
        }
910
        this.defaultTimeAttributeIndex = attr.getIndex();
911
    }
912

    
913
    protected void fixAll() {
914
        int i = 0;
915
        Iterator iter = super.iterator();
916
        DefaultFeatureAttributeDescriptor attr;
917

    
918
        while (iter.hasNext()) {
919
            attr = (DefaultFeatureAttributeDescriptor) iter.next();
920
            if (attr.getOder() < 1) {
921
                attr.setOrder(i * 10);
922
            }
923
            attr.setIndex(i++);
924
            attr.fixAll();
925
            if (attr.getEvaluator() != null) {
926
                this.hasEvaluators = true;
927
            }
928
            if (attr.getFeatureAttributeEmulator() != null) {
929
                this.hasEmulators = true;
930
                String[] x = attr.getFeatureAttributeEmulator().getRequiredFieldNames();
931
                if (!ArrayUtils.isEmpty(x)) {
932
                    this.requiredFields = true;
933
                }
934
            }
935
            switch (attr.getType()) {
936
                case DataTypes.GEOMETRY:
937
                    if (this.defaultGeometryAttributeName == null) {
938
                        this.defaultGeometryAttributeName = attr.getName();
939
                    }
940
                    break;
941
                case DataTypes.INSTANT:
942
                case DataTypes.INTERVAL:
943
                case DataTypes.DATE:
944
                    if (this.defaultTimeAttributeName == null && attr.isTime()) {
945
                        this.defaultTimeAttributeName = attr.getName();
946
                    }
947
                    break;
948
            }
949
        }
950
        if (this.defaultGeometryAttributeName != null) {
951
            this.defaultGeometryAttributeIndex = this.getIndex(this.defaultGeometryAttributeName);
952
        }
953
        if (this.defaultTimeAttributeName != null) {
954
            this.defaultTimeAttributeIndex = this.getIndex(this.defaultTimeAttributeName);
955
        }
956
        this.internalID = Long.toHexString(this.getCRC());
957

    
958
    }
959

    
960
    protected long getCRC() {
961
        StringBuffer buffer = new StringBuffer();
962
        for (int i = 0; i < this.size(); i++) {
963
            FeatureAttributeDescriptor x = this.getAttributeDescriptor(i);
964
            buffer.append(x.getName());
965
            buffer.append(x.getDataTypeName());
966
            buffer.append(x.getSize());
967
        }
968
        CRC32 crc = new CRC32();
969
        byte[] data = buffer.toString().getBytes();
970
        crc.update(data);
971
        return crc.getValue();
972
    }
973

    
974
    @Override
975
    public FeatureStore getStore() {
976
        if (this.storeRef == null) {
977
            return null;
978
        }
979
        return (FeatureStore) this.storeRef.get();
980
    }
981

    
982
    public void setStore(FeatureStore store) {
983
        if (store == null) {
984
            this.storeRef = null;
985
        } else {
986
            this.storeRef = new WeakReference(store);
987
        }
988
    }
989

    
990
    @Override
991
    public List<FeatureAttributeDescriptor> getFilteredAttributes(
992
            Predicate<FeatureAttributeDescriptor> filter,
993
            int max
994
    ) {
995
        List<FeatureAttributeDescriptor> attrs = new ArrayList<>();
996
        for (FeatureAttributeDescriptor attribute : this) {
997
            if (filter.test(attribute)) {
998
                attrs.add(attribute);
999
            }
1000
        }
1001
        return attrs;
1002
    }
1003
    
1004
    @Override
1005
    public List<FeatureAttributeDescriptor> getRecentUseds() {
1006
        return RECENTS_USEDS.getAttributes(this);
1007
    }
1008
    
1009
    @Override
1010
    public void loadFromState(PersistentState state)
1011
            throws PersistenceException {
1012

    
1013
//        FIXME: rules
1014
        hasEvaluators = state.getBoolean("hasEvaluators");
1015
        hasEmulators = state.getBoolean("hasEmulators");
1016
        defaultGeometryAttributeName = state.getString("defaultGeometryAttributeName");
1017
        defaultTimeAttributeName = state.getString("defaultTimeAttributeName");
1018
        defaultGeometryAttributeIndex = state.getInt("defaultGeometryAttributeIndex");
1019
        defaultTimeAttributeIndex = state.getInt("defaultTimeAttributeIndex");
1020
        id = state.getString("id");
1021
        hasOID = state.getBoolean("hasOID");
1022
        allowAtomaticValues = state.getBoolean("allowAtomaticValues");
1023

    
1024
        requiredFields = state.getBoolean("requiredFields");
1025
        internalID = state.getString("internalID");
1026
        tags = (Tags) state.get("tags");
1027
        if( tags == null ) {
1028
            this.tags = new DefaultTags();
1029
        }
1030

    
1031
        List<FeatureAttributeDescriptor> elements = state.getList("elements");
1032
        for (FeatureAttributeDescriptor element : elements) {
1033
            ((DefaultFeatureAttributeDescriptor) element).setFeatureType(this);
1034
            super.add(element);
1035
        }
1036
        this.pk = null;
1037
        this.fixAll();
1038
    }
1039

    
1040
    @Override
1041
    public void saveToState(PersistentState state) throws PersistenceException {
1042

    
1043
//        FIXME: rules
1044
        state.set("hasEvaluators", hasEvaluators);
1045
        state.set("hasEmulators", hasEmulators);
1046
        state.set("defaultGeometryAttributeName", defaultGeometryAttributeName);
1047
        state.set("defaultTimeAttributeName", defaultTimeAttributeName);
1048
        state.set("defaultGeometryAttributeIndex", defaultGeometryAttributeIndex);
1049
        state.set("defaultTimeAttributeIndex", defaultTimeAttributeIndex);
1050
        state.set("id", id);
1051
        state.set("hasOID", hasOID);
1052
        state.set("allowAtomaticValues", allowAtomaticValues);
1053

    
1054
        state.set("requiredFields", requiredFields);
1055
        state.set("internalID", internalID);
1056

    
1057
        List<FeatureAttributeDescriptor> elements = new ArrayList<>();
1058
        elements.addAll(this);
1059
        state.set("elements", elements);
1060
        state.set("tags", tags);
1061

    
1062
    }
1063

    
1064
    private static final String FEATTYPE_PERSISTENCE_DEFINITION_NAME = "FeatureType";
1065

    
1066
    public static void registerPersistenceDefinition() {
1067
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
1068

    
1069
        if (manager.getDefinition(FEATTYPE_PERSISTENCE_DEFINITION_NAME)
1070
                == null) {
1071
            DynStruct definition = manager.addDefinition(DefaultFeatureType.class,
1072
                    FEATTYPE_PERSISTENCE_DEFINITION_NAME,
1073
                    FEATTYPE_PERSISTENCE_DEFINITION_NAME
1074
                    + " persistent definition",
1075
                    null,
1076
                    null
1077
            );
1078
//            definition.addDynFieldObject("rules");
1079
            definition.addDynFieldBoolean("hasEvaluators");
1080
            definition.addDynFieldBoolean("hasEmulators");
1081
            definition.addDynFieldString("defaultGeometryAttributeName");
1082
            definition.addDynFieldString("defaultTimeAttributeName");
1083
            definition.addDynFieldInt("defaultGeometryAttributeIndex");
1084
            definition.addDynFieldInt("defaultTimeAttributeIndex");
1085
            definition.addDynFieldString("id");
1086
            definition.addDynFieldBoolean("hasOID");
1087
            definition.addDynFieldBoolean("allowAtomaticValues");
1088

    
1089
            definition.addDynFieldBoolean("requiredFields");
1090
            definition.addDynFieldString("internalID");
1091

    
1092
            definition.addDynFieldList("elements")
1093
                    .setClassOfItems(FeatureAttributeDescriptor.class);
1094

    
1095
            definition.addDynFieldObject("tags")
1096
                    .setClassOfValue(Tags.class);
1097
            
1098
        }
1099
    }
1100

    
1101
    @Override
1102
    public FeatureStore getAsFeatureStore() {
1103
        FeatureStore store = FeatureTypeToStoreProviderAdapter.createFeatureStore(this);
1104
        return store;
1105
    }
1106
    
1107
                
1108
    public String getNewFieldName() {
1109
        I18nManager i18n = ToolsLocator.getI18nManager();
1110
        String prefix = i18n.getTranslation("_Field");
1111
        String fieldName;
1112
        for (int i = 1; i < 1000; i++) {
1113
            fieldName = prefix +"-"+i;
1114
            if( this.get(fieldName)==null ) {
1115
                return fieldName;
1116
            }
1117
        }
1118
        fieldName = prefix + "-" + (new Date()).getTime();
1119
        return fieldName;
1120
    }
1121
    
1122
   public FeatureType getOriginalFeatureType()  {
1123
        DefaultFeatureStore store = (DefaultFeatureStore) this.getStore();
1124
        if (store==null) {
1125
            return null;
1126
        }
1127
        return store.getOriginalFeatureType(this);
1128
    }
1129
    @Override
1130
    public boolean hasOnlyMetadataChanges(FeatureType old) {
1131
        if( old == null ) {
1132
            throw new NullPointerException();
1133
        }
1134
        // Si hay campos nuevos -> false
1135
        for (FeatureAttributeDescriptor attr : this) {
1136
            if( old.getAttributeDescriptor(attr.getName())==null ) {
1137
                return false;
1138
            }
1139
        }
1140
        
1141
        // Si se ha eliminado algun campo -> false
1142
        for (FeatureAttributeDescriptor attr : old) {
1143
            if( this.getAttributeDescriptor(attr.getName())==null ) {
1144
                return false;
1145
            }
1146
        }
1147
        
1148
        // No hay campos nuevos ni se ha eliminado ninguno, asi que comparamos
1149
        // los campos uno a uno.
1150
        for (FeatureAttributeDescriptor attr : this) {
1151
            FeatureAttributeDescriptor attrold = old.getAttributeDescriptor(attr.getName());
1152
            if( !attr.hasOnlyMetadataChanges(attrold) ) {
1153
                return false;
1154
            }
1155
        }
1156
        return true;
1157
    }
1158
}