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 / DefaultFeatureAttributeDescriptor.java @ 45768

History | View | Annotate | Download (75.4 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 modify it under
7
 * the terms of the GNU General Public License as published by the Free Software
8
 * Foundation; either version 3 of the License, or (at your option) any later
9
 * version.
10
 *
11
 * This program is distributed in the hope that it will be useful, but WITHOUT
12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14
 * details.
15
 *
16
 * You should have received a copy of the GNU General Public License along with
17
 * this program; if not, write to the Free Software Foundation, Inc., 51
18
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19
 *
20
 * For any additional information, do not hesitate to contact us at info AT
21
 * gvsig.com, or visit our website www.gvsig.com.
22
 */
23
package org.gvsig.fmap.dal.feature.impl;
24

    
25
import java.lang.ref.WeakReference;
26
import java.math.BigDecimal;
27
import java.math.MathContext;
28
import java.math.RoundingMode;
29
import java.text.DateFormat;
30
import java.util.ArrayList;
31
import java.util.HashMap;
32
import java.util.LinkedHashMap;
33
import java.util.List;
34
import java.util.Locale;
35
import java.util.Map;
36
import java.util.Map.Entry;
37
import java.util.Objects;
38
import java.util.function.Supplier;
39
import javax.json.JsonObject;
40
import org.apache.commons.lang3.ArrayUtils;
41
import org.apache.commons.lang3.StringUtils;
42
import org.apache.commons.lang3.tuple.Pair;
43
import org.cresques.cts.IProjection;
44
import org.gvsig.expressionevaluator.Expression;
45
import org.gvsig.expressionevaluator.ExpressionUtils;
46
import org.gvsig.expressionevaluator.MutableSymbolTable;
47
import org.gvsig.fmap.dal.DALLocator;
48
import org.gvsig.fmap.dal.DataStore;
49
import org.gvsig.fmap.dal.DataTypes;
50
import org.gvsig.fmap.dal.expressionevaluator.FeatureAttributeEmulatorExpression;
51
import org.gvsig.fmap.dal.feature.DataProfile;
52
import org.gvsig.fmap.dal.feature.Feature;
53
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
54
import org.gvsig.fmap.dal.feature.FeatureAttributeEmulator;
55
import org.gvsig.fmap.dal.feature.FeatureAttributeGetter;
56
import org.gvsig.fmap.dal.feature.FeatureStore;
57
import org.gvsig.fmap.dal.feature.FeatureType;
58
import org.gvsig.fmap.dal.feature.ForeingKey;
59
import org.gvsig.fmap.dal.feature.ForeingKey.ContextForeingKey;
60
import org.gvsig.fmap.geom.Geometry;
61
import org.gvsig.fmap.geom.GeometryCoercionContext;
62
import org.gvsig.fmap.geom.GeometryException;
63
import org.gvsig.fmap.geom.GeometryLocator;
64
import org.gvsig.fmap.geom.GeometryUtils;
65
import org.gvsig.fmap.geom.type.GeometryType;
66
import org.gvsig.json.Json;
67
import org.gvsig.json.JsonManager;
68
import org.gvsig.json.JsonObjectBuilder;
69
import org.gvsig.json.SupportToJson;
70
import org.gvsig.timesupport.Interval;
71
import org.gvsig.timesupport.RelativeInterval;
72
import org.gvsig.timesupport.TimeSupportLocator;
73
import org.gvsig.tools.ToolsLocator;
74
import org.gvsig.tools.dataTypes.Coercion;
75
import org.gvsig.tools.dataTypes.CoercionContext;
76
import org.gvsig.tools.dataTypes.CoercionException;
77
import org.gvsig.tools.dataTypes.DataType;
78
import org.gvsig.tools.dataTypes.DataType.NumberPrecisionAndScale;
79
import org.gvsig.tools.dataTypes.DataTypeUtils;
80
import org.gvsig.tools.dynobject.AbstractDynMethod;
81
import org.gvsig.tools.dynobject.DynField;
82
import org.gvsig.tools.dynobject.DynField_LabelAttribute;
83
import org.gvsig.tools.dynobject.DynField_v2;
84
import org.gvsig.tools.dynobject.DynMethod;
85
import org.gvsig.tools.dynobject.DynObject;
86
import org.gvsig.tools.dynobject.DynObjectValueItem;
87
import org.gvsig.tools.dynobject.DynStruct;
88
import org.gvsig.tools.dynobject.Tags;
89
import org.gvsig.tools.dynobject.exception.DynFieldIsNotAContainerException;
90
import org.gvsig.tools.dynobject.exception.DynFieldValidateException;
91
import org.gvsig.tools.dynobject.exception.DynMethodException;
92
import org.gvsig.tools.dynobject.impl.DefaultTags;
93
import org.gvsig.tools.evaluator.AbstractEvaluator;
94
import org.gvsig.tools.evaluator.Evaluator;
95
import org.gvsig.tools.evaluator.EvaluatorData;
96
import org.gvsig.tools.evaluator.EvaluatorException;
97
import org.gvsig.tools.i18n.I18nManager;
98
import org.gvsig.tools.persistence.PersistenceManager;
99
import org.gvsig.tools.persistence.Persistent;
100
import org.gvsig.tools.persistence.PersistentState;
101
import org.gvsig.tools.persistence.exception.PersistenceException;
102
import org.gvsig.tools.util.GetItemWithSize;
103
import org.gvsig.tools.util.LabeledValue;
104
import org.slf4j.Logger;
105
import org.slf4j.LoggerFactory;
106

    
107
@SuppressWarnings("UseSpecificCatch")
108
public class DefaultFeatureAttributeDescriptor implements
109
        FeatureAttributeDescriptor, Persistent, DynField_v2, DynField_LabelAttribute {
110

    
111
    protected static final Logger LOGGER = LoggerFactory.getLogger(DefaultFeatureAttributeDescriptor.class);
112

    
113
    protected boolean allowNull;
114
    protected DataType dataType;
115
    protected String dataProfile;
116
    protected DateFormat dateFormat;
117
    protected Object defaultValue;
118
    protected int index;
119
    protected int maximumOccurrences;
120
    protected int minimumOccurrences;
121
    protected int size;
122
    protected String name;
123
    protected Class objectClass;
124
    protected int precision;
125
    protected int scale;
126
    protected int roundMode;
127
    protected Evaluator evaluator;
128
    protected boolean primaryKey;
129
    protected boolean readOnly;
130
    protected IProjection SRS;
131
    protected GeometryType geomType;
132
    protected int geometryType;
133
    protected int geometrySubType;
134
    protected Map<String, String> additionalInfo;
135
    protected boolean isAutomatic;
136
    protected boolean isTime = false;
137
    protected Interval interval;
138
    protected FeatureAttributeGetter featureAttributeGetter = null;
139
    protected FeatureAttributeEmulator featureAttributeEmulator = null;
140
    protected boolean indexed = false;
141
    protected boolean isIndexAscending = true;
142
    protected boolean allowIndexDuplicateds = true;
143

    
144
    protected DynObjectValueItem[] availableValues;
145
    protected DynObjectValueItem[] availableValuesCache; // No persistente
146
    protected Expression availableValuesExpression;
147
    protected boolean avoidCachingAvailableValues;
148
    private Map<Object, String> labelOfValueMap; // No persistente
149
    protected String description;
150
    protected Object minValue;
151
    protected Object maxValue;
152
    protected String label;
153
    protected String shortLabel;
154
    protected int order;
155
    protected boolean hidden;
156
    protected String groupName;
157
    protected Tags tags = new DefaultTags();
158
    private DynMethod availableValuesMethod;
159
    private DynMethod calculateMethod;
160
    private WeakReference typeRef;
161
    protected DefaultForeingKey foreingKey = null;
162

    
163
    protected CoercionContext coerceContext = null; // not persistent
164
    protected MathContext mathContext = null; // not persistent
165

    
166
    private int relationType = RELATION_TYPE_NONE;
167
    protected Locale locale;
168
    protected int displaySize;
169

    
170
    public DefaultFeatureAttributeDescriptor() {
171
        // Usada en la persistencia
172
        this.precision = DataType.PRECISION_NONE;
173
        this.scale = DataType.SCALE_NONE;
174
        this.roundMode = BigDecimal.ROUND_HALF_UP;
175
    }
176

    
177
    protected DefaultFeatureAttributeDescriptor(FeatureType type) {
178
        this();
179
//        LOGGER.info(String.format("Created FeatureAttributeDescriptor [%08x].", this.hashCode()));
180
        setFeatureType(type);
181
        this.allowNull = true;
182
        this.dataType = null;
183
        this.dateFormat = null;
184
        this.defaultValue = null;
185
        this.index = -1;
186
        this.maximumOccurrences = 0;
187
        this.minimumOccurrences = 0;
188
        this.size = 0;
189
        this.name = null;
190
        this.objectClass = null;
191
        this.precision = DataType.PRECISION_NONE;
192
        this.scale = DataType.SCALE_NONE;
193
        this.roundMode = BigDecimal.ROUND_HALF_UP;
194
        this.evaluator = null;
195
        this.primaryKey = false;
196
        this.readOnly = false;
197
        this.SRS = null;
198
        this.geometryType = Geometry.TYPES.NULL;
199
        this.geometrySubType = Geometry.SUBTYPES.UNKNOWN;
200
        this.additionalInfo = null;
201
        this.isAutomatic = false;
202
        this.hidden = false;
203
        this.relationType = RELATION_TYPE_NONE;
204
        this.locale = null;
205
        this.displaySize = 0;
206
        this.avoidCachingAvailableValues = false;
207
    }
208

    
209
    protected DefaultFeatureAttributeDescriptor(
210
            DefaultFeatureAttributeDescriptor other
211
    ) {
212
        this();
213
        copyFrom(other);
214
//        LOGGER.info(String.format("Created FeatureAttributeDescriptor [%08x] [%s] (copy).", this.hashCode(), this.name));
215
    }
216

    
217
    @Override
218
    public void copyFrom(DynField other1) {
219
        if (!(other1 instanceof DefaultFeatureAttributeDescriptor)) {
220
            throw new IllegalArgumentException("Can't copy from a non DefaultFeatureAttributeDescriptor");
221
        }
222
        DefaultFeatureAttributeDescriptor other = (DefaultFeatureAttributeDescriptor) other1;
223
        this.typeRef = other.typeRef;
224
        this.allowNull = other.allowNull;
225
        this.dataType = other.dataType;
226
        this.dateFormat = other.dateFormat;
227
        this.defaultValue = other.defaultValue;
228
        this.index = other.index;
229
        this.maximumOccurrences = other.maximumOccurrences;
230
        this.minimumOccurrences = other.minimumOccurrences;
231
        this.size = other.size;
232
        this.name = other.name;
233
        this.objectClass = other.objectClass;
234
        this.precision = other.precision;
235
        this.scale = other.scale;
236
        this.roundMode = other.roundMode;
237
        this.evaluator = other.evaluator;
238
        this.primaryKey = other.primaryKey;
239
        this.readOnly = other.readOnly;
240
        this.SRS = other.SRS;
241
        this.geometryType = other.geometryType;
242
        this.geometrySubType = other.geometrySubType;
243
        this.geomType = other.geomType;
244
        if (other.additionalInfo != null) {
245
            this.additionalInfo = new HashMap();
246
            for (Entry<String, String> entry : other.additionalInfo.entrySet()) {
247
                this.additionalInfo.put(entry.getKey(), entry.getValue());
248
            }
249
        } else {
250
            this.additionalInfo = null;
251
        }
252
        this.isAutomatic = other.isAutomatic;
253
        this.isTime = other.isTime;
254
        this.featureAttributeEmulator = other.featureAttributeEmulator;
255
        this.indexed = other.indexed;
256
        this.isIndexAscending = other.isIndexAscending;
257
        this.allowIndexDuplicateds = other.allowIndexDuplicateds;
258
        this.hidden = other.hidden;
259
        this.dataProfile = other.dataProfile;
260

    
261
        this.availableValues = other.availableValues;
262
        this.availableValuesExpression = other.availableValuesExpression;
263
        this.description = other.description;
264
        this.minValue = other.minValue;
265
        this.maxValue = other.maxValue;
266
        this.label = other.label;
267
        this.order = other.order;
268
        this.groupName = other.groupName;
269
        if (other.tags == null) {
270
            this.tags = null;
271
        } else {
272
            try {
273
                this.tags = (Tags) other.tags.clone();
274
            } catch (Exception ex) {
275
            }
276
        }
277
        this.foreingKey = null;
278
        if (other.foreingKey != null) {
279
            try {
280
                this.foreingKey = (DefaultForeingKey) other.foreingKey.clone();
281
            } catch (CloneNotSupportedException ex) {
282
            }
283
        }
284
        if (this.foreingKey != null) {
285
            this.foreingKey.setDescriptor(this);
286
        }
287

    
288
        // TODO: ? Habria que clonarlos ?
289
        this.availableValuesMethod = other.availableValuesMethod;
290
        this.calculateMethod = other.calculateMethod;
291
        this.relationType = other.relationType;
292
        this.locale = other.locale;
293
        this.displaySize = other.displaySize;
294
        this.avoidCachingAvailableValues = other.avoidCachingAvailableValues;
295
    }
296

    
297
    public void setFeatureType(FeatureType type) {
298
        // Usada en la persistencia
299
        if (type == null) {
300
            this.typeRef = null;
301
        } else {
302
            this.typeRef = new WeakReference(type);
303
//            LOGGER.info(String.format("FeatureAttributeDescriptor[%08x] set FeatureType [%08x], ref [%08x].", this.hashCode(), type.hashCode(), typeRef.hashCode()));
304
        }
305
    }
306

    
307
    @Override
308
    public String getDataTypeName() {
309
        if (this.getDataType() == null) {
310
            return "(unknow)";
311
        }
312
        return this.getDataType().getName();
313
    }
314

    
315
    @Override
316
    public DefaultFeatureAttributeDescriptor getCopy() {
317
        return new DefaultFeatureAttributeDescriptor(this);
318
    }
319

    
320
    @Override
321
    public Object clone() throws CloneNotSupportedException {
322
        return new DefaultFeatureAttributeDescriptor(this);
323
    }
324

    
325
    @Override
326
    public boolean allowNull() {
327
        return allowNull;
328
    }
329

    
330
    @Override
331
    public Locale getLocale() {
332
        if (this.locale == null) {
333
            if (this.dataType.isNumeric()) {
334
                this.locale = Locale.ENGLISH;
335
            } else {
336
                this.locale = Locale.getDefault();
337
            }
338
        }
339
        return this.locale;
340
    }
341

    
342
    @Override
343
    public DataType getDataType() {
344
        if (featureAttributeGetter != null) {
345
            return featureAttributeGetter.getDataType();
346
        }
347
        return this.dataType;
348
    }
349

    
350
    public FeatureAttributeDescriptor setDataType(int type) {
351
        this.dataType = ToolsLocator.getDataTypesManager().get(type);
352
        return this;
353
    }
354

    
355
    @Override
356
    public DateFormat getDateFormat() {
357
        return this.dateFormat;
358
    }
359

    
360
    @Override
361
    public Object getDefaultValue() {
362
        return this.defaultValue;
363
    }
364

    
365
    @Override
366
    @Deprecated
367
    public Object getDefaultValueCoerced() {
368
        return getCoercedDefaultValue();
369
    }
370

    
371
    @Override
372
    public Object getCoercedDefaultValue() {
373
        try {
374
            Object value = this.defaultValue;
375
            if (value == null) {
376
                return null;
377
            }
378
            if (ExpressionUtils.isDynamicText(value.toString())) {
379
                value = ExpressionUtils.evaluateDynamicText(value.toString());
380
            }
381
            return this.getDataType().coerce(value);
382
        } catch (CoercionException ex) {
383
            return null;
384
        }
385
    }
386

    
387
    @Override
388
    public Supplier getDefaultValueSupplier() {
389
        return (Supplier) this::getDefaultValueCoerced;
390
    }
391

    
392
    @Override
393
    public DynField setDefaultValueSupplier(Supplier supplier) {
394
        //Do nothing
395
        return this;
396
    }
397

    
398
    @Override
399
    public Evaluator getEvaluator() {
400
        return this.evaluator;
401
    }
402

    
403
    @Override
404
    public int getGeometryType() {
405
        if (this.dataType.getType() != DataTypes.GEOMETRY) {
406
            return Geometry.TYPES.UNKNOWN;
407
        }
408
        return this.geometryType;
409
    }
410

    
411
    @Override
412
    public int getGeometrySubType() {
413
        if (this.dataType.getType() != DataTypes.GEOMETRY) {
414
            return Geometry.SUBTYPES.UNKNOWN;
415
        }
416
        return this.geometrySubType;
417
    }
418

    
419
    @Override
420
    public GeometryType getGeomType() {
421
        if (this.dataType.getType() != DataTypes.GEOMETRY) {
422
            return null;
423
        }
424
        if (this.geomType == null) {
425
            try {
426
                this.geomType
427
                        = GeometryLocator.getGeometryManager().getGeometryType(
428
                                this.geometryType, this.geometrySubType);
429
            } catch (GeometryException e) {
430
                throw new RuntimeException(
431
                        "Error getting geometry type with type = "
432
                        + this.geometryType + ", subtype = "
433
                        + this.geometrySubType, e);
434
            }
435
        }
436
        return this.geomType;
437
    }
438

    
439
    @Override
440
    public int getIndex() {
441
        return this.index;
442
    }
443

    
444
    protected FeatureAttributeDescriptor setIndex(int index) {
445
        this.index = index;
446
        return this;
447
    }
448

    
449
    @Override
450
    public int getMaximumOccurrences() {
451
        return this.maximumOccurrences;
452
    }
453

    
454
    @Override
455
    public int getMinimumOccurrences() {
456
        return this.minimumOccurrences;
457
    }
458

    
459
    @Override
460
    public String getName() {
461
        return this.name;
462
    }
463

    
464
    public FeatureAttributeDescriptor setName(String name) {
465
//        LOGGER.info(String.format("FeatureAttributeDescriptor[%08x] set name [%s].", this.hashCode(), name));
466
        this.name = name;
467
        return this;
468
    }
469

    
470
    @Override
471
    public Class getObjectClass() {
472
        if (getDataType().getType() == DataTypes.OBJECT) {
473
            return objectClass;
474
        }
475
        return getDataType().getDefaultClass();
476
    }
477

    
478
    @Override
479
    public int getPrecision() {
480
        return this.precision;
481
    }
482

    
483
    @Override
484
    public int getScale() {
485
        return this.scale;
486
    }
487

    
488
    @Override
489
    public Coercion getCoercion() {
490
        return this.getDataType().getCoercion();
491
    }
492

    
493
    @Override
494
    public MathContext getMathContext() {
495
        if (this.mathContext == null) {
496
            if (this.getDataType().isNumeric()) {
497
                this.mathContext = new MathContext(
498
                        this.getPrecision(),
499
                        RoundingMode.valueOf(this.getRoundMode())
500
                );
501
            } else {
502
                this.mathContext = MathContext.UNLIMITED;
503
            }
504
        }
505
        return this.mathContext;
506
    }
507

    
508
    @Override
509
    public CoercionContext getCoercionContext() {
510
        if (this.coerceContext == null) {
511
            if (this.getDataType().isNumeric()) {
512
                this.coerceContext = DataTypeUtils.coerceContextDecimal(
513
                        this.getLocale(),
514
                        this.getPrecision(),
515
                        this.getScale(),
516
                        this.getRoundMode()
517
                );
518
            } else if (this.getType() == DataTypes.GEOMETRY) {
519
                GeometryCoercionContext context = GeometryLocator.getGeometryManager().createGeometryCoercionContext();
520
                context.setGeometryType(this.getGeomType());
521
                context.setMode(GeometryCoercionContext.MODE_ONERROR_DONTCONVERT);
522
                this.coerceContext = context;
523
            } else {
524
                this.coerceContext = DataTypeUtils.coerceContextLocale(
525
                        this.getLocale()
526
                );
527
            }
528
        }
529
        return this.coerceContext;
530
    }
531

    
532
    @Override
533
    public int getRoundMode() {
534
        return this.roundMode;
535
    }
536

    
537
    @Override
538
    public IProjection getSRS() {
539
        return this.SRS;
540
    }
541

    
542
    @Override
543
    public Interval getInterval() {
544
        return this.interval;
545
    }
546

    
547
    public IProjection getSRS(WeakReference storeRef) {
548
        if (this.SRS == null) {
549
            FeatureStore store = (FeatureStore) storeRef.get();
550
            this.SRS = (IProjection) store.getDynValue(DataStore.METADATA_CRS);
551
        }
552
        return this.SRS;
553
    }
554

    
555
    @Override
556
    public int getSize() {
557
        return this.size;
558
    }
559

    
560
    @Override
561
    public boolean isPrimaryKey() {
562
        return this.primaryKey;
563
    }
564

    
565
    @Override
566
    public boolean isReadOnly() {
567
        if (this.readOnly) {
568
            return true;
569
        }
570
        return this.isComputed();
571
    }
572

    
573
    @Override
574
    public String getAdditionalInfo(String infoName) {
575
        if (this.additionalInfo == null) {
576
            return null;
577
        }
578
        return this.additionalInfo.get(infoName);
579
    }
580

    
581
    @Override
582
    public boolean isAutomatic() {
583
        return this.isAutomatic;
584
    }
585

    
586
    @Override
587
    public boolean equals(Object obj) {
588
        if (this == obj) {
589
            return true;
590
        }
591
        if (!(obj instanceof DefaultFeatureAttributeDescriptor)) {
592
            return false;
593
        }
594
        DefaultFeatureAttributeDescriptor other
595
                = (DefaultFeatureAttributeDescriptor) obj;
596

    
597
        if (this.allowNull != other.allowNull) {
598
            return false;
599
        }
600

    
601
        if (this.index != other.index) {
602
            return false;
603
        }
604

    
605
        if (!Objects.equals(this.name, other.name)) {
606
            return false;
607
        }
608

    
609
        if (this.getDataType() != other.getDataType()) {
610
            return false;
611
        }
612

    
613
        if (this.size != other.size) {
614
            return false;
615
        }
616

    
617
        if (!Objects.equals(this.defaultValue, other.defaultValue)) {
618
            return false;
619
        }
620

    
621
        if (this.primaryKey != other.primaryKey) {
622
            return false;
623
        }
624

    
625
        if (this.isAutomatic != other.isAutomatic) {
626
            return false;
627
        }
628

    
629
        if (this.readOnly != other.readOnly) {
630
            return false;
631
        }
632

    
633
        if (this.precision != other.precision) {
634
            return false;
635
        }
636

    
637
        if (this.maximumOccurrences != other.maximumOccurrences) {
638
            return false;
639
        }
640

    
641
        if (this.minimumOccurrences != other.minimumOccurrences) {
642
            return false;
643
        }
644

    
645
        if (this.geometryType != other.geometryType) {
646
            return false;
647
        }
648

    
649
        if (this.geometrySubType != other.geometrySubType) {
650
            return false;
651
        }
652

    
653
        if (!Objects.equals(this.evaluator, other.evaluator)) {
654
            return false;
655
        }
656

    
657
        if (!Objects.equals(this.featureAttributeEmulator, other.featureAttributeEmulator)) {
658
            return false;
659
        }
660

    
661
        if (!Objects.equals(this.SRS, other.SRS)) {
662
            return false;
663
        }
664

    
665
        if (!Objects.equals(this.dateFormat, other.dateFormat)) {
666
            return false;
667
        }
668

    
669
        if (!Objects.equals(this.objectClass, other.objectClass)) {
670
            return false;
671
        }
672

    
673
        if (!Objects.equals(this.dataProfile, other.dataProfile)) {
674
            return false;
675
        }
676

    
677
        return true;
678
    }
679

    
680
    @Override
681
    public void loadFromState(PersistentState state)
682
            throws PersistenceException {
683
        allowNull = state.getBoolean("allowNull");
684
        dataType = ToolsLocator.getDataTypesManager().get(state.getInt("dataType"));
685
        dataProfile = state.getString("dataProfile");
686

    
687
//        FIXME: dateFormat;
688
        try {
689
            defaultValue = dataType.coerce(state.get("defaultValue"));
690
        } catch (CoercionException ex) {
691
        }
692

    
693
        index = state.getInt("index");
694
        maximumOccurrences = state.getInt("maximumOccurrences");
695
        minimumOccurrences = state.getInt("minimumOccurrences");
696
        size = state.getInt("size");
697
        name = state.getString("name");
698
        try {
699
            String objectClassName = state.getString("objectClass");
700
            if (!StringUtils.isBlank(objectClassName)) {
701
                objectClass = Class.forName(objectClassName);
702
            }
703
        } catch (Throwable e) {
704
            LOGGER.warn("Can't restore the objectClass of the FeatureAttributreDescriptor", e);
705
        }
706
        precision = state.getInt("precision");
707
        scale = state.getInt("scale");
708
        roundMode = state.getInt("roundMode");
709
        String locale_s = state.getString("locale");
710
        locale = (StringUtils.isBlank(locale_s) || "null".equalsIgnoreCase(locale_s)) ? null : Locale.forLanguageTag(locale_s);
711
        evaluator = (Evaluator) state.get("evaluator");
712
        primaryKey = state.getBoolean("primaryKey");
713
        readOnly = state.getBoolean("readOnly");
714
        SRS = (IProjection) state.get("SRS");
715
        geometryType = state.getInt("geometryType");
716
        geometrySubType = state.getInt("geometrySubType");
717
        if (geometryType != Geometry.TYPES.UNKNOWN
718
                && geometrySubType != Geometry.SUBTYPES.UNKNOWN) {
719
            geomType = GeometryUtils.getGeometryType(
720
                    geometryType,
721
                    geometrySubType
722
            );
723
        }
724
//        additionalInfo = (Map) state.get("aditionalInfo");
725
        isAutomatic = state.getBoolean("isAutomatic");
726
        isTime = state.getBoolean("isTime");
727
        if (state.hasValue("intervalStart")) {
728
            long intervalStart = state.getLong("interval_start");
729
            long intervalEnd = state.getLong("interval_end");
730
            interval = TimeSupportLocator.getManager().createRelativeInterval(intervalStart, intervalEnd);
731
        } else {
732
            interval = null;
733
        }
734
        featureAttributeEmulator = (FeatureAttributeEmulator) state.get("featureAttributeEmulator");
735
        indexed = state.getBoolean("indexed");
736
        isIndexAscending = state.getBoolean("isIndexAscending");
737
        allowIndexDuplicateds = state.getBoolean("allowIndexDuplicateds");
738

    
739
        Map<String, Object> values = state.getMap("availableValues");
740
        if (values == null || values.isEmpty()) {
741
            this.availableValues = null;
742
        } else {
743
            this.availableValues = new DynObjectValueItem[values.size()];
744
            int n = 0;
745
            for (Entry<String, Object> entry : values.entrySet()) {
746
                this.availableValues[n++] = new DynObjectValueItem(entry.getValue(), entry.getKey());
747
            }
748
        }
749

    
750
        description = state.getString("description");
751
        minValue = state.get("minValue");
752
        maxValue = state.get("maxValue");
753
        label = state.getString("label");
754
        order = state.getInt("order");
755
        hidden = state.getBoolean("hidden");
756
        groupName = state.getString("groupName");
757
        relationType = state.getInt("relationType", RELATION_TYPE_NONE);
758

    
759
        foreingKey = (DefaultForeingKey) state.get("foreingKey");
760
        if (foreingKey != null) {
761
            this.foreingKey.setDescriptor(this);
762
        }
763
        tags = (Tags) state.get("tags");
764
        if (tags == null) {
765
            this.tags = new DefaultTags();
766
        }
767
        displaySize = state.getInt("displaySize", 0);
768
        availableValuesExpression = (Expression) state.get("availableValuesExpression");
769
        avoidCachingAvailableValues = state.getBoolean("avoidCachingAvailableValues", false);
770
        availableValuesCache = null;
771

    
772
    }
773

    
774
    @Override
775
    public void saveToState(PersistentState state) throws PersistenceException {
776
        Coercion toString = ToolsLocator.getDataTypesManager().getCoercion(DataTypes.STRING);
777

    
778
        state.set("allowNull", allowNull);
779
        state.set("dataType", dataType.getType());
780
        state.set("dataProfile", dataProfile);
781

    
782
//        FIXME: dateFormat;
783
        state.set("defaultValue", Objects.toString(defaultValue, null));
784

    
785
        state.set("index", index);
786
        state.set("maximumOccurrences", maximumOccurrences);
787
        state.set("minimumOccurrences", minimumOccurrences);
788
        state.set("size", size);
789
        state.set("name", name);
790
        state.set("objectClass", objectClass == null ? null : objectClass.getName());
791
        state.set("precision", precision);
792
        state.set("scale", scale);
793
        state.set("roundMode", roundMode);
794
        if (this.locale == null) {
795
            state.setNull("locale");
796
        } else {
797
            state.set("locale", this.locale.toLanguageTag()); //toString.coerce(this.locale));
798
        }
799
        state.set("evaluator", evaluator);
800

    
801
        state.set("primaryKey", primaryKey);
802
        state.set("readOnly", readOnly);
803
        state.set("SRS", SRS);
804
        GeometryType theGeomType = this.getGeomType();
805
        if (theGeomType == null) {
806
            state.set("geometryType", Geometry.TYPES.UNKNOWN);
807
            state.set("geometrySubType", Geometry.SUBTYPES.UNKNOWN);
808
        } else {
809
            state.set("geometryType", theGeomType.getType());
810
            state.set("geometrySubType", theGeomType.getSubType());
811
        }
812

    
813
//      FIXME: additionalInfo
814
        state.set("isAutomatic", isAutomatic);
815
        state.set("isTime", isTime);
816
        if (this.interval == null) {
817
            state.setNull("interval_start");
818
            state.setNull("interval_end");
819
        } else {
820
            state.set("interval_start", ((RelativeInterval) interval).getStart().toMillis());
821
            state.set("interval_end", ((RelativeInterval) interval).getEnd().toMillis());
822
        }
823
        state.set("SRS", SRS);
824

    
825
//      FIXME: featureAttributeGetter
826
        if (featureAttributeEmulator instanceof Persistent) {
827
            state.set("featureAttributeEmulator", featureAttributeEmulator);
828
        } else {
829
            state.setNull("featureAttributeEmulator");
830
        }
831

    
832
        state.set("indexed", indexed);
833
        state.set("isIndexAscending", isIndexAscending);
834
        state.set("allowIndexDuplicateds", allowIndexDuplicateds);
835

    
836
        if (this.availableValues == null) {
837
            state.setNull("availableValues");
838
        } else {
839
            Map<String, Object> values = new LinkedHashMap<>();
840
            for (DynObjectValueItem value : availableValues) {
841
                values.put(value.getLabel(), value.getValue());
842
            }
843
            state.set("availableValues", values);
844
        }
845
        state.set("description", description);
846
        state.set("minValue", minValue);
847
        state.set("maxValue", maxValue);
848
        state.set("label", label);
849
        state.set("order", order);
850
        state.set("hidden", hidden);
851
        state.set("groupName", groupName);
852
        state.set("relationType", relationType);
853

    
854
        state.set("foreingKey", this.foreingKey);
855
        state.set("tags", this.tags);
856

    
857
        state.set("displaySize", displaySize);
858
        state.set("availableValuesExpression", availableValuesExpression);
859
        state.set("avoidCachingAvailableValues", avoidCachingAvailableValues);
860
    }
861

    
862
    private static final String FEATATTRDESC_PERSISTENCE_DEFINITION_NAME = "FeatureAttributeDescriptor";
863

    
864
    public static void registerPersistenceDefinition() {
865
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
866

    
867
        if (manager.getDefinition(FEATATTRDESC_PERSISTENCE_DEFINITION_NAME)
868
                == null) {
869
            DynStruct definition = manager.addDefinition(DefaultFeatureAttributeDescriptor.class,
870
                    FEATATTRDESC_PERSISTENCE_DEFINITION_NAME,
871
                    FEATATTRDESC_PERSISTENCE_DEFINITION_NAME
872
                    + " persistent definition",
873
                    null,
874
                    null
875
            );
876
            definition.addDynFieldBoolean("allowNull");
877
            definition.addDynFieldInt("dataType");
878
            definition.addDynFieldString("dataProfile");
879
//            definition.addDynFieldString("dateFormat");
880
            definition.addDynFieldString("defaultValue");
881
            definition.addDynFieldInt("index");
882
            definition.addDynFieldInt("maximumOccurrences");
883
            definition.addDynFieldInt("minimumOccurrences");
884
            definition.addDynFieldInt("size");
885
            definition.addDynFieldString("name");
886
            definition.addDynFieldString("objectClass");
887
            definition.addDynFieldInt("precision");
888
            definition.addDynFieldInt("scale").setMandatory(false).setDefaultDynValue(DataType.SCALE_NONE);
889
            definition.addDynFieldInt("roundMode").setMandatory(false).setDefaultDynValue(BigDecimal.ROUND_HALF_UP);
890
            definition.addDynFieldString("locale").setMandatory(false).setDefaultDynValue("null");
891
            definition.addDynFieldObject("evaluator").setClassOfValue(Evaluator.class);
892
            definition.addDynFieldBoolean("primaryKey");
893
            definition.addDynFieldBoolean("readOnly");
894
            definition.addDynFieldObject("SRS")
895
                    .setClassOfValue(IProjection.class);
896
            definition.addDynFieldInt("geometryType");
897
            definition.addDynFieldInt("geometrySubType");
898
//            definition.addDynFieldMap("additionalInfo");
899
            definition.addDynFieldBoolean("isAutomatic");
900
            definition.addDynFieldBoolean("isTime");
901
            definition.addDynFieldLong("interval_start");
902
            definition.addDynFieldLong("interval_end");
903
            definition.addDynFieldObject("featureAttributeEmulator")
904
                    .setClassOfValue(FeatureAttributeEmulator.class);
905
            definition.addDynFieldBoolean("indexed");
906
            definition.addDynFieldBoolean("isIndexAscending");
907
            definition.addDynFieldBoolean("allowIndexDuplicateds");
908
            definition.addDynFieldMap("availableValues")
909
                    .setClassOfItems(Object.class);
910
            definition.addDynFieldString("description");
911
            definition.addDynFieldObject("minValue");
912
            definition.addDynFieldObject("maxValue");
913
            definition.addDynFieldString("label");
914
            definition.addDynFieldInt("order");
915
            definition.addDynFieldBoolean("hidden");
916
            definition.addDynFieldBoolean("avoidCachingAvailableValues");
917
            definition.addDynFieldString("groupName");
918
            definition.addDynFieldInt("relationType");
919

    
920
            definition.addDynFieldObject("foreingKey")
921
                    .setClassOfValue(DefaultForeingKey.class);
922

    
923
            definition.addDynFieldObject("tags")
924
                    .setClassOfValue(Tags.class);
925

    
926
            definition.addDynFieldInt("displaySize").setMandatory(false);
927
            definition.addDynFieldObject("availableValuesExpression")
928
                    .setClassOfValue(Expression.class)
929
                    .setMandatory(false);
930
        }
931
    }
932

    
933
    /*
934
     * Start of DynField interface Implementation
935
     *
936
     */
937
    @Override
938
    public Tags getTags() {
939
        return tags;
940
    }
941

    
942
    private Expression availableValuesFilter;
943

    
944
    @Override
945
    public Expression getAvailableValuesFilter() {
946
        return this.availableValuesFilter;
947
    }
948

    
949
    public FeatureAttributeDescriptor setAvailableValuesFilter(Expression filter) {
950
        this.availableValuesFilter = filter;
951
        return this;
952
    }
953

    
954
    @Override
955
    public boolean hasConstantAvailableValues() {
956
        return this.availableValues != null;
957
    }
958

    
959
    @Override
960
    public boolean isAvoidCachingAvailableValues() {
961
        return this.avoidCachingAvailableValues;
962
    }
963

    
964
    public boolean hasAvailableValues() {
965
        return getAvailableValues() != null;
966
    }
967

    
968
    @Override
969
    public DynObjectValueItem[] getAvailableValues(DynObject context) {
970
        if (this.availableValuesMethod != null) {
971
            DynObjectValueItem[] values;
972
            try {
973
                values = (DynObjectValueItem[]) this.availableValuesMethod.invoke(context, new Object[]{this});
974
            } catch (DynMethodException ex) {
975
                return this.getAvailableValues();
976
            }
977
            if (values != null) {
978
                return values;
979
            }
980
        }
981
        Expression filter = this.availableValuesFilter;
982
        if (!ExpressionUtils.isEmpty(filter)) {
983
            if (this.isForeingKey() && this.foreingKey.isClosedList()) {
984
                ContextForeingKey foreingkeyContext = this.foreingKey.createContext();
985
                foreingkeyContext.setContextValues(context);
986
                DynObjectValueItem[] values = this.foreingKey.getAvailableValues(foreingkeyContext);
987
                return values;
988
            }
989
            MutableSymbolTable contextSymbolTable = ExpressionUtils.createSymbolTable("feature", context);
990
            MutableSymbolTable symbolTable = ExpressionUtils.createSymbolTable();
991
            symbolTable.addSymbolTable(contextSymbolTable);
992

    
993
            DynObjectValueItem[] allValues = this.getAvailableValues();
994
            List<DynObjectValueItem> filteredValues = new ArrayList<>();
995
            for (DynObjectValueItem value : allValues) {
996
                symbolTable.setVar("$value", value.getValue());
997
                symbolTable.setVar("$label", value.getLabel());
998
                Object include = filter.execute(symbolTable);
999
                if (DataTypeUtils.isFalse(include, false)) {
1000
                    continue;
1001
                }
1002
                filteredValues.add(value);
1003
            }
1004
            DynObjectValueItem[] values = filteredValues.toArray(
1005
                    new DynObjectValueItem[filteredValues.size()]
1006
            );
1007
            return values;
1008
        }
1009
        return this.getAvailableValues();
1010
    }
1011

    
1012
    @Override
1013
    public boolean isAvailableValuesCalculated() {
1014
        if (this.availableValuesMethod != null) {
1015
            return true;
1016
        }
1017
        if (!ExpressionUtils.isEmpty(this.availableValuesFilter)) {
1018
            return true;
1019
        }
1020
        return false;
1021
    }
1022

    
1023
    @Override
1024
    public DynObjectValueItem[] getAvailableValues() {
1025
        DynObjectValueItem[] values = this.availableValues;
1026

    
1027
        if (values != null) {
1028
            return values;
1029
        }
1030
        values = this.availableValuesCache;
1031
        if (values != null) {
1032
            return values;
1033
        }
1034
        if (this.isForeingKey() && this.foreingKey.isClosedList()) {
1035
            values = this.foreingKey.getAvailableValues(null);
1036

    
1037
        } else if (this.availableValuesExpression != null) {
1038
            values = this.getAvailableValuesFromExpression();
1039
        }
1040
        if (!this.avoidCachingAvailableValues) {
1041
            this.availableValuesCache = values;
1042
        }
1043
        return values;
1044
    }
1045

    
1046
    private DynObjectValueItem[] getAvailableValuesFrom(GetItemWithSize values) {
1047
        if (values.size() == 0) {
1048
            return null;
1049
        }
1050
        DynObjectValueItem[] r = null;
1051
        Object firstelement = values.get(0);
1052
        if (firstelement instanceof LabeledValue) {
1053
            r = new DynObjectValueItem[values.size()];
1054
            for (int i = 0; i < values.size(); i++) {
1055
                LabeledValue v = (LabeledValue) values.get(i);
1056
                r[i] = new DynObjectValueItem(
1057
                        v.getValue(),
1058
                        Objects.toString(v.getLabel(), Objects.toString(v.getValue(), String.valueOf(i)))
1059
                );
1060
            }
1061
        } else if (firstelement instanceof Pair) {
1062
            r = new DynObjectValueItem[values.size()];
1063
            for (int i = 0; i < values.size(); i++) {
1064
                Pair v = (Pair) values.get(i);
1065
                r[i] = new DynObjectValueItem(
1066
                        v.getValue(),
1067
                        Objects.toString(v.getKey(), Objects.toString(v.getValue(), String.valueOf(i)))
1068
                );
1069
            }
1070
        } else if (firstelement instanceof JsonObject) {
1071
            JsonObject v = (JsonObject) firstelement;
1072
            String labelname = null;
1073
            for (String theName : new String[]{
1074
                "name", "label", "key", "description"
1075
            }) {
1076
                if (v.containsKey(theName)) {
1077
                    labelname = theName;
1078
                    break;
1079
                }
1080
                if (v.containsKey(theName.toUpperCase())) {
1081
                    labelname = theName.toLowerCase();
1082
                    break;
1083
                }
1084
            }
1085
            String valuename = null;
1086
            if (v.containsKey("value")) {
1087
                valuename = "value";
1088
            }
1089
            r = new DynObjectValueItem[values.size()];
1090
            for (int i = 0; i < values.size(); i++) {
1091
                v = (JsonObject) values.get(i);
1092
                String theLabel;
1093
                Object theValue;
1094
                if (labelname == null) {
1095
                    theLabel = v.toString();
1096
                } else {
1097
                    theLabel = v.getString(labelname);
1098
                }
1099
                if (valuename == null) {
1100
                    theValue = v.getString(valuename);
1101
                } else {
1102
                    theValue = v;
1103
                }
1104
                r[i] = new DynObjectValueItem(theValue, theLabel);
1105
            }
1106
        } else if (firstelement instanceof Map) {
1107
            Map<String, Object> v = (Map<String, Object>) firstelement;
1108
            String labelname = null;
1109
            for (String theName : new String[]{
1110
                "name", "label", "key", "description"
1111
            }) {
1112
                if (v.containsKey(theName)) {
1113
                    labelname = theName;
1114
                    break;
1115
                }
1116
                if (v.containsKey(theName.toUpperCase())) {
1117
                    labelname = theName.toLowerCase();
1118
                    break;
1119
                }
1120
            }
1121
            String valuename = null;
1122
            if (v.containsKey("value")) {
1123
                valuename = "value";
1124
            }
1125
            r = new DynObjectValueItem[values.size()];
1126
            for (int i = 0; i < values.size(); i++) {
1127
                v = (Map<String, Object>) values.get(i);
1128
                String theLabel;
1129
                Object theValue;
1130
                if (labelname == null) {
1131
                    theLabel = v.toString();
1132
                } else {
1133
                    theLabel = (String) v.get(labelname);
1134
                }
1135
                if (valuename == null) {
1136
                    theValue = v;
1137
                } else {
1138
                    theValue = v.get(valuename);
1139
                }
1140
                r[i] = new DynObjectValueItem(theValue, theLabel);
1141
            }
1142
        } else if (firstelement instanceof Feature) {
1143
            Feature v = (Feature) firstelement;
1144
            FeatureType featureType = v.getType();
1145
            String valuename = null;
1146
            FeatureAttributeDescriptor[] pks = featureType.getPrimaryKey();
1147
            if (pks != null && pks.length == 1) {
1148
                valuename = pks[0].getName();
1149
            }
1150
            String labelname = null;
1151
            for (String theName : new String[]{
1152
                "name", "label", "key", "description"
1153
            }) {
1154
                if (featureType.get(theName) != null) {
1155
                    labelname = theName;
1156
                    break;
1157
                }
1158
            }
1159
            r = new DynObjectValueItem[values.size()];
1160
            for (int i = 0; i < values.size(); i++) {
1161
                v = (Feature) values.get(i);
1162
                String theLabel;
1163
                Object theValue;
1164
                if (labelname == null) {
1165
                    theLabel = v.toString();
1166
                } else {
1167
                    theLabel = v.getString(labelname);
1168
                }
1169
                if (valuename == null) {
1170
                    theValue = v.getReference().getCode();
1171
                } else {
1172
                    theValue = v.get(valuename);
1173
                }
1174
                r[i] = new DynObjectValueItem(theValue, theLabel);
1175
            }
1176
        }
1177
        return r;
1178
    }
1179

    
1180
    private DynObjectValueItem[] getAvailableValuesFromExpression() {
1181
        if (this.availableValuesExpression == null || this.availableValuesExpression.isEmpty()) {
1182
            return null;
1183
        }
1184
        try {
1185
            Object value = this.availableValuesExpression.execute(null);
1186
            if (value instanceof DynObjectValueItem[]) {
1187
                return (DynObjectValueItem[]) value;
1188
            }
1189
            if (value instanceof List) {
1190
                return this.getAvailableValuesFrom(new GetItemWithSize() {
1191
                    @Override
1192
                    public Object get(int i) {
1193
                        return ((List) value).get(i);
1194
                    }
1195

    
1196
                    @Override
1197
                    public int size() {
1198
                        return ((List) value).size();
1199
                    }
1200
                });
1201
            }
1202
        } catch (Throwable th) {
1203
            LOGGER.warn("Can't get available values from expression", th);
1204
        }
1205
        return null;
1206
    }
1207

    
1208
    @Override
1209
    public Expression getAvailableValuesExpression() {
1210
        return this.availableValuesExpression;
1211
    }
1212

    
1213
    @Override
1214
    public FeatureAttributeDescriptor setAvailableValuesExpression(String expression) {
1215
        if (StringUtils.isBlank(expression)) {
1216
            this.availableValuesExpression = null;
1217
            return this;
1218
        }
1219
        this.availableValuesExpression = ExpressionUtils.createExpression(expression);
1220
        return this;
1221
    }
1222

    
1223
    @Override
1224
    public FeatureAttributeDescriptor setAvailableValuesExpression(Expression expression) {
1225
        this.availableValuesExpression = expression;
1226
        return this;
1227
    }
1228

    
1229
    @Override
1230
    public String getLabelOfValue(Object value) {
1231
        if (this.labelOfValueMap != null) {
1232
            String theLabel = this.labelOfValueMap.get(value);
1233
            if (theLabel == null) {
1234
                theLabel = Objects.toString(value, "");
1235
            }
1236
            return theLabel;
1237
        }
1238
        DynObjectValueItem[] values = this.getAvailableValues();
1239
        if (values == null) {
1240
            return Objects.toString(value, "");
1241
        }
1242
        Map<Object, String> map = new LinkedHashMap<>();
1243
        for (DynObjectValueItem theValue : values) {
1244
            map.put(theValue.getValue(), theValue.getLabel());
1245
        }
1246
        this.labelOfValueMap = map;
1247
        String theLabel = this.labelOfValueMap.get(value);
1248
        if (theLabel == null) {
1249
            theLabel = Objects.toString(value, "");
1250
        }
1251
        return theLabel;
1252
    }
1253

    
1254
    @Override
1255
    public String getDescription() {
1256
        if (this.description == null) {
1257
            return getName();
1258
        }
1259
        return this.description;
1260
    }
1261

    
1262
    @Override
1263
    public Object getMaxValue() {
1264
        return this.maxValue;
1265
    }
1266

    
1267
    @Override
1268
    public Object getMinValue() {
1269
        return this.minValue;
1270
    }
1271

    
1272
    @Override
1273
    public int getTheTypeOfAvailableValues() {
1274
        return 1;
1275
    }
1276

    
1277
    @Override
1278
    public int getType() {
1279
        if (featureAttributeGetter != null) {
1280
            return featureAttributeGetter.getDataType().getType();
1281
        }
1282
        return getDataType().getType();
1283
    }
1284

    
1285
    @Override
1286
    public boolean isMandatory() {
1287
        return !allowNull() || isPrimaryKey();
1288
    }
1289

    
1290
    @Override
1291
    public boolean isPersistent() {
1292
        return false;
1293
    }
1294

    
1295
    @Override
1296
    public DynField setAvailableValues(DynObjectValueItem[] values) {
1297
        if (ArrayUtils.isEmpty(values)) {
1298
            this.availableValues = null;
1299
        } else {
1300
            this.availableValues = values;
1301
        }
1302
        return this;
1303
    }
1304

    
1305
    @Override
1306
    public DynField setDescription(String description) {
1307
        this.description = description;
1308
        return this;
1309
    }
1310

    
1311
    @Override
1312
    public DynField setMandatory(boolean mandatory) {
1313
        throw new UnsupportedOperationException();
1314
    }
1315

    
1316
    @Override
1317
    public DynField setMaxValue(Object maxValue) {
1318
        try {
1319
            this.maxValue = this.coerce(maxValue);
1320
        } catch (CoercionException e) {
1321
            throw new IllegalArgumentException(e);
1322
        }
1323
        return this;
1324
    }
1325

    
1326
    @Override
1327
    public DynField setMinValue(Object minValue) {
1328
        try {
1329
            this.maxValue = this.coerce(minValue);
1330
        } catch (CoercionException e) {
1331
            throw new IllegalArgumentException(e);
1332
        }
1333
        return this;
1334
    }
1335

    
1336
    @Override
1337
    public DynField setPersistent(boolean persistent) {
1338
        throw new UnsupportedOperationException();
1339
    }
1340

    
1341
    @Override
1342
    public DynField setTheTypeOfAvailableValues(int type) {
1343
        throw new UnsupportedOperationException();
1344
    }
1345

    
1346
    @Override
1347
    public DynField setType(int type) {
1348
        throw new UnsupportedOperationException();
1349
    }
1350

    
1351
    @Override
1352
    @Deprecated
1353
    public DynField setDefaultDynValue(Object defaultValue) {
1354
        return this.setDefaultFieldValue(defaultValue);
1355
    }
1356

    
1357
    @Override
1358
    public DynField setDefaultFieldValue(Object defaultValue) {
1359
        this.defaultValue = defaultValue;
1360
        return this;
1361
    }
1362

    
1363
    @Override
1364
    public Class getClassOfValue() {
1365
        return null;
1366
    }
1367

    
1368
    @Override
1369
    public DynField getElementsType() {
1370
        return null;
1371
    }
1372

    
1373
    @Override
1374
    public DynField setClassOfValue(Class theClass)
1375
            throws DynFieldIsNotAContainerException {
1376
        throw new UnsupportedOperationException();
1377
    }
1378

    
1379
    @Override
1380
    public DynField setElementsType(DynStruct type)
1381
            throws DynFieldIsNotAContainerException {
1382
        throw new UnsupportedOperationException();
1383
    }
1384

    
1385
    @Override
1386
    public DynField setElementsType(int type)
1387
            throws DynFieldIsNotAContainerException {
1388
        throw new UnsupportedOperationException();
1389
    }
1390

    
1391
    public FeatureAttributeDescriptor setDataProfileName(String dataProfile) {
1392
        this.dataProfile = dataProfile;
1393
        return this;
1394
    }
1395

    
1396
    @Override
1397
    public String getDataProfileName() {
1398
        return dataProfile;
1399
    }
1400

    
1401
    @Override
1402
    public DataProfile getDataProfile() {
1403
        if (StringUtils.isBlank(dataProfile)) {
1404
            return null;
1405
        }
1406
        DataProfile profile = DALLocator.getDataManager().getDataProfile(dataProfile);
1407
        return profile;
1408
    }
1409

    
1410
    @Override
1411
    public void validate(Object value) throws DynFieldValidateException {
1412

    
1413
        if (value == null && !this.allowNull()) {
1414
            throw new DynFieldValidateException(value, this, null);
1415
        }
1416

    
1417
        try {
1418
            this.dataType.coerce(value);
1419
        } catch (CoercionException e) {
1420
            throw new DynFieldValidateException(value, this, e);
1421
        }
1422

    
1423
        /*
1424
         * Other checks will be needed
1425
         */
1426
    }
1427

    
1428
    @Override
1429
    public String getSubtype() {
1430
        if (featureAttributeGetter != null) {
1431
            return featureAttributeGetter.getDataType().getSubtype();
1432
        }
1433
        return this.dataType.getSubtype();
1434
    }
1435

    
1436
    @Override
1437
    public Object coerce(Object value) throws CoercionException {
1438
        if (value == null) {
1439
            return value; // O debe devolver this.defaultValue
1440
        }
1441
        try {
1442
            return this.getDataType().coerce(value, this.getCoercionContext());
1443
        } catch (Exception ex) {
1444
            throw new RuntimeException(ex);
1445
        }
1446
    }
1447

    
1448
    @Override
1449
    public DynField setAvailableValues(List values) {
1450
        if (values == null || values.isEmpty()) {
1451
            this.availableValues = null;
1452
        } else {
1453
            this.availableValues = (DynObjectValueItem[]) values.toArray(
1454
                    new DynObjectValueItem[values.size()]
1455
            );
1456
        }
1457
        return this;
1458
    }
1459

    
1460
    @Override
1461
    public String getGroup() {
1462
        return this.groupName;
1463
    }
1464

    
1465
    @Override
1466
    public int getOder() {
1467
        return this.order;
1468
    }
1469

    
1470
    @Override
1471
    public String getLabel() {
1472
        if (this.label == null) {
1473
            return this.getName();
1474
        }
1475
        return this.label;
1476
    }
1477

    
1478
    @Override
1479
    public String getLocalizedLabel() {
1480
        if (StringUtils.isBlank(this.label)) {
1481
            return this.getName();
1482
        }
1483
        I18nManager i18n = ToolsLocator.getI18nManager();
1484
        return i18n.getTranslation(this.label);
1485
    }
1486

    
1487
    @Override
1488
    public DynField setLabel(String label) {
1489
        this.label = label;
1490
        return this;
1491
    }
1492

    
1493
    @Override
1494
    public DynField setShortLabel(String shortLabel) {
1495
        this.shortLabel = shortLabel;
1496
        return this;
1497
    }
1498

    
1499
    @Override
1500
    public String getShortLabel() {
1501
        return StringUtils.isBlank(shortLabel) ? getLabel() : shortLabel;
1502
    }
1503

    
1504
    @Override
1505
    public String getLocalizedShortLabel() {
1506
        if (StringUtils.isBlank(shortLabel)) {
1507
            return this.getLocalizedLabel();
1508
        }
1509
        I18nManager i18n = ToolsLocator.getI18nManager();
1510
        return i18n.getTranslation(shortLabel);
1511
    }
1512

    
1513
    @Override
1514
    public DynField setGroup(String groupName) {
1515
        this.groupName = groupName;
1516
        return this;
1517
    }
1518

    
1519
    @Override
1520
    public DynField setOrder(int order) {
1521
        this.order = order;
1522
        return this;
1523
    }
1524

    
1525
    @Override
1526
    public DynField setHidden(boolean hidden) {
1527
        this.hidden = hidden;
1528
        return this;
1529
    }
1530

    
1531
    @Override
1532
    public boolean isHidden() {
1533
        return this.hidden;
1534
    }
1535

    
1536
    @Override
1537
    public DynField setReadOnly(boolean readOnly) {
1538
        this.readOnly = readOnly;
1539
        return this;
1540
    }
1541

    
1542
    @Override
1543
    public boolean isContainer() {
1544
        return false;
1545
    }
1546

    
1547
    @Override
1548
    public Class getClassOfItems() {
1549
        return null;
1550
    }
1551

    
1552
    @Override
1553
    public DynField setClassOfItems(Class theClass) {
1554
        throw new UnsupportedOperationException();
1555
    }
1556

    
1557
    @Override
1558
    public DynField setType(DataType type) {
1559
        throw new UnsupportedOperationException();
1560
    }
1561

    
1562
    @Override
1563
    public DynField setSubtype(String subtype) {
1564
        throw new UnsupportedOperationException();
1565
    }
1566

    
1567
    @Override
1568
    public boolean isTime() {
1569
        return isTime;
1570
    }
1571

    
1572
    @Override
1573
    public FeatureAttributeGetter getFeatureAttributeGetter() {
1574
        return featureAttributeGetter;
1575
    }
1576

    
1577
    @Override
1578
    public void setFeatureAttributeGetter(
1579
            FeatureAttributeGetter featureAttributeTransform) {
1580
        this.featureAttributeGetter = featureAttributeTransform;
1581
    }
1582

    
1583
    @Override
1584
    public FeatureAttributeEmulator getFeatureAttributeEmulator() {
1585
        return this.featureAttributeEmulator;
1586
    }
1587

    
1588
    public FeatureAttributeDescriptor setFeatureAttributeEmulator(FeatureAttributeEmulator featureAttributeEmulator) {
1589
        this.featureAttributeEmulator = featureAttributeEmulator;
1590
        return this;
1591
    }
1592

    
1593
    @Override
1594
    public boolean isIndexed() {
1595
        return this.indexed;
1596
    }
1597

    
1598
    @Override
1599
    public boolean isForeingKey() {
1600
        return this.foreingKey != null && this.foreingKey.isForeingKey();
1601
    }
1602

    
1603
    @Override
1604
    public ForeingKey getForeingKey() {
1605
        return this.foreingKey;
1606
    }
1607

    
1608
    @Override
1609
    public boolean allowIndexDuplicateds() {
1610
        return this.allowIndexDuplicateds;
1611
    }
1612

    
1613
    @Override
1614
    public boolean isIndexAscending() {
1615
        return this.isIndexAscending;
1616
    }
1617

    
1618
    @Override
1619
    public DynField setClassOfValue(DynStruct dynStrct) {
1620
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
1621
    }
1622

    
1623
    @Override
1624
    public DynField setClassOfValue(String theClassNameOfValue) {
1625
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
1626
    }
1627

    
1628
    @Override
1629
    public String getClassNameOfValue() {
1630
        return null;
1631
    }
1632

    
1633
    @Override
1634
    public DynStruct getDynClassOfValue() {
1635
        return null;
1636
    }
1637

    
1638
    @Override
1639
    public DynField setTypeOfItems(int type) {
1640
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
1641
    }
1642

    
1643
    @Override
1644
    public int getTypeOfItems() {
1645
        return DataTypes.INVALID;
1646
    }
1647

    
1648
    @Override
1649
    public DynField setClassOfItems(DynStruct dynStrct) {
1650
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
1651
    }
1652

    
1653
    @Override
1654
    public DynField setClassOfItems(String theClassNameOfValue) {
1655
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
1656
    }
1657

    
1658
    @Override
1659
    public String getClassNameOfItems() {
1660
        return null;
1661
    }
1662

    
1663
    @Override
1664
    public DynStruct getDynClassOfItems() {
1665
        return null;
1666
    }
1667

    
1668
    @Override
1669
    public DynField setRelationType(int relationType) {
1670
        this.relationType = relationType;
1671
        return this;
1672
    }
1673

    
1674
    @Override
1675
    public int getRelationType() {
1676
        return this.relationType;
1677
    }
1678

    
1679
    @Override
1680
    public DynField setAvailableValues(DynMethod availableValuesMethod) {
1681
        this.availableValuesMethod = availableValuesMethod;
1682
        return this;
1683
    }
1684

    
1685
    @Override
1686
    public DynMethod getAvailableValuesMethod() {
1687
        if (this.availableValuesMethod != null) {
1688
            return this.availableValuesMethod;
1689
        }
1690
        if (this.availableValuesFilter == null && !this.isForeingKey()) {
1691
            return null;
1692
        }
1693
        DynMethod method = new AbstractDynMethod("getAvailableValuesOf" + this.getName()) {
1694
            @Override
1695
            public Object invoke(DynObject context, Object[] args) throws DynMethodException {
1696
                return getAvailableValues(context);
1697
            }
1698
        };
1699
        return method;
1700
    }
1701

    
1702
    @Override
1703
    public DynMethod getCalculateMethod() {
1704
        return this.calculateMethod;
1705
    }
1706

    
1707
    @Override
1708
    public DynField setCalculateMethod(DynMethod method) {
1709
        this.calculateMethod = method;
1710
        return this;
1711
    }
1712

    
1713
    @Override
1714
    public boolean isCalculated() {
1715
        return this.calculateMethod != null;
1716
    }
1717

    
1718
    @Override
1719
    public Object getCalculatedValue(DynObject self) {
1720
        try {
1721
            return this.calculateMethod.invoke(self, new Object[]{this});
1722
        } catch (DynMethodException ex) {
1723
            throw new RuntimeException(ex);
1724
        }
1725
    }
1726

    
1727
    @Override
1728
    public DynField setValidateElements(boolean validate) {
1729
        return this;
1730
    }
1731

    
1732
    @Override
1733
    public boolean getValidateElements() {
1734
        return false;
1735
    }
1736

    
1737
    @Override
1738
    public boolean hasLabel() {
1739
        return StringUtils.isNotBlank(this.label);
1740
    }
1741

    
1742
    @Override
1743
    public boolean hasShortLabel() {
1744
        return StringUtils.isNotBlank(this.shortLabel);
1745
    }
1746

    
1747
    @Override
1748
    public boolean hasDescription() {
1749
        return StringUtils.isNotBlank(this.description);
1750
    }
1751

    
1752
    @Override
1753
    public FeatureAttributeDescriptor getValue() {
1754
        return this;
1755
    }
1756

    
1757
    @Override
1758
    public int getDisplaySize() {
1759
        return this.displaySize;
1760
    }
1761

    
1762
    @Override
1763
    public boolean isInAvailableValues(Object valueToCheck) {
1764
        if (this.getAvailableValues() != null) {
1765
            for (DynObjectValueItem availableValue : this.getAvailableValues()) {
1766
                if (Objects.equals(valueToCheck, availableValue.getValue())) {
1767
                    return true;
1768
                }
1769
            }
1770
        }
1771
        return false;
1772
    }
1773

    
1774
    private class ConstantValueEvaluator extends AbstractEvaluator {
1775

    
1776
        @Override
1777
        public Object evaluate(EvaluatorData data) throws EvaluatorException {
1778
            return defaultValue;
1779
        }
1780

    
1781
        @Override
1782
        public String getName() {
1783
            return "Constant attribute " + name;
1784
        }
1785
    }
1786

    
1787
    public void setConstantValue(boolean isConstantValue) {
1788
        if (isConstantValue) {
1789
            /* Cuando un attributo tiene asociado un evaluador, este se interpreta
1790
             * como que no debe cargarse de la fuente de datos subyacente, siendo
1791
             * el evaluador el que se encarga de proporcionar su valor.
1792
             * Nos limitamos a asignar un evaluador que retorna simpre el valor
1793
             * por defecto para ese attributo.
1794
             */
1795
            this.evaluator = new ConstantValueEvaluator();
1796
        } else {
1797
            this.evaluator = null;
1798
        }
1799
    }
1800

    
1801
    @Override
1802
    public boolean isComputed() {
1803
        return featureAttributeEmulator != null || evaluator != null || isCalculated();
1804
    }
1805

    
1806
    @Override
1807
    public FeatureStore getStore() {
1808
        FeatureType ftype = this.getFeatureType();
1809
        if (ftype == null) {
1810
            return null;
1811
        }
1812
        return ftype.getStore();
1813
    }
1814

    
1815
    @Override
1816
    public FeatureType getFeatureType() {
1817
        if (this.typeRef == null) {
1818
            return null;
1819
        }
1820
        FeatureType ftype = (FeatureType) this.typeRef.get();
1821
//        LOGGER.info(String.format("FeatureAttributeDescriptor[%08x] get FeatureType [%08x], ref [%08x].", this.hashCode(), ftype.hashCode(), typeRef.hashCode()));
1822
        return ftype;
1823
    }
1824

    
1825
    public FeatureAttributeDescriptor setInterval(Interval interval) {
1826
        this.interval = interval;
1827
        return this;
1828
    }
1829

    
1830
    public void fixAll() {
1831
        if (!this.getDataType().supportSize()) {
1832
            this.size = 0;
1833
        }
1834
        NumberPrecisionAndScale ps = this.getDataType().fixPrecisionAndScale(this.precision, this.scale);
1835
        this.precision = ps.getPrecision();
1836
        this.scale = ps.getScale();
1837

    
1838
        switch (this.getType()) {
1839
            case DataTypes.INSTANT:
1840
            case DataTypes.INTERVAL:
1841
            case DataTypes.DATE:
1842
            case DataTypes.TIME:
1843
            case DataTypes.TIMESTAMP:
1844
                if (this.getInterval() != null) {
1845
                    this.isTime = true;
1846
                }
1847
                break;
1848
        }
1849
    }
1850

    
1851
    @Override
1852
    public String[] getRequiredFieldNames() {
1853
        FeatureAttributeEmulator emulator = this.getFeatureAttributeEmulator();
1854
        if (emulator == null) {
1855
            return null;
1856
        }
1857
        return emulator.getRequiredFieldNames();
1858
    }
1859

    
1860
    @Override
1861
    public void recentUsed() {
1862
        DefaultFeatureType.RECENTS_USEDS.add(this);
1863
    }
1864

    
1865
    @Override
1866
    public boolean hasOnlyMetadataChanges(FeatureAttributeDescriptor other) {
1867
        if (other == null) {
1868
            throw new NullPointerException();
1869
        }
1870
        DefaultFeatureAttributeDescriptor old = (DefaultFeatureAttributeDescriptor) other;
1871
        if (!StringUtils.equalsIgnoreCase(old.name, this.name)) {
1872
            return false;
1873
        }
1874
        if (old.isComputed() && old.isComputed() == this.isComputed()) {
1875
            return true;
1876
        }
1877
        if (this.dataType != old.dataType) {
1878
            return false;
1879
        }
1880
        if (this.size != old.size) {
1881
            return false;
1882
        }
1883
        if (this.precision != old.precision) {
1884
            return false;
1885
        }
1886
//        if( this.primaryKey != old.primaryKey ) {
1887
//            return false;
1888
//        }
1889
        if (this.geomType != old.geomType) {
1890
            return false;
1891
        }
1892
        if (this.SRS != old.SRS) {
1893
            return false;
1894
        }
1895
        if (this.isAutomatic != old.isAutomatic) {
1896
            return false;
1897
        }
1898
        return true;
1899
    }
1900

    
1901
    private class PropertiesBuilder {
1902

    
1903
        private String name;
1904
        private DataType type;
1905
        private Map<String, String> sets;
1906
        private String sep;
1907

    
1908
        public PropertiesBuilder() {
1909
            this.sets = new LinkedHashMap<>();
1910
        }
1911

    
1912
        public void separator(String sep) {
1913
            this.sep = sep;
1914
        }
1915

    
1916
        public void name(String name) {
1917
            this.name = name;
1918
        }
1919

    
1920
        public void type(DataType type) {
1921
            this.type = type;
1922
        }
1923

    
1924
        public void set(String name, ForeingKey fk) {
1925
            if (fk == null) {
1926
                return;
1927
            }
1928
            if (!fk.isForeingKey()) {
1929
                return;
1930
            }
1931
            this.set(name, fk.isForeingKey());
1932
            this.set(name + "_code", fk.getCodeName());
1933
            this.set(name + "_label", fk.getLabelFormula());
1934
            this.set(name + "_closedlist", fk.isClosedList());
1935
            this.set(name + "_table", fk.getTableName());
1936
        }
1937

    
1938
        public void set(String name, FeatureAttributeEmulator value) {
1939
            if (value == null) {
1940
                return;
1941
            }
1942
            if (value instanceof FeatureAttributeEmulatorExpression) {
1943
                this.set(name, ((FeatureAttributeEmulatorExpression) value).getExpression().getPhrase());
1944
            }
1945
        }
1946

    
1947
        public void set(String name, IProjection value) {
1948
            if (value == null) {
1949
                return;
1950
            }
1951
            this.set(name, value.getAbrev());
1952
        }
1953

    
1954
        public void set(String name, GeometryType value) {
1955
            if (value == null) {
1956
                return;
1957
            }
1958
            this.set(name, value.getFullName().replace(":", "@"));
1959
        }
1960

    
1961
        public void set(String name, Object value) {
1962
            if (value == null) {
1963
                return;
1964
            }
1965
            String s = Objects.toString(value, "");
1966
            if (StringUtils.isBlank(s)) {
1967
                return;
1968
            }
1969
            this.sets.put(name, s);
1970
        }
1971

    
1972
        public void set(String name, Object value, Object skipValue) {
1973
            if (value == null || value == skipValue) {
1974
                return;
1975
            }
1976
            String s = Objects.toString(value, "");
1977
            if (StringUtils.isBlank(s)) {
1978
                return;
1979
            }
1980
            this.sets.put(name, s);
1981
        }
1982

    
1983
        @Override
1984
        public String toString() {
1985
            StringBuilder builder = new StringBuilder();
1986
            builder.append(this.name);
1987
            builder.append(sep);
1988
            builder.append(this.type.getName());
1989
            for (String key : this.sets.keySet()) {
1990
                builder.append(sep);
1991
                builder.append("set");
1992
                builder.append(sep);
1993
                builder.append(key);
1994
                builder.append("=");
1995
                builder.append(this.sets.get(key));
1996
            }
1997
            return builder.toString();
1998
        }
1999
    }
2000

    
2001
    private String getAll() {
2002
        PropertiesBuilder builder = new PropertiesBuilder();
2003
        builder.separator("/");
2004
        builder.name(this.name);
2005
        builder.type(this.dataType);
2006
        builder.set("size", this.size, 0);
2007
        switch (this.getType()) {
2008
            case DataTypes.BYTE:
2009
            case DataTypes.INTEGER:
2010
            case DataTypes.LONG:
2011
                break;
2012
            case DataTypes.FLOAT:
2013
            case DataTypes.DOUBLE:
2014
                builder.set("locale", this.getLocale());
2015
                break;
2016
            case DataTypes.DECIMAL:
2017
                builder.set("precision", this.precision);
2018
                builder.set("scale", this.scale);
2019
                builder.set("roundMode", this.getRoundMode());
2020
                builder.set("locale", this.getLocale());
2021
                break;
2022
            case DataTypes.DATE:
2023
            case DataTypes.TIME:
2024
            case DataTypes.TIMESTAMP:
2025
                builder.set("locale", this.getLocale());
2026
                break;
2027
            case DataTypes.GEOMETRY:
2028
                IProjection proj = this.getSRS();
2029
                if (proj != null) {
2030
                    builder.set("srs", proj.getAbrev().replace(":", "@"));
2031
                }
2032
                GeometryType theGeomType = this.getGeomType();
2033
                if (theGeomType != null) {
2034
                    String geomTypeName = GeometryUtils.getGeometryTypeName(this.getGeomType().getType());
2035
                    String geomSubtypeName = GeometryUtils.getGeometrySubtypeName(this.getGeomType().getSubType());
2036
                    builder.set("geomtype", geomTypeName + "@" + geomSubtypeName);
2037
                }
2038
                break;
2039
        }
2040
        builder.set("hidden", this.isHidden(), false);
2041
        builder.set("readOnly", this.isReadOnly(), false);
2042
        builder.set("allowNull", this.allowNull(), true);
2043
        builder.set("pk", this.isPrimaryKey(), false);
2044
        builder.set("automatic", this.isAutomatic(), false);
2045
        builder.set("isTime", this.isTime(), false);
2046
        builder.set("profile", this.getDataProfileName());
2047
        builder.set("group", this.getGroup());
2048
        builder.set("description", this.description);
2049
        builder.set("label", this.label);
2050
        builder.set("shortLabel", this.shortLabel);
2051
        builder.set("order", this.getOder());
2052
        if (this.getFeatureAttributeEmulator() instanceof FeatureAttributeEmulatorExpression) {
2053
            Expression exp = ((FeatureAttributeEmulatorExpression) this.getFeatureAttributeEmulator()).getExpression();
2054
            if (exp != null) {
2055
                builder.set("expression", exp.getPhrase());
2056
            }
2057
        }
2058
        builder.set("isAvoidCachingAvailableValues", this.isAvoidCachingAvailableValues(), false);
2059
        if (this.isForeingKey()) {
2060
            builder.set("fk", this.isForeingKey());
2061
            builder.set("fk_table", this.getForeingKey().getTableName());
2062
            builder.set("fk_code", this.getForeingKey().getCodeName());
2063
            builder.set("fk_label", this.getForeingKey().getLabelFormula());
2064
            builder.set("fk.closedlist", this.getForeingKey().isClosedList());
2065
        }
2066
        return builder.toString();
2067
    }
2068

    
2069
    @Override
2070
    public Object get(String name) {
2071
        if (StringUtils.isBlank(name)) {
2072
            throw new IllegalArgumentException("Name can't be empty");
2073
        }
2074
        switch (name.trim().toLowerCase()) {
2075
            case "all":
2076
                return this.getAll();
2077
            case "isreadonly":
2078
            case "readonly":
2079
                return this.isReadOnly();
2080
            case "hidden":
2081
                return this.isHidden();
2082
            case "allownull":
2083
                return this.allowNull();
2084
            case "pk":
2085
            case "ispk":
2086
            case "primarykey":
2087
            case "isprimarykey":
2088
                return this.isPrimaryKey();
2089
            case "isautomatic":
2090
            case "automatic":
2091
                return this.isAutomatic();
2092
            case "time":
2093
            case "istime":
2094
                return this.isTime();
2095
            case "profile":
2096
                return this.getDataProfile();
2097
            case "group":
2098
                return this.getGroup();
2099
            case "description":
2100
                return this.getDescription();
2101
            case "label":
2102
                return this.getLabel();
2103
            case "shortlabel":
2104
                return this.getShortLabel();
2105
            case "isavoidcachingavailablevalues":
2106
            case "avoidcachingavailablevalues":
2107
            case "nocachingavailablevalues":
2108
                return this.isAvoidCachingAvailableValues();
2109
            case "expression":
2110
                return this.getFeatureAttributeEmulator();
2111
            case "size":
2112
                return this.getSize();
2113
            case "precision":
2114
                return this.getPrecision();
2115
            case "scale":
2116
                return this.getScale();
2117
            case "roundmode":
2118
                return this.getRoundMode();
2119
            case "locale":
2120
                return this.getLocale();
2121
            case "order":
2122
                return this.getOder();
2123
            case "isfk":
2124
            case "isforeingkey":
2125
                return this.isForeingKey();
2126
            case "fk":
2127
            case "foreingkey":
2128
                return this.getForeingKey();
2129
            case "fk_code":
2130
            case "foreingkey_code":
2131
            case "foreingkey.code":
2132
                return this.getForeingKey().getCodeName();
2133
            case "fk_label":
2134
            case "foreingkey_label":
2135
            case "foreingkey.label":
2136
                return this.getForeingKey().getLabelFormula();
2137
            case "fk.closedlist":
2138
            case "foreingkey_closedlist":
2139
            case "foreingkey.closedlist":
2140
                return this.getForeingKey().isClosedList();
2141
            case "fk_table":
2142
            case "foreingkey_table":
2143
            case "foreingkey.table":
2144
                return this.getForeingKey().getTableName();
2145
            case "interval":
2146
                return this.getInterval();
2147
            case "geomtype":
2148
            case "geometrytype":
2149
                return this.getGeomType();
2150
            case "srs":
2151
                return this.getSRS();
2152
            default:
2153
                throw new IllegalArgumentException("Name attribute '" + name + "' not valid.");
2154
        }
2155
    }
2156

    
2157
    public void setSRSForced(IProjection SRS) {
2158
        this.SRS = SRS;
2159
    }
2160

    
2161
    @Override
2162
    public JsonObject toJson() {
2163
        return this.toJsonBuilder().build();
2164
    }
2165

    
2166
    @Override
2167
    public JsonObjectBuilder toJsonBuilder() {
2168
        JsonObjectBuilder builder = Json.createObjectBuilder();
2169
        builder.add_class(this);
2170
        builder.add("name", this.name);
2171
        builder.add("description", this.description);
2172
        builder.add("label", this.label);
2173
        builder.add("shortLabel", this.shortLabel);
2174
        builder.add("order", this.order);
2175
        builder.add("groupName", this.groupName);
2176
        builder.add("dataType", this.dataType);
2177
        builder.add("size", this.size);
2178
        builder.add("precision", this.precision);
2179
        builder.add("scale", this.scale);
2180
        builder.add("roundMode", this.roundMode);
2181

    
2182
        builder.add("allowNull", this.allowNull);
2183
        builder.add("primaryKey", this.primaryKey);
2184
        builder.add("readOnly", this.readOnly);
2185
        builder.add("isAutomatic", this.isAutomatic);
2186
        builder.add("isTime", this.isTime);
2187
        builder.add("indexed", this.indexed);
2188
        builder.add("isIndexAscending", this.isIndexAscending);
2189
        builder.add("allowIndexDuplicateds", this.allowIndexDuplicateds);
2190
        builder.add("hidden", this.hidden);
2191
        builder.add("avoidCachingAvailableValues", this.avoidCachingAvailableValues);
2192

    
2193
        builder.add("geometryType", this.getGeomType());
2194
        builder.add("srs", this.getSRS());
2195

    
2196
        builder.add("relationType", this.relationType);
2197
        builder.add("displaySize", this.displaySize);
2198
        builder.add("locale", this.getLocale());
2199
        builder.add("expression", this.getFeatureAttributeEmulator());
2200
        if (this.isForeingKey()) {
2201
            builder.add("fk", this.isForeingKey());
2202
            builder.add("fk_table", this.getForeingKey().getTableName());
2203
            builder.add("fk_code", this.getForeingKey().getCodeName());
2204
            builder.add("fk_label", this.getForeingKey().getLabelFormula());
2205
            builder.add("fk_closedlist", this.getForeingKey().isClosedList());
2206
        }
2207
        builder.add("availableValuesExpression", this.availableValuesExpression);
2208
        builder.add("defaultValue", Objects.toString(this.defaultValue, ""));
2209
        builder.add("dataProfile", this.getDataProfileName());
2210
        builder.add("tags", tags);
2211
        builder.add("availableValues", availableValues);
2212
        builder.add("additionalInfo", this.additionalInfo);
2213
        return builder;
2214
    }
2215

    
2216
    public void fromJson(JsonObject json) {
2217
        this.name = json.getString("name");
2218
        this.description = json.getString("description");
2219
        this.label = json.getString("label");
2220
        this.shortLabel = json.getString("shortLabel");
2221
        this.order = json.getInt("order");
2222
        this.groupName = json.getString("groupName");
2223
        this.precision = json.getInt("precision");
2224
        this.size = json.getInt("size");
2225
        this.scale = json.getInt("scale");
2226
        this.roundMode = json.getInt("roundMode");
2227

    
2228
        this.allowNull = json.getBoolean("allowNull");
2229
        this.primaryKey = json.getBoolean("primaryKey");
2230
        this.readOnly = json.getBoolean("readOnly");
2231
        this.isAutomatic = json.getBoolean("isAutomatic");
2232
        this.isTime = json.getBoolean("isTime");
2233
        this.indexed = json.getBoolean("indexed");
2234
        this.isIndexAscending = json.getBoolean("isIndexAscending");
2235
        this.allowIndexDuplicateds = json.getBoolean("allowIndexDuplicateds");
2236
        this.hidden = json.getBoolean("hidden");
2237
        this.avoidCachingAvailableValues = json.getBoolean("avoidCachingAvailableValues");
2238

    
2239
        this.relationType = json.getInt("relationType");
2240
        this.displaySize = json.getInt("displaySize");
2241

    
2242
        this.dataType = (DataType) Json.toObject(json, "dataType");
2243
        this.geomType = (GeometryType) Json.toObject(json, "geometryType");
2244
        this.SRS = (IProjection) Json.toObject(json, "srs");
2245
        this.locale = (Locale) Json.toObject(json, "locale");
2246
        this.featureAttributeEmulator = (FeatureAttributeEmulator) Json.toObject(json, "expression");
2247

    
2248
        this.tags = (Tags) Json.toObject(json, "tags");
2249
        this.additionalInfo = Json.toMap(json, "additionalInfo");
2250
        this.availableValues = (DynObjectValueItem[]) Json.toArray(json, "availableValues", new DynObjectValueItem[0]);
2251
        this.dataProfile = json.getString("dataProfile", null);
2252
        try {
2253
            this.defaultValue = this.coerce(json.getString("defaultValue", null));
2254
        } catch (Exception ex) {
2255
            LOGGER.warn("Can't retrive default value for attribute '" + this.name + "'.", ex);
2256
        }
2257
        this.availableValuesExpression = (Expression) Json.toObject(json, "availableValuesExpression");
2258
        if (json.getBoolean("fk", false)) {
2259
            this.foreingKey = new DefaultForeingKey();
2260
            this.foreingKey.setForeingKey(true);
2261
            this.foreingKey.setTableName(json.getString("fk_table", null));
2262
            this.foreingKey.setCodeName(json.getString("fk_code", null));
2263
            this.foreingKey.setLabelFormula(json.getString("fk_label", null));
2264
            this.foreingKey.setClosedList(json.getBoolean("fk_closedlist", false));
2265
        } else {
2266
            this.foreingKey = null;
2267
        }
2268
    }
2269

    
2270
    private static class TheJsonSerializer implements JsonManager.JsonSerializer {
2271

    
2272
        public TheJsonSerializer() {
2273
        }
2274

    
2275
        @Override
2276
        public Class getObjectClass() {
2277
            return DefaultFeatureAttributeDescriptor.class;
2278
        }
2279

    
2280
        @Override
2281
        public Object toObject(JsonObject json) {
2282
            DefaultFeatureAttributeDescriptor o = new DefaultFeatureAttributeDescriptor();
2283
            o.fromJson(json);
2284
            return o;
2285
        }
2286

    
2287
        @Override
2288
        public JsonObjectBuilder toJsonBuilder(Object value) {
2289
            return ((SupportToJson) value).toJsonBuilder();
2290
        }
2291

    
2292
    }
2293

    
2294
    public static void selfRegister() {
2295
        Json.registerSerializer(new TheJsonSerializer());
2296
    }
2297

    
2298
}