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

History | View | Annotate | Download (77.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
    protected String defaultFormat;
171

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

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

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

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

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

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

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

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

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

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

    
327
    @Override
328
    public boolean allowNull() {
329
        return allowNull;
330
    }
331

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
679
        return true;
680
    }
681

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

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

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

    
741
        Map<String, Object> values = state.getMap("availableValues");
742
        if (values == null || values.isEmpty()) {
743
            this.availableValues = null;
744
        } else {
745
            this.availableValues = new DynObjectValueItem[values.size()];
746
            int n = 0;
747
            Coercion coercion = this.getCoercion();
748
            for (Entry<String, Object> entry : values.entrySet()) {
749
                Object value;
750
                try {
751
                    value = coercion.coerce(entry.getValue());
752
                } catch (CoercionException ex) {
753
                    value = entry.getValue();
754
                }
755
                this.availableValues[n++] = new DynObjectValueItem(value, entry.getKey());
756
            }
757
        }
758

    
759
        description = state.getString("description");
760
        minValue = state.get("minValue");
761
        maxValue = state.get("maxValue");
762
        label = state.getString("label");
763
        order = state.getInt("order");
764
        hidden = state.getBoolean("hidden");
765
        groupName = state.getString("groupName");
766
        relationType = state.getInt("relationType", RELATION_TYPE_NONE);
767

    
768
        foreingKey = (DefaultForeingKey) state.get("foreingKey");
769
        if (foreingKey != null) {
770
            this.foreingKey.setDescriptor(this);
771
        }
772
        tags = (Tags) state.get("tags");
773
        if (tags == null) {
774
            this.tags = new DefaultTags();
775
        }
776
        displaySize = state.getInt("displaySize", 0);
777
        availableValuesExpression = (Expression) state.get("availableValuesExpression");
778
        avoidCachingAvailableValues = state.getBoolean("avoidCachingAvailableValues", false);
779
        availableValuesCache = null;
780
        defaultFormat = state.getString("defaultFormat");
781
    }
782

    
783
    @Override
784
    public void saveToState(PersistentState state) throws PersistenceException {
785
        Coercion toString = ToolsLocator.getDataTypesManager().getCoercion(DataTypes.STRING);
786

    
787
        state.set("allowNull", allowNull);
788
        state.set("dataType", dataType.getType());
789
        state.set("dataProfile", dataProfile);
790

    
791
//        FIXME: dateFormat;
792
        state.set("defaultValue", Objects.toString(defaultValue, null));
793

    
794
        state.set("index", index);
795
        state.set("maximumOccurrences", maximumOccurrences);
796
        state.set("minimumOccurrences", minimumOccurrences);
797
        state.set("size", size);
798
        state.set("name", name);
799
        state.set("objectClass", objectClass == null ? null : objectClass.getName());
800
        state.set("precision", precision);
801
        state.set("scale", scale);
802
        state.set("roundMode", roundMode);
803
        if (this.locale == null) {
804
            state.setNull("locale");
805
        } else {
806
            state.set("locale", this.locale.toLanguageTag()); //toString.coerce(this.locale));
807
        }
808
        state.set("evaluator", evaluator);
809

    
810
        state.set("primaryKey", primaryKey);
811
        state.set("readOnly", readOnly);
812
        state.set("SRS", SRS);
813
        GeometryType theGeomType = this.getGeomType();
814
        if (theGeomType == null) {
815
            state.set("geometryType", Geometry.TYPES.UNKNOWN);
816
            state.set("geometrySubType", Geometry.SUBTYPES.UNKNOWN);
817
        } else {
818
            state.set("geometryType", theGeomType.getType());
819
            state.set("geometrySubType", theGeomType.getSubType());
820
        }
821

    
822
//      FIXME: additionalInfo
823
        state.set("isAutomatic", isAutomatic);
824
        state.set("isTime", isTime);
825
        if (this.interval == null) {
826
            state.setNull("interval_start");
827
            state.setNull("interval_end");
828
        } else {
829
            state.set("interval_start", ((RelativeInterval) interval).getStart().toMillis());
830
            state.set("interval_end", ((RelativeInterval) interval).getEnd().toMillis());
831
        }
832
        state.set("SRS", SRS);
833

    
834
//      FIXME: featureAttributeGetter
835
        if (featureAttributeEmulator instanceof Persistent) {
836
            state.set("featureAttributeEmulator", featureAttributeEmulator);
837
        } else {
838
            state.setNull("featureAttributeEmulator");
839
        }
840

    
841
        state.set("indexed", indexed);
842
        state.set("isIndexAscending", isIndexAscending);
843
        state.set("allowIndexDuplicateds", allowIndexDuplicateds);
844

    
845
        if (this.availableValues == null) {
846
            state.setNull("availableValues");
847
        } else {
848
            Map<String, Object> values = new LinkedHashMap<>();
849
            for (DynObjectValueItem value : availableValues) {
850
                values.put(value.getLabel(), value.getValue());
851
            }
852
            state.set("availableValues", values);
853
        }
854
        state.set("description", description);
855
        state.set("minValue", minValue);
856
        state.set("maxValue", maxValue);
857
        state.set("label", label);
858
        state.set("order", order);
859
        state.set("hidden", hidden);
860
        state.set("groupName", groupName);
861
        state.set("relationType", relationType);
862

    
863
        state.set("foreingKey", this.foreingKey);
864
        state.set("tags", this.tags);
865

    
866
        state.set("displaySize", displaySize);
867
        state.set("availableValuesExpression", availableValuesExpression);
868
        state.set("avoidCachingAvailableValues", avoidCachingAvailableValues);
869
        state.set("defaultFormat", defaultFormat);
870
    }
871

    
872
    private static final String FEATATTRDESC_PERSISTENCE_DEFINITION_NAME = "FeatureAttributeDescriptor";
873

    
874
    public static void registerPersistenceDefinition() {
875
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
876

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

    
930
            definition.addDynFieldObject("foreingKey")
931
                    .setClassOfValue(DefaultForeingKey.class);
932

    
933
            definition.addDynFieldObject("tags")
934
                    .setClassOfValue(Tags.class);
935

    
936
            definition.addDynFieldInt("displaySize").setMandatory(false);
937
            definition.addDynFieldObject("availableValuesExpression")
938
                    .setClassOfValue(Expression.class)
939
                    .setMandatory(false);
940
            definition.addDynFieldString("defaultFormat").setMandatory(false);
941
        }
942
    }
943

    
944
    /*
945
     * Start of DynField interface Implementation
946
     *
947
     */
948
    @Override
949
    public Tags getTags() {
950
        return tags;
951
    }
952

    
953
    private Expression availableValuesFilter;
954

    
955
    @Override
956
    public Expression getAvailableValuesFilter() {
957
        return this.availableValuesFilter;
958
    }
959

    
960
    public FeatureAttributeDescriptor setAvailableValuesFilter(Expression filter) {
961
        this.availableValuesFilter = filter;
962
        return this;
963
    }
964

    
965
    public FeatureAttributeDescriptor setAvailableValuesFilter(String filter) {
966
        this.availableValuesFilter = ExpressionUtils.createExpression(filter);
967
        return this;
968
    }
969

    
970
    @Override
971
    public boolean hasConstantAvailableValues() {
972
        return this.availableValues != null;
973
    }
974

    
975
    @Override
976
    public boolean isAvoidCachingAvailableValues() {
977
        return this.avoidCachingAvailableValues;
978
    }
979

    
980
    public boolean hasAvailableValues() {
981
        return getAvailableValues() != null;
982
    }
983

    
984
    @Override
985
    public DynObjectValueItem[] getAvailableValues(DynObject context) {
986
        if (this.availableValuesMethod != null) {
987
            DynObjectValueItem[] values;
988
            try {
989
                values = (DynObjectValueItem[]) this.availableValuesMethod.invoke(context, new Object[]{this});
990
            } catch (DynMethodException ex) {
991
                return this.getAvailableValues();
992
            }
993
            if (values != null) {
994
                return values;
995
            }
996
        }
997
        Expression filter = this.availableValuesFilter;
998
        if (!ExpressionUtils.isEmpty(filter)) {
999
            if (this.isForeingKey() && this.foreingKey.isClosedList()) {
1000
                ContextForeingKey foreingkeyContext = this.foreingKey.createContext();
1001
                foreingkeyContext.setContextValues(context);
1002
                DynObjectValueItem[] values = this.foreingKey.getAvailableValues(foreingkeyContext);
1003
                return values;
1004
            }
1005
            MutableSymbolTable contextSymbolTable = ExpressionUtils.createSymbolTable("feature", context);
1006
            MutableSymbolTable symbolTable = ExpressionUtils.createSymbolTable();
1007
            symbolTable.addSymbolTable(contextSymbolTable);
1008

    
1009
            DynObjectValueItem[] allValues = this.getAvailableValues();
1010
            List<DynObjectValueItem> filteredValues = new ArrayList<>();
1011
            for (DynObjectValueItem value : allValues) {
1012
                symbolTable.setVar("$value", value.getValue());
1013
                symbolTable.setVar("$label", value.getLabel());
1014
                Object include = filter.execute(symbolTable);
1015
                if (DataTypeUtils.isFalse(include, false)) {
1016
                    continue;
1017
                }
1018
                filteredValues.add(value);
1019
            }
1020
            DynObjectValueItem[] values = filteredValues.toArray(
1021
                    new DynObjectValueItem[filteredValues.size()]
1022
            );
1023
            return values;
1024
        }
1025
        return this.getAvailableValues();
1026
    }
1027

    
1028
    @Override
1029
    public boolean isAvailableValuesCalculated() {
1030
        if (this.availableValuesMethod != null) {
1031
            return true;
1032
        }
1033
        if (!ExpressionUtils.isEmpty(this.availableValuesFilter)) {
1034
            return true;
1035
        }
1036
        return false;
1037
    }
1038

    
1039
    @Override
1040
    public DynObjectValueItem[] getAvailableValues() {
1041
        DynObjectValueItem[] values = this.availableValues;
1042

    
1043
        if (values != null) {
1044
            return values;
1045
        }
1046
        values = this.availableValuesCache;
1047
        if (values != null) {
1048
            return values;
1049
        }
1050
        if (this.isForeingKey() && this.foreingKey.isClosedList()) {
1051
            values = this.foreingKey.getAvailableValues(null);
1052

    
1053
        } else if (this.availableValuesExpression != null) {
1054
            values = this.getAvailableValuesFromExpression();
1055
        }
1056
        if (!this.avoidCachingAvailableValues) {
1057
            this.availableValuesCache = values;
1058
        }
1059
        return values;
1060
    }
1061

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

    
1196
    private DynObjectValueItem[] getAvailableValuesFromExpression() {
1197
        if (this.availableValuesExpression == null || this.availableValuesExpression.isEmpty()) {
1198
            return null;
1199
        }
1200
        try {
1201
            Object value = this.availableValuesExpression.execute(null);
1202
            if (value instanceof DynObjectValueItem[]) {
1203
                return (DynObjectValueItem[]) value;
1204
            }
1205
            if (value instanceof List) {
1206
                return this.getAvailableValuesFrom(new GetItemWithSize() {
1207
                    @Override
1208
                    public Object get(int i) {
1209
                        return ((List) value).get(i);
1210
                    }
1211

    
1212
                    @Override
1213
                    public int size() {
1214
                        return ((List) value).size();
1215
                    }
1216
                });
1217
            }
1218
        } catch (Throwable th) {
1219
            LOGGER.warn("Can't get available values from expression", th);
1220
        }
1221
        return null;
1222
    }
1223

    
1224
    @Override
1225
    public Expression getAvailableValuesExpression() {
1226
        return this.availableValuesExpression;
1227
    }
1228

    
1229
    @Override
1230
    public FeatureAttributeDescriptor setAvailableValuesExpression(String expression) {
1231
        if (StringUtils.isBlank(expression)) {
1232
            this.availableValuesExpression = null;
1233
            return this;
1234
        }
1235
        this.availableValuesExpression = ExpressionUtils.createExpression(expression);
1236
        return this;
1237
    }
1238

    
1239
    @Override
1240
    public FeatureAttributeDescriptor setAvailableValuesExpression(Expression expression) {
1241
        this.availableValuesExpression = expression;
1242
        return this;
1243
    }
1244

    
1245
    @Override
1246
    public String getLabelOfValue(Object value) {
1247
        if (this.labelOfValueMap != null) {
1248
            String theLabel = this.labelOfValueMap.get(value);
1249
            if (theLabel == null) {
1250
                theLabel = Objects.toString(value, "");
1251
            }
1252
            return theLabel;
1253
        }
1254
        DynObjectValueItem[] values = this.getAvailableValues();
1255
        if (values == null) {
1256
            return Objects.toString(value, "");
1257
        }
1258
        Map<Object, String> map = new LinkedHashMap<>();
1259
        for (DynObjectValueItem theValue : values) {
1260
            map.put(theValue.getValue(), theValue.getLabel());
1261
        }
1262
        this.labelOfValueMap = map;
1263
        String theLabel = this.labelOfValueMap.get(value);
1264
        if (theLabel == null) {
1265
            theLabel = Objects.toString(value, "");
1266
        }
1267
        return theLabel;
1268
    }
1269

    
1270
    @Override
1271
    public String getDescription() {
1272
        if (this.description == null) {
1273
            return getName();
1274
        }
1275
        return this.description;
1276
    }
1277

    
1278
    @Override
1279
    public Object getMaxValue() {
1280
        return this.maxValue;
1281
    }
1282

    
1283
    @Override
1284
    public Object getMinValue() {
1285
        return this.minValue;
1286
    }
1287

    
1288
    @Override
1289
    public int getTheTypeOfAvailableValues() {
1290
        return 1;
1291
    }
1292

    
1293
    @Override
1294
    public int getType() {
1295
        if (featureAttributeGetter != null) {
1296
            return featureAttributeGetter.getDataType().getType();
1297
        }
1298
        return getDataType().getType();
1299
    }
1300

    
1301
    @Override
1302
    public boolean isMandatory() {
1303
        return !allowNull() || isPrimaryKey();
1304
    }
1305

    
1306
    @Override
1307
    public boolean isPersistent() {
1308
        return false;
1309
    }
1310

    
1311
    @Override
1312
    public DynField setAvailableValues(DynObjectValueItem[] values) {
1313
        if (ArrayUtils.isEmpty(values)) {
1314
            this.availableValues = null;
1315
        } else {
1316
            Coercion coercion = this.getCoercion();
1317
            this.availableValues = new DynObjectValueItem[values.length];
1318
            for (int i = 0; i < values.length; i++) {
1319
                DynObjectValueItem element = values[i];
1320
                Object value;
1321
                try {
1322
                    value = coercion.coerce(element.getValue());
1323
                } catch (CoercionException ex) {
1324
                    value = element.getValue();
1325
                }
1326
                this.availableValues[i] = new DynObjectValueItem(value, element.getLabel());
1327
            }
1328
        }
1329
        return this;
1330
    }
1331

    
1332
    @Override
1333
    public DynField setDescription(String description) {
1334
        this.description = description;
1335
        return this;
1336
    }
1337

    
1338
    @Override
1339
    public DynField setMandatory(boolean mandatory) {
1340
        throw new UnsupportedOperationException();
1341
    }
1342

    
1343
    @Override
1344
    public DynField setMaxValue(Object maxValue) {
1345
        try {
1346
            this.maxValue = this.coerce(maxValue);
1347
        } catch (CoercionException e) {
1348
            throw new IllegalArgumentException(e);
1349
        }
1350
        return this;
1351
    }
1352

    
1353
    @Override
1354
    public DynField setMinValue(Object minValue) {
1355
        try {
1356
            this.maxValue = this.coerce(minValue);
1357
        } catch (CoercionException e) {
1358
            throw new IllegalArgumentException(e);
1359
        }
1360
        return this;
1361
    }
1362

    
1363
    @Override
1364
    public DynField setPersistent(boolean persistent) {
1365
        throw new UnsupportedOperationException();
1366
    }
1367

    
1368
    @Override
1369
    public DynField setTheTypeOfAvailableValues(int type) {
1370
        throw new UnsupportedOperationException();
1371
    }
1372

    
1373
    @Override
1374
    public DynField setType(int type) {
1375
        throw new UnsupportedOperationException();
1376
    }
1377

    
1378
    @Override
1379
    @Deprecated
1380
    public DynField setDefaultDynValue(Object defaultValue) {
1381
        return this.setDefaultFieldValue(defaultValue);
1382
    }
1383

    
1384
    @Override
1385
    public DynField setDefaultFieldValue(Object defaultValue) {
1386
        this.defaultValue = defaultValue;
1387
        return this;
1388
    }
1389

    
1390
    @Override
1391
    public Class getClassOfValue() {
1392
        return null;
1393
    }
1394

    
1395
    @Override
1396
    public DynField getElementsType() {
1397
        return null;
1398
    }
1399

    
1400
    @Override
1401
    public DynField setClassOfValue(Class theClass)
1402
            throws DynFieldIsNotAContainerException {
1403
        throw new UnsupportedOperationException();
1404
    }
1405

    
1406
    @Override
1407
    public DynField setElementsType(DynStruct type)
1408
            throws DynFieldIsNotAContainerException {
1409
        throw new UnsupportedOperationException();
1410
    }
1411

    
1412
    @Override
1413
    public DynField setElementsType(int type)
1414
            throws DynFieldIsNotAContainerException {
1415
        throw new UnsupportedOperationException();
1416
    }
1417

    
1418
    public FeatureAttributeDescriptor setDataProfileName(String dataProfile) {
1419
        this.dataProfile = dataProfile;
1420
        return this;
1421
    }
1422

    
1423
    @Override
1424
    public String getDataProfileName() {
1425
        return dataProfile;
1426
    }
1427

    
1428
    @Override
1429
    public DataProfile getDataProfile() {
1430
        if (StringUtils.isBlank(dataProfile)) {
1431
            return null;
1432
        }
1433
        DataProfile profile = DALLocator.getDataManager().getDataProfile(dataProfile);
1434
        return profile;
1435
    }
1436

    
1437
    @Override
1438
    public void validate(Object value) throws DynFieldValidateException {
1439

    
1440
        if (value == null && !this.allowNull()) {
1441
            throw new DynFieldValidateException(value, this, null);
1442
        }
1443

    
1444
        try {
1445
            this.dataType.coerce(value);
1446
        } catch (CoercionException e) {
1447
            throw new DynFieldValidateException(value, this, e);
1448
        }
1449

    
1450
        /*
1451
         * Other checks will be needed
1452
         */
1453
    }
1454

    
1455
    @Override
1456
    public String getSubtype() {
1457
        if (featureAttributeGetter != null) {
1458
            return featureAttributeGetter.getDataType().getSubtype();
1459
        }
1460
        return this.dataType.getSubtype();
1461
    }
1462

    
1463
    @Override
1464
    public Object coerce(Object value) throws CoercionException {
1465
        if (value == null) {
1466
            return value; // O debe devolver this.defaultValue
1467
        }
1468
        try {
1469
            return this.getDataType().coerce(value, this.getCoercionContext());
1470
        } catch (Exception ex) {
1471
            throw new RuntimeException(ex);
1472
        }
1473
    }
1474

    
1475
    @Override
1476
    public DynField setAvailableValues(List values) {
1477
        if (values == null || values.isEmpty()) {
1478
            this.availableValues = null;
1479
        } else {
1480
            this.availableValues = (DynObjectValueItem[]) values.toArray(
1481
                    new DynObjectValueItem[values.size()]
1482
            );
1483
        }
1484
        return this;
1485
    }
1486

    
1487
    @Override
1488
    public String getGroup() {
1489
        return this.groupName;
1490
    }
1491

    
1492
    @Override
1493
    public int getOder() {
1494
        return this.order;
1495
    }
1496

    
1497
    @Override
1498
    public String getLabel() {
1499
        if (this.label == null) {
1500
            return this.getName();
1501
        }
1502
        return this.label;
1503
    }
1504

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

    
1514
    @Override
1515
    public DynField setLabel(String label) {
1516
        this.label = label;
1517
        return this;
1518
    }
1519

    
1520
    @Override
1521
    public DynField setShortLabel(String shortLabel) {
1522
        this.shortLabel = shortLabel;
1523
        return this;
1524
    }
1525

    
1526
    @Override
1527
    public String getShortLabel() {
1528
        return StringUtils.isBlank(shortLabel) ? getLabel() : shortLabel;
1529
    }
1530

    
1531
    @Override
1532
    public String getLocalizedShortLabel() {
1533
        if (StringUtils.isBlank(shortLabel)) {
1534
            return this.getLocalizedLabel();
1535
        }
1536
        I18nManager i18n = ToolsLocator.getI18nManager();
1537
        return i18n.getTranslation(shortLabel);
1538
    }
1539

    
1540
    @Override
1541
    public DynField setGroup(String groupName) {
1542
        this.groupName = groupName;
1543
        return this;
1544
    }
1545

    
1546
    @Override
1547
    public DynField setOrder(int order) {
1548
        this.order = order;
1549
        return this;
1550
    }
1551

    
1552
    @Override
1553
    public DynField setHidden(boolean hidden) {
1554
        this.hidden = hidden;
1555
        return this;
1556
    }
1557

    
1558
    @Override
1559
    public boolean isHidden() {
1560
        return this.hidden;
1561
    }
1562

    
1563
    @Override
1564
    public DynField setReadOnly(boolean readOnly) {
1565
        this.readOnly = readOnly;
1566
        return this;
1567
    }
1568

    
1569
    @Override
1570
    public boolean isContainer() {
1571
        return false;
1572
    }
1573

    
1574
    @Override
1575
    public Class getClassOfItems() {
1576
        return null;
1577
    }
1578

    
1579
    @Override
1580
    public DynField setClassOfItems(Class theClass) {
1581
        throw new UnsupportedOperationException();
1582
    }
1583

    
1584
    @Override
1585
    public DynField setType(DataType type) {
1586
        throw new UnsupportedOperationException();
1587
    }
1588

    
1589
    @Override
1590
    public DynField setSubtype(String subtype) {
1591
        throw new UnsupportedOperationException();
1592
    }
1593

    
1594
    @Override
1595
    public boolean isTime() {
1596
        return isTime;
1597
    }
1598

    
1599
    @Override
1600
    public FeatureAttributeGetter getFeatureAttributeGetter() {
1601
        return featureAttributeGetter;
1602
    }
1603

    
1604
    @Override
1605
    public void setFeatureAttributeGetter(
1606
            FeatureAttributeGetter featureAttributeTransform) {
1607
        this.featureAttributeGetter = featureAttributeTransform;
1608
    }
1609

    
1610
    @Override
1611
    public FeatureAttributeEmulator getFeatureAttributeEmulator() {
1612
        return this.featureAttributeEmulator;
1613
    }
1614

    
1615
    public FeatureAttributeDescriptor setFeatureAttributeEmulator(FeatureAttributeEmulator featureAttributeEmulator) {
1616
        this.featureAttributeEmulator = featureAttributeEmulator;
1617
        return this;
1618
    }
1619

    
1620
    @Override
1621
    public boolean isIndexed() {
1622
        return this.indexed;
1623
    }
1624

    
1625
    @Override
1626
    public boolean isForeingKey() {
1627
        return this.foreingKey != null && this.foreingKey.isForeingKey();
1628
    }
1629

    
1630
    @Override
1631
    public ForeingKey getForeingKey() {
1632
        return this.foreingKey;
1633
    }
1634

    
1635
    @Override
1636
    public boolean allowIndexDuplicateds() {
1637
        return this.allowIndexDuplicateds;
1638
    }
1639

    
1640
    @Override
1641
    public boolean isIndexAscending() {
1642
        return this.isIndexAscending;
1643
    }
1644

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

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

    
1655
    @Override
1656
    public String getClassNameOfValue() {
1657
        return null;
1658
    }
1659

    
1660
    @Override
1661
    public DynStruct getDynClassOfValue() {
1662
        return null;
1663
    }
1664

    
1665
    @Override
1666
    public DynField setTypeOfItems(int type) {
1667
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
1668
    }
1669

    
1670
    @Override
1671
    public int getTypeOfItems() {
1672
        return DataTypes.INVALID;
1673
    }
1674

    
1675
    @Override
1676
    public DynField setClassOfItems(DynStruct dynStrct) {
1677
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
1678
    }
1679

    
1680
    @Override
1681
    public DynField setClassOfItems(String theClassNameOfValue) {
1682
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
1683
    }
1684

    
1685
    @Override
1686
    public String getClassNameOfItems() {
1687
        return null;
1688
    }
1689

    
1690
    @Override
1691
    public DynStruct getDynClassOfItems() {
1692
        return null;
1693
    }
1694

    
1695
    @Override
1696
    public DynField setRelationType(int relationType) {
1697
        this.relationType = relationType;
1698
        return this;
1699
    }
1700

    
1701
    @Override
1702
    public int getRelationType() {
1703
        return this.relationType;
1704
    }
1705

    
1706
    @Override
1707
    public DynField setAvailableValues(DynMethod availableValuesMethod) {
1708
        this.availableValuesMethod = availableValuesMethod;
1709
        return this;
1710
    }
1711

    
1712
    @Override
1713
    public DynMethod getAvailableValuesMethod() {
1714
        if (this.availableValuesMethod != null) {
1715
            return this.availableValuesMethod;
1716
        }
1717
        if (this.availableValuesFilter == null && !this.isForeingKey()) {
1718
            return null;
1719
        }
1720
        DynMethod method = new AbstractDynMethod("getAvailableValuesOf" + this.getName()) {
1721
            @Override
1722
            public Object invoke(DynObject context, Object[] args) throws DynMethodException {
1723
                return getAvailableValues(context);
1724
            }
1725
        };
1726
        return method;
1727
    }
1728

    
1729
    @Override
1730
    public DynMethod getCalculateMethod() {
1731
        return this.calculateMethod;
1732
    }
1733

    
1734
    @Override
1735
    public DynField setCalculateMethod(DynMethod method) {
1736
        this.calculateMethod = method;
1737
        return this;
1738
    }
1739

    
1740
    @Override
1741
    public boolean isCalculated() {
1742
        return this.calculateMethod != null;
1743
    }
1744

    
1745
    @Override
1746
    public Object getCalculatedValue(DynObject self) {
1747
        try {
1748
            return this.calculateMethod.invoke(self, new Object[]{this});
1749
        } catch (DynMethodException ex) {
1750
            throw new RuntimeException(ex);
1751
        }
1752
    }
1753

    
1754
    @Override
1755
    public DynField setValidateElements(boolean validate) {
1756
        return this;
1757
    }
1758

    
1759
    @Override
1760
    public boolean getValidateElements() {
1761
        return false;
1762
    }
1763

    
1764
    @Override
1765
    public boolean hasLabel() {
1766
        return StringUtils.isNotBlank(this.label);
1767
    }
1768

    
1769
    @Override
1770
    public boolean hasShortLabel() {
1771
        return StringUtils.isNotBlank(this.shortLabel);
1772
    }
1773

    
1774
    @Override
1775
    public boolean hasDescription() {
1776
        return StringUtils.isNotBlank(this.description);
1777
    }
1778

    
1779
    @Override
1780
    public FeatureAttributeDescriptor getValue() {
1781
        return this;
1782
    }
1783

    
1784
    @Override
1785
    public int getDisplaySize() {
1786
        return this.displaySize;
1787
    }
1788

    
1789
    @Override
1790
    public boolean isInAvailableValues(Object valueToCheck) {
1791
        if (this.getAvailableValues() != null) {
1792
            for (DynObjectValueItem availableValue : this.getAvailableValues()) {
1793
                if (Objects.equals(valueToCheck, availableValue.getValue())) {
1794
                    return true;
1795
                }
1796
            }
1797
        }
1798
        return false;
1799
    }
1800

    
1801
    private class ConstantValueEvaluator extends AbstractEvaluator {
1802

    
1803
        @Override
1804
        public Object evaluate(EvaluatorData data) throws EvaluatorException {
1805
            return defaultValue;
1806
        }
1807

    
1808
        @Override
1809
        public String getName() {
1810
            return "Constant attribute " + name;
1811
        }
1812
    }
1813

    
1814
    public void setConstantValue(boolean isConstantValue) {
1815
        if (isConstantValue) {
1816
            /* Cuando un attributo tiene asociado un evaluador, este se interpreta
1817
             * como que no debe cargarse de la fuente de datos subyacente, siendo
1818
             * el evaluador el que se encarga de proporcionar su valor.
1819
             * Nos limitamos a asignar un evaluador que retorna simpre el valor
1820
             * por defecto para ese attributo.
1821
             */
1822
            this.evaluator = new ConstantValueEvaluator();
1823
        } else {
1824
            this.evaluator = null;
1825
        }
1826
    }
1827

    
1828
    @Override
1829
    public boolean isComputed() {
1830
        return featureAttributeEmulator != null || evaluator != null || isCalculated();
1831
    }
1832

    
1833
    @Override
1834
    public FeatureStore getStore() {
1835
        FeatureType ftype = this.getFeatureType();
1836
        if (ftype == null) {
1837
            return null;
1838
        }
1839
        return ftype.getStore();
1840
    }
1841

    
1842
    @Override
1843
    public FeatureType getFeatureType() {
1844
        if (this.typeRef == null) {
1845
            return null;
1846
        }
1847
        FeatureType ftype = (FeatureType) this.typeRef.get();
1848
//        LOGGER.info(String.format("FeatureAttributeDescriptor[%08x] get FeatureType [%08x], ref [%08x].", this.hashCode(), ftype.hashCode(), typeRef.hashCode()));
1849
        return ftype;
1850
    }
1851

    
1852
    public FeatureAttributeDescriptor setInterval(Interval interval) {
1853
        this.interval = interval;
1854
        return this;
1855
    }
1856

    
1857
    public void fixAll() {
1858
        if (!this.getDataType().supportSize()) {
1859
            this.size = 0;
1860
        }
1861
        NumberPrecisionAndScale ps = this.getDataType().fixPrecisionAndScale(this.precision, this.scale);
1862
        this.precision = ps.getPrecision();
1863
        this.scale = ps.getScale();
1864

    
1865
        switch (this.getType()) {
1866
            case DataTypes.INSTANT:
1867
            case DataTypes.INTERVAL:
1868
            case DataTypes.DATE:
1869
            case DataTypes.TIME:
1870
            case DataTypes.TIMESTAMP:
1871
                if (this.getInterval() != null) {
1872
                    this.isTime = true;
1873
                }
1874
                break;
1875
        }
1876
    }
1877

    
1878
    @Override
1879
    public String[] getRequiredFieldNames() {
1880
        FeatureAttributeEmulator emulator = this.getFeatureAttributeEmulator();
1881
        if (emulator == null) {
1882
            return null;
1883
        }
1884
        return emulator.getRequiredFieldNames();
1885
    }
1886

    
1887
    @Override
1888
    public void recentUsed() {
1889
        DefaultFeatureType.RECENTS_USEDS.add(this);
1890
    }
1891

    
1892
    @Override
1893
    public boolean hasOnlyMetadataChanges(FeatureAttributeDescriptor other) {
1894
        if (other == null) {
1895
            throw new NullPointerException();
1896
        }
1897
        DefaultFeatureAttributeDescriptor old = (DefaultFeatureAttributeDescriptor) other;
1898
        if (!StringUtils.equalsIgnoreCase(old.name, this.name)) {
1899
            return false;
1900
        }
1901
        if (old.isComputed() && old.isComputed() == this.isComputed()) {
1902
            return true;
1903
        }
1904
        if (this.dataType != old.dataType) {
1905
            return false;
1906
        }
1907
        if (this.size != old.size) {
1908
            return false;
1909
        }
1910
        if (this.precision != old.precision) {
1911
            return false;
1912
        }
1913
//        if( this.primaryKey != old.primaryKey ) {
1914
//            return false;
1915
//        }
1916
        if (this.geomType != old.geomType) {
1917
            return false;
1918
        }
1919
        if (this.SRS != old.SRS) {
1920
            return false;
1921
        }
1922
        if (this.isAutomatic != old.isAutomatic) {
1923
            return false;
1924
        }
1925
        return true;
1926
    }
1927

    
1928
    private class PropertiesBuilder {
1929

    
1930
        private String name;
1931
        private DataType type;
1932
        private Map<String, String> sets;
1933
        private String sep;
1934

    
1935
        public PropertiesBuilder() {
1936
            this.sets = new LinkedHashMap<>();
1937
        }
1938

    
1939
        public void separator(String sep) {
1940
            this.sep = sep;
1941
        }
1942

    
1943
        public void name(String name) {
1944
            this.name = name;
1945
        }
1946

    
1947
        public void type(DataType type) {
1948
            this.type = type;
1949
        }
1950

    
1951
        public void set(String name, ForeingKey fk) {
1952
            if (fk == null) {
1953
                return;
1954
            }
1955
            if (!fk.isForeingKey()) {
1956
                return;
1957
            }
1958
            this.set(name, fk.isForeingKey());
1959
            this.set(name + "_code", fk.getCodeName());
1960
            this.set(name + "_label", fk.getLabelFormula());
1961
            this.set(name + "_closedlist", fk.isClosedList());
1962
            this.set(name + "_table", fk.getTableName());
1963
        }
1964

    
1965
        public void set(String name, FeatureAttributeEmulator value) {
1966
            if (value == null) {
1967
                return;
1968
            }
1969
            if (value instanceof FeatureAttributeEmulatorExpression) {
1970
                this.set(name, ((FeatureAttributeEmulatorExpression) value).getExpression().getPhrase());
1971
            }
1972
        }
1973

    
1974
        public void set(String name, IProjection value) {
1975
            if (value == null) {
1976
                return;
1977
            }
1978
            this.set(name, value.getAbrev());
1979
        }
1980

    
1981
        public void set(String name, GeometryType value) {
1982
            if (value == null) {
1983
                return;
1984
            }
1985
            this.set(name, value.getFullName().replace(":", "@"));
1986
        }
1987

    
1988
        public void set(String name, Object value) {
1989
            if (value == null) {
1990
                return;
1991
            }
1992
            String s = Objects.toString(value, "");
1993
            if (StringUtils.isBlank(s)) {
1994
                return;
1995
            }
1996
            this.sets.put(name, s);
1997
        }
1998

    
1999
        public void set(String name, Object value, Object skipValue) {
2000
            if (value == null || value == skipValue) {
2001
                return;
2002
            }
2003
            String s = Objects.toString(value, "");
2004
            if (StringUtils.isBlank(s)) {
2005
                return;
2006
            }
2007
            this.sets.put(name, s);
2008
        }
2009

    
2010
        @Override
2011
        public String toString() {
2012
            StringBuilder builder = new StringBuilder();
2013
            builder.append(this.name);
2014
            builder.append(sep);
2015
            builder.append(this.type.getName());
2016
            for (String key : this.sets.keySet()) {
2017
                builder.append(sep);
2018
                builder.append("set");
2019
                builder.append(sep);
2020
                builder.append(key);
2021
                builder.append("=");
2022
                builder.append(this.sets.get(key));
2023
            }
2024
            return builder.toString();
2025
        }
2026
    }
2027

    
2028
    private String getAll() {
2029
        PropertiesBuilder builder = new PropertiesBuilder();
2030
        builder.separator("/");
2031
        builder.name(this.name);
2032
        builder.type(this.dataType);
2033
        builder.set("size", this.size, 0);
2034
        switch (this.getType()) {
2035
            case DataTypes.BYTE:
2036
            case DataTypes.INTEGER:
2037
            case DataTypes.LONG:
2038
                break;
2039
            case DataTypes.FLOAT:
2040
            case DataTypes.DOUBLE:
2041
                builder.set("locale", this.getLocale());
2042
                break;
2043
            case DataTypes.DECIMAL:
2044
                builder.set("precision", this.precision);
2045
                builder.set("scale", this.scale);
2046
                builder.set("roundMode", this.getRoundMode());
2047
                builder.set("locale", this.getLocale());
2048
                break;
2049
            case DataTypes.DATE:
2050
            case DataTypes.TIME:
2051
            case DataTypes.TIMESTAMP:
2052
                builder.set("locale", this.getLocale());
2053
                break;
2054
            case DataTypes.GEOMETRY:
2055
                IProjection proj = this.getSRS();
2056
                if (proj != null) {
2057
                    builder.set("srs", proj.getAbrev().replace(":", "@"));
2058
                }
2059
                GeometryType theGeomType = this.getGeomType();
2060
                if (theGeomType != null) {
2061
                    String geomTypeName = GeometryUtils.getGeometryTypeName(this.getGeomType().getType());
2062
                    String geomSubtypeName = GeometryUtils.getGeometrySubtypeName(this.getGeomType().getSubType());
2063
                    builder.set("geomtype", geomTypeName + "@" + geomSubtypeName);
2064
                }
2065
                break;
2066
        }
2067
        builder.set("hidden", this.isHidden(), false);
2068
        builder.set("readOnly", this.isReadOnly(), false);
2069
        builder.set("allowNull", this.allowNull(), true);
2070
        builder.set("pk", this.isPrimaryKey(), false);
2071
        builder.set("automatic", this.isAutomatic(), false);
2072
        builder.set("isTime", this.isTime(), false);
2073
        builder.set("profile", this.getDataProfileName());
2074
        builder.set("group", this.getGroup());
2075
        builder.set("description", this.description);
2076
        builder.set("label", this.label);
2077
        builder.set("shortLabel", this.shortLabel);
2078
        builder.set("order", this.getOder());
2079
        if (this.getFeatureAttributeEmulator() instanceof FeatureAttributeEmulatorExpression) {
2080
            Expression exp = ((FeatureAttributeEmulatorExpression) this.getFeatureAttributeEmulator()).getExpression();
2081
            if (exp != null) {
2082
                builder.set("expression", exp.getPhrase());
2083
            }
2084
        }
2085
        builder.set("isAvoidCachingAvailableValues", this.isAvoidCachingAvailableValues(), false);
2086
        if (this.isForeingKey()) {
2087
            builder.set("fk", this.isForeingKey());
2088
            builder.set("fk_table", this.getForeingKey().getTableName());
2089
            builder.set("fk_code", this.getForeingKey().getCodeName());
2090
            builder.set("fk_label", this.getForeingKey().getLabelFormula());
2091
            builder.set("fk.closedlist", this.getForeingKey().isClosedList());
2092
        }
2093
        return builder.toString();
2094
    }
2095

    
2096
    @Override
2097
    public Object get(String name) {
2098
        if (StringUtils.isBlank(name)) {
2099
            throw new IllegalArgumentException("Name can't be empty");
2100
        }
2101
        switch (name.trim().toLowerCase()) {
2102
            case "all":
2103
                return this.getAll();
2104
            case "isreadonly":
2105
            case "readonly":
2106
                return this.isReadOnly();
2107
            case "hidden":
2108
                return this.isHidden();
2109
            case "allownull":
2110
                return this.allowNull();
2111
            case "pk":
2112
            case "ispk":
2113
            case "primarykey":
2114
            case "isprimarykey":
2115
                return this.isPrimaryKey();
2116
            case "isautomatic":
2117
            case "automatic":
2118
                return this.isAutomatic();
2119
            case "time":
2120
            case "istime":
2121
                return this.isTime();
2122
            case "profile":
2123
                return this.getDataProfile();
2124
            case "group":
2125
                return this.getGroup();
2126
            case "description":
2127
                return this.getDescription();
2128
            case "label":
2129
                return this.getLabel();
2130
            case "shortlabel":
2131
                return this.getShortLabel();
2132
            case "isavoidcachingavailablevalues":
2133
            case "avoidcachingavailablevalues":
2134
            case "nocachingavailablevalues":
2135
                return this.isAvoidCachingAvailableValues();
2136
            case "expression":
2137
                return this.getFeatureAttributeEmulator();
2138
            case "size":
2139
                return this.getSize();
2140
            case "precision":
2141
                return this.getPrecision();
2142
            case "scale":
2143
                return this.getScale();
2144
            case "roundmode":
2145
                return this.getRoundMode();
2146
            case "locale":
2147
                return this.getLocale();
2148
            case "order":
2149
                return this.getOder();
2150
            case "isfk":
2151
            case "isforeingkey":
2152
                return this.isForeingKey();
2153
            case "fk":
2154
            case "foreingkey":
2155
                return this.getForeingKey();
2156
            case "fk_code":
2157
            case "foreingkey_code":
2158
            case "foreingkey.code":
2159
                return this.getForeingKey().getCodeName();
2160
            case "fk_label":
2161
            case "foreingkey_label":
2162
            case "foreingkey.label":
2163
                return this.getForeingKey().getLabelFormula();
2164
            case "fk.closedlist":
2165
            case "foreingkey_closedlist":
2166
            case "foreingkey.closedlist":
2167
                return this.getForeingKey().isClosedList();
2168
            case "fk_table":
2169
            case "foreingkey_table":
2170
            case "foreingkey.table":
2171
                return this.getForeingKey().getTableName();
2172
            case "interval":
2173
                return this.getInterval();
2174
            case "geomtype":
2175
            case "geometrytype":
2176
                return this.getGeomType();
2177
            case "srs":
2178
                return this.getSRS();
2179
            default:
2180
                throw new IllegalArgumentException("Name attribute '" + name + "' not valid.");
2181
        }
2182
    }
2183

    
2184
    public void setSRSForced(IProjection SRS) {
2185
        this.SRS = SRS;
2186
    }
2187

    
2188
    @Override
2189
    public JsonObject toJson() {
2190
        return this.toJsonBuilder().build();
2191
    }
2192

    
2193
    @Override
2194
    public JsonObjectBuilder toJsonBuilder() {
2195
        JsonObjectBuilder builder = Json.createObjectBuilder();
2196
        builder.add_class(this);
2197
        builder.add("name", this.name);
2198
        builder.add("description", this.description);
2199
        builder.add("label", this.label);
2200
        builder.add("shortLabel", this.shortLabel);
2201
        builder.add("order", this.order);
2202
        builder.add("groupName", this.groupName);
2203
        builder.add("dataType", this.dataType);
2204
        builder.add("size", this.size);
2205
        builder.add("precision", this.precision);
2206
        builder.add("scale", this.scale);
2207
        builder.add("roundMode", this.roundMode);
2208

    
2209
        builder.add("allowNull", this.allowNull);
2210
        builder.add("primaryKey", this.primaryKey);
2211
        builder.add("readOnly", this.readOnly);
2212
        builder.add("isAutomatic", this.isAutomatic);
2213
        builder.add("isTime", this.isTime);
2214
        builder.add("indexed", this.indexed);
2215
        builder.add("isIndexAscending", this.isIndexAscending);
2216
        builder.add("allowIndexDuplicateds", this.allowIndexDuplicateds);
2217
        builder.add("hidden", this.hidden);
2218
        builder.add("avoidCachingAvailableValues", this.avoidCachingAvailableValues);
2219

    
2220
        builder.add("geometryType", this.getGeomType());
2221
        builder.add("srs", this.getSRS());
2222

    
2223
        builder.add("relationType", this.relationType);
2224
        builder.add("displaySize", this.displaySize);
2225
        builder.add("locale", this.getLocale());
2226
        builder.add("expression", this.getFeatureAttributeEmulator());
2227
        if (this.isForeingKey()) {
2228
            builder.add("fk", this.isForeingKey());
2229
            builder.add("fk_table", this.getForeingKey().getTableName());
2230
            builder.add("fk_code", this.getForeingKey().getCodeName());
2231
            builder.add("fk_label", this.getForeingKey().getLabelFormula());
2232
            builder.add("fk_closedlist", this.getForeingKey().isClosedList());
2233
        }
2234
        builder.add("availableValuesExpression", this.availableValuesExpression);
2235
        builder.add("defaultValue", Objects.toString(this.defaultValue, null));
2236
        builder.add("dataProfile", this.getDataProfileName());
2237
        builder.add("tags", tags);
2238
        builder.add("availableValues", availableValues);
2239
        builder.add("additionalInfo", this.additionalInfo);
2240
        builder.add("defaultFormat", this.defaultFormat);
2241
        return builder;
2242
    }
2243

    
2244
    public void fromJson(JsonObject json) {
2245
        this.name = json.getString("name");
2246
        this.description = json.getString("description");
2247
        this.label = json.getString("label");
2248
        this.shortLabel = json.getString("shortLabel");
2249
        this.order = json.getInt("order");
2250
        this.groupName = json.getString("groupName");
2251
        this.precision = json.getInt("precision");
2252
        this.size = json.getInt("size");
2253
        this.scale = json.getInt("scale");
2254
        this.roundMode = json.getInt("roundMode");
2255

    
2256
        this.allowNull = json.getBoolean("allowNull");
2257
        this.primaryKey = json.getBoolean("primaryKey");
2258
        this.readOnly = json.getBoolean("readOnly");
2259
        this.isAutomatic = json.getBoolean("isAutomatic");
2260
        this.isTime = json.getBoolean("isTime");
2261
        this.indexed = json.getBoolean("indexed");
2262
        this.isIndexAscending = json.getBoolean("isIndexAscending");
2263
        this.allowIndexDuplicateds = json.getBoolean("allowIndexDuplicateds");
2264
        this.hidden = json.getBoolean("hidden");
2265
        this.avoidCachingAvailableValues = json.getBoolean("avoidCachingAvailableValues");
2266

    
2267
        this.relationType = json.getInt("relationType");
2268
        this.displaySize = json.getInt("displaySize");
2269

    
2270
        this.dataType = (DataType) Json.toObject(json, "dataType");
2271
        this.geomType = (GeometryType) Json.toObject(json, "geometryType");
2272
        this.SRS = (IProjection) Json.toObject(json, "srs");
2273
        this.locale = (Locale) Json.toObject(json, "locale");
2274
        this.featureAttributeEmulator = (FeatureAttributeEmulator) Json.toObject(json, "expression");
2275

    
2276
        this.tags = (Tags) Json.toObject(json, "tags");
2277
        this.additionalInfo = Json.toMap(json, "additionalInfo");
2278
        this.availableValues = (DynObjectValueItem[]) Json.toArray(json, "availableValues", new DynObjectValueItem[0]);
2279
        this.dataProfile = json.getString("dataProfile", null);
2280
        try {
2281
            this.defaultValue = json.getString("defaultValue", null);
2282
            if(!(this.defaultValue instanceof String && ExpressionUtils.isDynamicText((String) this.defaultValue))){
2283
                this.defaultValue = this.coerce(this.defaultValue);
2284
            }
2285
        } catch (Exception ex) {
2286
            LOGGER.warn("Can't retrive default value for attribute '" + this.name + "'.", ex);
2287
        }
2288
        this.availableValuesExpression = (Expression) Json.toObject(json, "availableValuesExpression");
2289
        if (json.getBoolean("fk", false)) {
2290
            this.foreingKey = new DefaultForeingKey();
2291
            this.foreingKey.setForeingKey(true);
2292
            this.foreingKey.setTableName(json.getString("fk_table", null));
2293
            this.foreingKey.setCodeName(json.getString("fk_code", null));
2294
            this.foreingKey.setLabelFormula(json.getString("fk_label", null));
2295
            this.foreingKey.setClosedList(json.getBoolean("fk_closedlist", false));
2296
        } else {
2297
            this.foreingKey = null;
2298
        }
2299
        this.description = json.getString("defaultFormat",null);
2300
    }
2301

    
2302
    private static class TheJsonSerializer implements JsonManager.JsonSerializer {
2303

    
2304
        public TheJsonSerializer() {
2305
        }
2306

    
2307
        @Override
2308
        public Class getObjectClass() {
2309
            return DefaultFeatureAttributeDescriptor.class;
2310
        }
2311

    
2312
        @Override
2313
        public Object toObject(JsonObject json) {
2314
            DefaultFeatureAttributeDescriptor o = new DefaultFeatureAttributeDescriptor();
2315
            o.fromJson(json);
2316
            return o;
2317
        }
2318

    
2319
        @Override
2320
        public JsonObjectBuilder toJsonBuilder(Object value) {
2321
            return ((SupportToJson) value).toJsonBuilder();
2322
        }
2323

    
2324
    }
2325

    
2326
    public static void selfRegister() {
2327
        Json.registerSerializer(new TheJsonSerializer());
2328
    }
2329

    
2330
    @Override
2331
    public String getDefaultFormat() {
2332
        return this.defaultFormat;
2333
    }
2334

    
2335
    @Override
2336
    public String format(Object value) {
2337
        try {
2338
            if( this.defaultFormat == null ) {
2339
                return DataTypeUtils.toString(value, Objects.toString(value, ""));
2340
            }
2341
            return String.format(this.defaultFormat, value);
2342
        } catch(Exception ex) {
2343
            return Objects.toString(value, "");
2344
        }
2345
    }
2346

    
2347
    
2348
}