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

History | View | Annotate | Download (79.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.defaultFormat = null;
188
        this.index = -1;
189
        this.maximumOccurrences = 0;
190
        this.minimumOccurrences = 0;
191
        this.size = 0;
192
        this.name = null;
193
        this.objectClass = null;
194
        this.precision = DataType.PRECISION_NONE;
195
        this.scale = DataType.SCALE_NONE;
196
        this.roundMode = BigDecimal.ROUND_HALF_UP;
197
        this.evaluator = null;
198
        this.primaryKey = false;
199
        this.readOnly = false;
200
        this.SRS = null;
201
        this.geometryType = Geometry.TYPES.NULL;
202
        this.geometrySubType = Geometry.SUBTYPES.UNKNOWN;
203
        this.additionalInfo = null;
204
        this.isAutomatic = false;
205
        this.hidden = false;
206
        this.relationType = RELATION_TYPE_NONE;
207
        this.locale = null;
208
        this.displaySize = 0;
209
        this.avoidCachingAvailableValues = false;
210
    }
211

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

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

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

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

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

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

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

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

    
329
    @Override
330
    public boolean allowNull() {
331
//        TODO: Habria que meter este cambio en proximos builds 2022/11/16.
332
//        if( this.isPrimaryKey() ) {
333
//            return false;
334
//        }
335
        return allowNull;
336
    }
337

    
338
    @Override
339
    public Locale getLocale() {
340
        // FIXME: Debe devolver el locale que toca ENGLISH o default, 
341
        // pero no asignarlo a "locale", manteniendo el null en la variable.
342
        // Ojo que tambien habria que tocar el setLocale.
343
        if (this.locale == null) {
344
            if (this.dataType.isNumeric()) {
345
                this.locale = Locale.ENGLISH; //return
346
            } else {
347
                this.locale = Locale.getDefault();
348
            }
349
        }
350
        return this.locale;
351
    }
352

    
353
    @Override
354
    public DataType getDataType() {
355
        if (featureAttributeGetter != null) {
356
            return featureAttributeGetter.getDataType();
357
        }
358
        return this.dataType;
359
    }
360

    
361
    public FeatureAttributeDescriptor setDataType(int type) {
362
        this.dataType = ToolsLocator.getDataTypesManager().get(type);
363
        return this;
364
    }
365

    
366
    @Override
367
    public DateFormat getDateFormat() {
368
        return this.dateFormat;
369
    }
370

    
371
    @Override
372
    public Object getDefaultValue() {
373
        return this.defaultValue;
374
    }
375

    
376
    @Override
377
    @Deprecated
378
    public Object getDefaultValueCoerced() {
379
        return getCoercedDefaultValue();
380
    }
381

    
382
    @Override
383
    public Object getCoercedDefaultValue() {
384
        try {
385
            Object value = this.defaultValue;
386
            if (value == null) {
387
                return null;
388
            }
389
            if (ExpressionUtils.isDynamicText(value.toString())) {
390
                value = ExpressionUtils.evaluateDynamicText(value.toString());
391
            }
392
            return this.getDataType().coerce(value);
393
        } catch (CoercionException ex) {
394
            return null;
395
        }
396
    }
397

    
398
    @Override
399
    public Supplier getDefaultValueSupplier() {
400
        return (Supplier) this::getDefaultValueCoerced;
401
    }
402

    
403
    @Override
404
    public DynField setDefaultValueSupplier(Supplier supplier) {
405
        //Do nothing
406
        return this;
407
    }
408

    
409
    @Override
410
    public Evaluator getEvaluator() {
411
        return this.evaluator;
412
    }
413

    
414
    @Override
415
    public int getGeometryType() {
416
        if (this.dataType.getType() != DataTypes.GEOMETRY) {
417
            return Geometry.TYPES.UNKNOWN;
418
        }
419
        return this.geometryType;
420
    }
421

    
422
    @Override
423
    public int getGeometrySubType() {
424
        if (this.dataType.getType() != DataTypes.GEOMETRY) {
425
            return Geometry.SUBTYPES.UNKNOWN;
426
        }
427
        return this.geometrySubType;
428
    }
429

    
430
    @Override
431
    public GeometryType getGeomType() {
432
        if (this.dataType.getType() != DataTypes.GEOMETRY) {
433
            return null;
434
        }
435
        if (this.geomType == null) {
436
            try {
437
                this.geomType
438
                        = GeometryLocator.getGeometryManager().getGeometryType(
439
                                this.geometryType, this.geometrySubType);
440
            } catch (GeometryException e) {
441
                throw new RuntimeException(
442
                        "Error getting geometry type with type = "
443
                        + this.geometryType + ", subtype = "
444
                        + this.geometrySubType, e);
445
            }
446
        }
447
        return this.geomType;
448
    }
449

    
450
    @Override
451
    public int getIndex() {
452
        return this.index;
453
    }
454

    
455
    protected FeatureAttributeDescriptor setIndex(int index) {
456
        this.index = index;
457
        return this;
458
    }
459

    
460
    @Override
461
    public int getMaximumOccurrences() {
462
        return this.maximumOccurrences;
463
    }
464

    
465
    @Override
466
    public int getMinimumOccurrences() {
467
        return this.minimumOccurrences;
468
    }
469

    
470
    @Override
471
    public String getName() {
472
        return this.name;
473
    }
474

    
475
    public FeatureAttributeDescriptor setName(String name) {
476
//        LOGGER.info(String.format("FeatureAttributeDescriptor[%08x] set name [%s].", this.hashCode(), name));
477
        this.name = name;
478
        return this;
479
    }
480

    
481
    @Override
482
    public Class getObjectClass() {
483
        if (getDataType().getType() == DataTypes.OBJECT) {
484
            return objectClass;
485
        }
486
        return getDataType().getDefaultClass();
487
    }
488

    
489
    @Override
490
    public int getPrecision() {
491
        return this.precision;
492
    }
493

    
494
    @Override
495
    public int getScale() {
496
        return this.scale;
497
    }
498

    
499
    @Override
500
    public Coercion getCoercion() {
501
        return this.getDataType().getCoercion();
502
    }
503

    
504
    @Override
505
    public MathContext getMathContext() {
506
        if (this.mathContext == null) {
507
            if (this.getDataType().isNumeric()) {
508
                this.mathContext = new MathContext(
509
                        this.getPrecision(),
510
                        RoundingMode.valueOf(this.getRoundMode())
511
                );
512
            } else {
513
                this.mathContext = MathContext.UNLIMITED;
514
            }
515
        }
516
        return this.mathContext;
517
    }
518

    
519
    @Override
520
    public CoercionContext getCoercionContext() {
521
        if (this.coerceContext == null) {
522
            if (this.getDataType().isNumeric()) {
523
                this.coerceContext = DataTypeUtils.coerceContextDecimal(
524
                        this.getLocale(),
525
                        this.getPrecision(),
526
                        this.getScale(),
527
                        this.getRoundMode()
528
                );
529
            } else if (this.getType() == DataTypes.GEOMETRY) {
530
                GeometryCoercionContext context = GeometryLocator.getGeometryManager().createGeometryCoercionContext();
531
                context.setGeometryType(this.getGeomType());
532
                context.setMode(GeometryCoercionContext.MODE_ONERROR_DONTCONVERT);
533
                this.coerceContext = context;
534
            } else if (this.getType() == DataTypes.TIMESTAMP) {
535
//                if(this.locale != null){
536
                    this.coerceContext = DataTypeUtils.coerceContextLocale(
537
                            this.locale
538
                    );
539
//                }
540
            } else {
541
                this.coerceContext = DataTypeUtils.coerceContextLocale(
542
                        this.getLocale()
543
                );
544
            }
545
        }
546
        return this.coerceContext;
547
    }
548

    
549
    @Override
550
    public int getRoundMode() {
551
        return this.roundMode;
552
    }
553

    
554
    @Override
555
    public IProjection getSRS() {
556
        return this.SRS;
557
    }
558

    
559
    @Override
560
    public Interval getInterval() {
561
        return this.interval;
562
    }
563

    
564
    public IProjection getSRS(WeakReference storeRef) {
565
        if (this.SRS == null) {
566
            FeatureStore store = (FeatureStore) storeRef.get();
567
            this.SRS = (IProjection) store.getDynValue(DataStore.METADATA_CRS);
568
        }
569
        return this.SRS;
570
    }
571

    
572
    @Override
573
    public int getSize() {
574
        return this.size;
575
    }
576

    
577
    @Override
578
    public boolean isPrimaryKey() {
579
        return this.primaryKey;
580
    }
581

    
582
    @Override
583
    public boolean isReadOnly() {
584
        if (this.readOnly) {
585
            return true;
586
        }
587
        return this.isComputed();
588
    }
589

    
590
    @Override
591
    public String getAdditionalInfo(String infoName) {
592
        if (this.additionalInfo == null) {
593
            return null;
594
        }
595
        return this.additionalInfo.get(infoName);
596
    }
597

    
598
    @Override
599
    public boolean isAutomatic() {
600
        return this.isAutomatic;
601
    }
602

    
603
    @Override
604
    public boolean equals(Object obj) {
605
        if (this == obj) {
606
            return true;
607
        }
608
        if (!(obj instanceof DefaultFeatureAttributeDescriptor)) {
609
            return false;
610
        }
611
        DefaultFeatureAttributeDescriptor other
612
                = (DefaultFeatureAttributeDescriptor) obj;
613

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

    
618
        if (this.index != other.index) {
619
            return false;
620
        }
621

    
622
        if (!Objects.equals(this.name, other.name)) {
623
            return false;
624
        }
625

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

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

    
634
        if (!Objects.equals(this.defaultValue, other.defaultValue)) {
635
            return false;
636
        }
637
        if (!Objects.equals(this.defaultFormat, other.defaultFormat)) {
638
            return false;
639
        }
640

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

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

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

    
653
        if (this.precision != other.precision) {
654
            return false;
655
        }
656

    
657
        if (this.maximumOccurrences != other.maximumOccurrences) {
658
            return false;
659
        }
660

    
661
        if (this.minimumOccurrences != other.minimumOccurrences) {
662
            return false;
663
        }
664

    
665
        if (this.geometryType != other.geometryType) {
666
            return false;
667
        }
668

    
669
        if (this.geometrySubType != other.geometrySubType) {
670
            return false;
671
        }
672

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

    
677
        if (!Objects.equals(this.featureAttributeEmulator, other.featureAttributeEmulator)) {
678
            return false;
679
        }
680

    
681
        if (!Objects.equals(this.SRS, other.SRS)) {
682
            return false;
683
        }
684

    
685
        if (!Objects.equals(this.dateFormat, other.dateFormat)) {
686
            return false;
687
        }
688

    
689
        if (!Objects.equals(this.objectClass, other.objectClass)) {
690
            return false;
691
        }
692

    
693
        if (!Objects.equals(this.dataProfile, other.dataProfile)) {
694
            return false;
695
        }
696

    
697
        return true;
698
    }
699

    
700
    @Override
701
    public void loadFromState(PersistentState state)
702
            throws PersistenceException {
703
        allowNull = state.getBoolean("allowNull");
704
        dataType = ToolsLocator.getDataTypesManager().get(state.getInt("dataType"));
705
        dataProfile = state.getString("dataProfile");
706

    
707
//        FIXME: dateFormat;
708
        try {
709
            defaultValue = dataType.coerce(state.get("defaultValue"));
710
        } catch (CoercionException ex) {
711
        }
712

    
713
        index = state.getInt("index");
714
        maximumOccurrences = state.getInt("maximumOccurrences");
715
        minimumOccurrences = state.getInt("minimumOccurrences");
716
        size = state.getInt("size");
717
        name = state.getString("name");
718
        try {
719
            String objectClassName = state.getString("objectClass");
720
            if (!StringUtils.isBlank(objectClassName)) {
721
                objectClass = Class.forName(objectClassName);
722
            }
723
        } catch (Throwable e) {
724
            LOGGER.warn("Can't restore the objectClass of the FeatureAttributreDescriptor", e);
725
        }
726
        precision = state.getInt("precision");
727
        scale = state.getInt("scale");
728
        roundMode = state.getInt("roundMode");
729
        String locale_s = state.getString("locale");
730
        locale = (StringUtils.isBlank(locale_s) || "null".equalsIgnoreCase(locale_s)) ? null : Locale.forLanguageTag(locale_s);
731
        evaluator = (Evaluator) state.get("evaluator");
732
        primaryKey = state.getBoolean("primaryKey");
733
        readOnly = state.getBoolean("readOnly");
734
        SRS = (IProjection) state.get("SRS");
735
        geometryType = state.getInt("geometryType");
736
        geometrySubType = state.getInt("geometrySubType");
737
        if (geometryType != Geometry.TYPES.UNKNOWN
738
                && geometrySubType != Geometry.SUBTYPES.UNKNOWN) {
739
            geomType = GeometryUtils.getGeometryType(
740
                    geometryType,
741
                    geometrySubType
742
            );
743
        }
744
//        additionalInfo = (Map) state.get("aditionalInfo");
745
        isAutomatic = state.getBoolean("isAutomatic");
746
        isTime = state.getBoolean("isTime");
747
        if (state.hasValue("intervalStart")) {
748
            long intervalStart = state.getLong("interval_start");
749
            long intervalEnd = state.getLong("interval_end");
750
            interval = TimeSupportLocator.getManager().createRelativeInterval(intervalStart, intervalEnd);
751
        } else {
752
            interval = null;
753
        }
754
        featureAttributeEmulator = (FeatureAttributeEmulator) state.get("featureAttributeEmulator");
755
        indexed = state.getBoolean("indexed");
756
        isIndexAscending = state.getBoolean("isIndexAscending");
757
        allowIndexDuplicateds = state.getBoolean("allowIndexDuplicateds");
758

    
759
        Map<String, Object> values = state.getMap("availableValues");
760
        if (values == null || values.isEmpty()) {
761
            this.availableValues = null;
762
        } else {
763
            this.availableValues = new DynObjectValueItem[values.size()];
764
            int n = 0;
765
            Coercion coercion = this.getCoercion();
766
            for (Entry<String, Object> entry : values.entrySet()) {
767
                Object value;
768
                try {
769
                    value = coercion.coerce(entry.getValue());
770
                } catch (CoercionException ex) {
771
                    value = entry.getValue();
772
                }
773
                this.availableValues[n++] = new DynObjectValueItem(value, entry.getKey());
774
            }
775
        }
776

    
777
        description = state.getString("description");
778
        minValue = state.get("minValue");
779
        maxValue = state.get("maxValue");
780
        label = state.getString("label");
781
        order = state.getInt("order");
782
        hidden = state.getBoolean("hidden");
783
        groupName = state.getString("groupName");
784
        relationType = state.getInt("relationType", RELATION_TYPE_NONE);
785

    
786
        foreingKey = (DefaultForeingKey) state.get("foreingKey");
787
        if (foreingKey != null) {
788
            this.foreingKey.setDescriptor(this);
789
        }
790
        tags = (Tags) state.get("tags");
791
        if (tags == null) {
792
            this.tags = new DefaultTags();
793
        }
794
        displaySize = state.getInt("displaySize", 0);
795
        availableValuesExpression = (Expression) state.get("availableValuesExpression");
796
        avoidCachingAvailableValues = state.getBoolean("avoidCachingAvailableValues", false);
797
        availableValuesCache = null;
798
        defaultFormat = state.getString("defaultFormat");
799
    }
800

    
801
    @Override
802
    public void saveToState(PersistentState state) throws PersistenceException {
803
        Coercion toString = ToolsLocator.getDataTypesManager().getCoercion(DataTypes.STRING);
804

    
805
        state.set("allowNull", allowNull);
806
        state.set("dataType", dataType.getType());
807
        state.set("dataProfile", dataProfile);
808

    
809
//        FIXME: dateFormat;
810
        state.set("defaultValue", Objects.toString(defaultValue, null));
811

    
812
        state.set("index", index);
813
        state.set("maximumOccurrences", maximumOccurrences);
814
        state.set("minimumOccurrences", minimumOccurrences);
815
        state.set("size", size);
816
        state.set("name", name);
817
        state.set("objectClass", objectClass == null ? null : objectClass.getName());
818
        state.set("precision", precision);
819
        state.set("scale", scale);
820
        state.set("roundMode", roundMode);
821
        if (this.locale == null) {
822
            state.setNull("locale");
823
        } else {
824
            state.set("locale", this.locale.toLanguageTag()); //toString.coerce(this.locale));
825
        }
826
        state.set("evaluator", evaluator);
827

    
828
        state.set("primaryKey", primaryKey);
829
        state.set("readOnly", readOnly);
830
        state.set("SRS", SRS);
831
        GeometryType theGeomType = this.getGeomType();
832
        if (theGeomType == null) {
833
            state.set("geometryType", Geometry.TYPES.UNKNOWN);
834
            state.set("geometrySubType", Geometry.SUBTYPES.UNKNOWN);
835
        } else {
836
            state.set("geometryType", theGeomType.getType());
837
            state.set("geometrySubType", theGeomType.getSubType());
838
        }
839

    
840
//      FIXME: additionalInfo
841
        state.set("isAutomatic", isAutomatic);
842
        state.set("isTime", isTime);
843
        if (this.interval == null) {
844
            state.setNull("interval_start");
845
            state.setNull("interval_end");
846
        } else {
847
            state.set("interval_start", ((RelativeInterval) interval).getStart().toMillis());
848
            state.set("interval_end", ((RelativeInterval) interval).getEnd().toMillis());
849
        }
850
        state.set("SRS", SRS);
851

    
852
//      FIXME: featureAttributeGetter
853
        if (featureAttributeEmulator instanceof Persistent) {
854
            state.set("featureAttributeEmulator", featureAttributeEmulator);
855
        } else {
856
            state.setNull("featureAttributeEmulator");
857
        }
858

    
859
        state.set("indexed", indexed);
860
        state.set("isIndexAscending", isIndexAscending);
861
        state.set("allowIndexDuplicateds", allowIndexDuplicateds);
862

    
863
        if (this.availableValues == null) {
864
            state.setNull("availableValues");
865
        } else {
866
            Map<String, Object> values = new LinkedHashMap<>();
867
            for (DynObjectValueItem value : availableValues) {
868
                if( value!=null ) {
869
                    values.put(value.getLabel(), value.getValue());
870
                }
871
            }
872
            state.set("availableValues", values);
873
        }
874
        state.set("description", description);
875
        state.set("minValue", minValue);
876
        state.set("maxValue", maxValue);
877
        state.set("label", label);
878
        state.set("order", order);
879
        state.set("hidden", hidden);
880
        state.set("groupName", groupName);
881
        state.set("relationType", relationType);
882

    
883
        state.set("foreingKey", this.foreingKey);
884
        state.set("tags", this.tags);
885

    
886
        state.set("displaySize", displaySize);
887
        state.set("availableValuesExpression", availableValuesExpression);
888
        state.set("avoidCachingAvailableValues", avoidCachingAvailableValues);
889
        state.set("defaultFormat", defaultFormat);
890
    }
891

    
892
    private static final String FEATATTRDESC_PERSISTENCE_DEFINITION_NAME = "FeatureAttributeDescriptor";
893

    
894
    public static void registerPersistenceDefinition() {
895
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
896

    
897
        if (manager.getDefinition(FEATATTRDESC_PERSISTENCE_DEFINITION_NAME)
898
                == null) {
899
            DynStruct definition = manager.addDefinition(DefaultFeatureAttributeDescriptor.class,
900
                    FEATATTRDESC_PERSISTENCE_DEFINITION_NAME,
901
                    FEATATTRDESC_PERSISTENCE_DEFINITION_NAME
902
                    + " persistent definition",
903
                    null,
904
                    null
905
            );
906
            definition.addDynFieldBoolean("allowNull");
907
            definition.addDynFieldInt("dataType");
908
            definition.addDynFieldString("dataProfile");
909
//            definition.addDynFieldString("dateFormat");
910
            definition.addDynFieldString("defaultValue");
911
            definition.addDynFieldInt("index");
912
            definition.addDynFieldInt("maximumOccurrences");
913
            definition.addDynFieldInt("minimumOccurrences");
914
            definition.addDynFieldInt("size");
915
            definition.addDynFieldString("name");
916
            definition.addDynFieldString("objectClass");
917
            definition.addDynFieldInt("precision");
918
            definition.addDynFieldInt("scale").setMandatory(false).setDefaultDynValue(DataType.SCALE_NONE);
919
            definition.addDynFieldInt("roundMode").setMandatory(false).setDefaultDynValue(BigDecimal.ROUND_HALF_UP);
920
            definition.addDynFieldString("locale").setMandatory(false).setDefaultDynValue("null");
921
            definition.addDynFieldObject("evaluator").setClassOfValue(Evaluator.class);
922
            definition.addDynFieldBoolean("primaryKey");
923
            definition.addDynFieldBoolean("readOnly");
924
            definition.addDynFieldObject("SRS")
925
                    .setClassOfValue(IProjection.class);
926
            definition.addDynFieldInt("geometryType");
927
            definition.addDynFieldInt("geometrySubType");
928
//            definition.addDynFieldMap("additionalInfo");
929
            definition.addDynFieldBoolean("isAutomatic");
930
            definition.addDynFieldBoolean("isTime");
931
            definition.addDynFieldLong("interval_start");
932
            definition.addDynFieldLong("interval_end");
933
            definition.addDynFieldObject("featureAttributeEmulator")
934
                    .setClassOfValue(FeatureAttributeEmulator.class);
935
            definition.addDynFieldBoolean("indexed");
936
            definition.addDynFieldBoolean("isIndexAscending");
937
            definition.addDynFieldBoolean("allowIndexDuplicateds");
938
            definition.addDynFieldMap("availableValues")
939
                    .setClassOfItems(Object.class);
940
            definition.addDynFieldString("description");
941
            definition.addDynFieldObject("minValue");
942
            definition.addDynFieldObject("maxValue");
943
            definition.addDynFieldString("label");
944
            definition.addDynFieldInt("order");
945
            definition.addDynFieldBoolean("hidden");
946
            definition.addDynFieldBoolean("avoidCachingAvailableValues");
947
            definition.addDynFieldString("groupName");
948
            definition.addDynFieldInt("relationType");
949

    
950
            definition.addDynFieldObject("foreingKey")
951
                    .setClassOfValue(DefaultForeingKey.class);
952

    
953
            definition.addDynFieldObject("tags")
954
                    .setClassOfValue(Tags.class);
955

    
956
            definition.addDynFieldInt("displaySize").setMandatory(false);
957
            definition.addDynFieldObject("availableValuesExpression")
958
                    .setClassOfValue(Expression.class)
959
                    .setMandatory(false);
960
            definition.addDynFieldString("defaultFormat").setMandatory(false);
961
        }
962
    }
963

    
964
    /*
965
     * Start of DynField interface Implementation
966
     *
967
     */
968
    @Override
969
    public Tags getTags() {
970
        return tags;
971
    }
972

    
973
    private Expression availableValuesFilter;
974

    
975
    @Override
976
    public Expression getAvailableValuesFilter() {
977
        return this.availableValuesFilter;
978
    }
979

    
980
    public FeatureAttributeDescriptor setAvailableValuesFilter(Expression filter) {
981
        this.availableValuesFilter = filter;
982
        return this;
983
    }
984

    
985
    public FeatureAttributeDescriptor setAvailableValuesFilter(String filter) {
986
        this.availableValuesFilter = ExpressionUtils.createExpression(filter);
987
        return this;
988
    }
989

    
990
    @Override
991
    public boolean hasConstantAvailableValues() {
992
        return this.availableValues != null;
993
    }
994

    
995
    @Override
996
    public boolean isAvoidCachingAvailableValues() {
997
        return this.avoidCachingAvailableValues;
998
    }
999

    
1000
    public boolean hasAvailableValues() {
1001
        return getAvailableValues() != null;
1002
    }
1003

    
1004
    @Override
1005
    public DynObjectValueItem[] getAvailableValues(DynObject context) {
1006
        if (this.availableValuesMethod != null) {
1007
            DynObjectValueItem[] values;
1008
            try {
1009
                values = (DynObjectValueItem[]) this.availableValuesMethod.invoke(context, new Object[]{this});
1010
            } catch (DynMethodException ex) {
1011
                return this.getAvailableValues();
1012
            }
1013
            if (values != null) {
1014
                return values;
1015
            }
1016
        }
1017
        Expression filter = this.availableValuesFilter;
1018
        if (!ExpressionUtils.isEmpty(filter)) {
1019
            if (this.isForeingKey() && this.foreingKey.isClosedList()) {
1020
                ContextForeingKey foreingkeyContext = this.foreingKey.createContext();
1021
                foreingkeyContext.setContextValues(context);
1022
                DynObjectValueItem[] values = this.foreingKey.getAvailableValues(foreingkeyContext);
1023
                return values;
1024
            }
1025
            MutableSymbolTable contextSymbolTable = ExpressionUtils.createSymbolTable("feature", context);
1026
            MutableSymbolTable symbolTable = ExpressionUtils.createSymbolTable();
1027
            symbolTable.addSymbolTable(contextSymbolTable);
1028

    
1029
            DynObjectValueItem[] allValues = this.getAvailableValues();
1030
            List<DynObjectValueItem> filteredValues = new ArrayList<>();
1031
            for (DynObjectValueItem value : allValues) {
1032
                symbolTable.setVar("$value", value.getValue());
1033
                symbolTable.setVar("$label", value.getLabel());
1034
                Object include = filter.execute(symbolTable);
1035
                if (DataTypeUtils.isFalse(include, false)) {
1036
                    continue;
1037
                }
1038
                filteredValues.add(value);
1039
            }
1040
            DynObjectValueItem[] values = filteredValues.toArray(
1041
                    new DynObjectValueItem[filteredValues.size()]
1042
            );
1043
            return values;
1044
        }
1045
        return this.getAvailableValues();
1046
    }
1047

    
1048
    @Override
1049
    public boolean isAvailableValuesCalculated() {
1050
        if (this.availableValuesMethod != null) {
1051
            return true;
1052
        }
1053
        if (!ExpressionUtils.isEmpty(this.availableValuesFilter)) {
1054
            return true;
1055
        }
1056
        if( this.isForeingKey() && this.foreingKey.isClosedList() ) {
1057
            return true;
1058
        }
1059
        return false;
1060
    }
1061

    
1062
    @Override
1063
    public DynObjectValueItem[] getAvailableValues() {
1064
        DynObjectValueItem[] values = this.availableValues;
1065

    
1066
        if (values != null) {
1067
            return values;
1068
        }
1069
        if (this.isForeingKey() && this.foreingKey.isClosedList()) {
1070
            values = this.foreingKey.getAvailableValues(null);
1071
            return values;
1072
        }
1073
        values = this.availableValuesCache;
1074
        if (values != null) {
1075
            return values;
1076
        }
1077
//        if (this.isForeingKey() && this.foreingKey.isClosedList()) {
1078
//            values = this.foreingKey.getAvailableValues(null);
1079
//
1080
//        } else 
1081
        if (this.availableValuesExpression != null) {
1082
            values = this.getAvailableValuesFromExpression();
1083
        }
1084
        if (!this.avoidCachingAvailableValues) {
1085
            this.availableValuesCache = values;
1086
        }
1087
        return values;
1088
    }
1089

    
1090
    private DynObjectValueItem[] getAvailableValuesFrom(GetItemWithSize values) {
1091
        if (values.size() == 0) {
1092
            return null;
1093
        }
1094
        DynObjectValueItem[] r = null;
1095
        Object firstelement = values.get(0);
1096
        if (firstelement instanceof LabeledValue) {
1097
            r = new DynObjectValueItem[values.size()];
1098
            for (int i = 0; i < values.size(); i++) {
1099
                LabeledValue v = (LabeledValue) values.get(i);
1100
                r[i] = new DynObjectValueItem(
1101
                        v.getValue(),
1102
                        Objects.toString(v.getLabel(), Objects.toString(v.getValue(), String.valueOf(i)))
1103
                );
1104
            }
1105
        } else if (firstelement instanceof Pair) {
1106
            r = new DynObjectValueItem[values.size()];
1107
            for (int i = 0; i < values.size(); i++) {
1108
                Pair v = (Pair) values.get(i);
1109
                r[i] = new DynObjectValueItem(
1110
                        v.getValue(),
1111
                        Objects.toString(v.getKey(), Objects.toString(v.getValue(), String.valueOf(i)))
1112
                );
1113
            }
1114
        } else if (firstelement instanceof JsonObject) {
1115
            JsonObject v = (JsonObject) firstelement;
1116
            String labelname = null;
1117
            for (String theName : new String[]{
1118
                "name", "label", "key", "description"
1119
            }) {
1120
                if (v.containsKey(theName)) {
1121
                    labelname = theName;
1122
                    break;
1123
                }
1124
                if (v.containsKey(theName.toUpperCase())) {
1125
                    labelname = theName.toLowerCase();
1126
                    break;
1127
                }
1128
            }
1129
            String valuename = null;
1130
            if (v.containsKey("value")) {
1131
                valuename = "value";
1132
            }
1133
            r = new DynObjectValueItem[values.size()];
1134
            for (int i = 0; i < values.size(); i++) {
1135
                v = (JsonObject) values.get(i);
1136
                String theLabel;
1137
                Object theValue;
1138
                if (labelname == null) {
1139
                    theLabel = v.toString();
1140
                } else {
1141
                    theLabel = v.getString(labelname);
1142
                }
1143
                if (valuename == null) {
1144
                    theValue = v.getString(valuename);
1145
                } else {
1146
                    theValue = v;
1147
                }
1148
                r[i] = new DynObjectValueItem(theValue, theLabel);
1149
            }
1150
        } else if (firstelement instanceof Map) {
1151
            Map<String, Object> v = (Map<String, Object>) firstelement;
1152
            String labelname = null;
1153
            for (String theName : new String[]{
1154
                "name", "label", "key", "description"
1155
            }) {
1156
                if (v.containsKey(theName)) {
1157
                    labelname = theName;
1158
                    break;
1159
                }
1160
                if (v.containsKey(theName.toUpperCase())) {
1161
                    labelname = theName.toLowerCase();
1162
                    break;
1163
                }
1164
            }
1165
            String valuename = null;
1166
            if (v.containsKey("value")) {
1167
                valuename = "value";
1168
            }
1169
            r = new DynObjectValueItem[values.size()];
1170
            for (int i = 0; i < values.size(); i++) {
1171
                v = (Map<String, Object>) values.get(i);
1172
                String theLabel;
1173
                Object theValue;
1174
                if (labelname == null) {
1175
                    theLabel = v.toString();
1176
                } else {
1177
                    theLabel = (String) v.get(labelname);
1178
                }
1179
                if (valuename == null) {
1180
                    theValue = v;
1181
                } else {
1182
                    theValue = v.get(valuename);
1183
                }
1184
                r[i] = new DynObjectValueItem(theValue, theLabel);
1185
            }
1186
        } else if (firstelement instanceof Feature) {
1187
            Feature v = (Feature) firstelement;
1188
            FeatureType featureType = v.getType();
1189
            String valuename = null;
1190
            FeatureAttributeDescriptor[] pks = featureType.getPrimaryKey();
1191
            if (pks != null && pks.length == 1) {
1192
                valuename = pks[0].getName();
1193
            }
1194
            String labelname = null;
1195
            for (String theName : new String[]{
1196
                "name", "label", "key", "description"
1197
            }) {
1198
                if (featureType.get(theName) != null) {
1199
                    labelname = theName;
1200
                    break;
1201
                }
1202
            }
1203
            r = new DynObjectValueItem[values.size()];
1204
            for (int i = 0; i < values.size(); i++) {
1205
                v = (Feature) values.get(i);
1206
                String theLabel;
1207
                Object theValue;
1208
                if (labelname == null) {
1209
                    theLabel = v.toString();
1210
                } else {
1211
                    theLabel = v.getString(labelname);
1212
                }
1213
                if (valuename == null) {
1214
                    theValue = v.getReference().getCode();
1215
                } else {
1216
                    theValue = v.get(valuename);
1217
                }
1218
                r[i] = new DynObjectValueItem(theValue, theLabel);
1219
            }
1220
        }
1221
        return r;
1222
    }
1223

    
1224
    private DynObjectValueItem[] getAvailableValuesFromExpression() {
1225
        if (this.availableValuesExpression == null || this.availableValuesExpression.isEmpty()) {
1226
            return null;
1227
        }
1228
        try {
1229
            Object value = this.availableValuesExpression.execute(null);
1230
            if (value instanceof DynObjectValueItem[]) {
1231
                return (DynObjectValueItem[]) value;
1232
            }
1233
            if (value instanceof List) {
1234
                return this.getAvailableValuesFrom(new GetItemWithSize() {
1235
                    @Override
1236
                    public Object get(int i) {
1237
                        return ((List) value).get(i);
1238
                    }
1239

    
1240
                    @Override
1241
                    public int size() {
1242
                        return ((List) value).size();
1243
                    }
1244
                });
1245
            }
1246
        } catch (Throwable th) {
1247
            LOGGER.warn("Can't get available values from expression", th);
1248
        }
1249
        return null;
1250
    }
1251

    
1252
    @Override
1253
    public Expression getAvailableValuesExpression() {
1254
        return this.availableValuesExpression;
1255
    }
1256

    
1257
    @Override
1258
    public FeatureAttributeDescriptor setAvailableValuesExpression(String expression) {
1259
        if (StringUtils.isBlank(expression)) {
1260
            this.availableValuesExpression = null;
1261
            return this;
1262
        }
1263
        this.availableValuesExpression = ExpressionUtils.createExpression(expression);
1264
        return this;
1265
    }
1266

    
1267
    @Override
1268
    public FeatureAttributeDescriptor setAvailableValuesExpression(Expression expression) {
1269
        this.availableValuesExpression = expression;
1270
        return this;
1271
    }
1272

    
1273
    @Override
1274
    public String getLabelOfValue(Object value) {
1275
        if (this.labelOfValueMap != null) {
1276
            String theLabel = this.labelOfValueMap.get(value);
1277
            if (theLabel == null) {
1278
                theLabel = Objects.toString(value, "");
1279
            }
1280
            return theLabel;
1281
        }
1282
        DynObjectValueItem[] values = this.getAvailableValues();
1283
        if (values == null) {
1284
            return Objects.toString(value, "");
1285
        }
1286
        Map<Object, String> map = new LinkedHashMap<>();
1287
        for (DynObjectValueItem theValue : values) {
1288
            map.put(theValue.getValue(), theValue.getLabel());
1289
        }
1290
        this.labelOfValueMap = map;
1291
        String theLabel = this.labelOfValueMap.get(value);
1292
        if (theLabel == null) {
1293
            theLabel = Objects.toString(value, "");
1294
        }
1295
        return theLabel;
1296
    }
1297

    
1298
    @Override
1299
    public String getDescription() {
1300
        if (this.description == null) {
1301
            return getName();
1302
        }
1303
        return this.description;
1304
    }
1305

    
1306
    @Override
1307
    public Object getMaxValue() {
1308
        return this.maxValue;
1309
    }
1310

    
1311
    @Override
1312
    public Object getMinValue() {
1313
        return this.minValue;
1314
    }
1315

    
1316
    @Override
1317
    public int getTheTypeOfAvailableValues() {
1318
        return 1;
1319
    }
1320

    
1321
    @Override
1322
    public int getType() {
1323
        if (featureAttributeGetter != null) {
1324
            return featureAttributeGetter.getDataType().getType();
1325
        }
1326
        return getDataType().getType();
1327
    }
1328

    
1329
    @Override
1330
    public boolean isMandatory() {
1331
        return !allowNull() || isPrimaryKey();
1332
    }
1333

    
1334
    @Override
1335
    public boolean isPersistent() {
1336
        return false;
1337
    }
1338

    
1339
    @Override
1340
    public DynField setAvailableValues(DynObjectValueItem[] values) {
1341
        if (ArrayUtils.isEmpty(values)) {
1342
            this.availableValues = null;
1343
        } else {
1344
            Coercion coercion = this.getCoercion();
1345
            this.availableValues = new DynObjectValueItem[values.length];
1346
            for (int i = 0; i < values.length; i++) {
1347
                DynObjectValueItem element = values[i];
1348
                Object value;
1349
                try {
1350
                    value = coercion.coerce(element.getValue());
1351
                } catch (CoercionException ex) {
1352
                    value = element.getValue();
1353
                }
1354
                this.availableValues[i] = new DynObjectValueItem(value, element.getLabel());
1355
            }
1356
        }
1357
        return this;
1358
    }
1359

    
1360
    @Override
1361
    public DynField setDescription(String description) {
1362
        this.description = description;
1363
        return this;
1364
    }
1365

    
1366
    @Override
1367
    public DynField setMandatory(boolean mandatory) {
1368
        throw new UnsupportedOperationException();
1369
    }
1370

    
1371
    @Override
1372
    public DynField setMaxValue(Object maxValue) {
1373
        try {
1374
            this.maxValue = this.coerce(maxValue);
1375
        } catch (CoercionException e) {
1376
            throw new IllegalArgumentException(e);
1377
        }
1378
        return this;
1379
    }
1380

    
1381
    @Override
1382
    public DynField setMinValue(Object minValue) {
1383
        try {
1384
            this.maxValue = this.coerce(minValue);
1385
        } catch (CoercionException e) {
1386
            throw new IllegalArgumentException(e);
1387
        }
1388
        return this;
1389
    }
1390

    
1391
    @Override
1392
    public DynField setPersistent(boolean persistent) {
1393
        throw new UnsupportedOperationException();
1394
    }
1395

    
1396
    @Override
1397
    public DynField setTheTypeOfAvailableValues(int type) {
1398
        throw new UnsupportedOperationException();
1399
    }
1400

    
1401
    @Override
1402
    public DynField setType(int type) {
1403
        throw new UnsupportedOperationException();
1404
    }
1405

    
1406
    @Override
1407
    @Deprecated
1408
    public DynField setDefaultDynValue(Object defaultValue) {
1409
        return this.setDefaultFieldValue(defaultValue);
1410
    }
1411

    
1412
    @Override
1413
    public DynField setDefaultFieldValue(Object defaultValue) {
1414
        this.defaultValue = defaultValue;
1415
        return this;
1416
    }
1417

    
1418
    @Override
1419
    public Class getClassOfValue() {
1420
        return null;
1421
    }
1422

    
1423
    @Override
1424
    public DynField getElementsType() {
1425
        return null;
1426
    }
1427

    
1428
    @Override
1429
    public DynField setClassOfValue(Class theClass)
1430
            throws DynFieldIsNotAContainerException {
1431
        throw new UnsupportedOperationException();
1432
    }
1433

    
1434
    @Override
1435
    public DynField setElementsType(DynStruct type)
1436
            throws DynFieldIsNotAContainerException {
1437
        throw new UnsupportedOperationException();
1438
    }
1439

    
1440
    @Override
1441
    public DynField setElementsType(int type)
1442
            throws DynFieldIsNotAContainerException {
1443
        throw new UnsupportedOperationException();
1444
    }
1445

    
1446
    public FeatureAttributeDescriptor setDataProfileName(String dataProfile) {
1447
        this.dataProfile = dataProfile;
1448
        return this;
1449
    }
1450

    
1451
    @Override
1452
    public String getDataProfileName() {
1453
        return dataProfile;
1454
    }
1455

    
1456
    @Override
1457
    public boolean hasDataProfile() {
1458
        return StringUtils.isNotBlank(dataProfile);
1459
    }
1460
    
1461
    @Override
1462
    public DataProfile getDataProfile() {
1463
        if (StringUtils.isBlank(dataProfile)) {
1464
            return null;
1465
        }
1466
        DataProfile profile = DALLocator.getDataManager().getDataProfile(dataProfile);
1467
        return profile;
1468
    }
1469

    
1470
    @Override
1471
    public void validate(Object value) throws DynFieldValidateException {
1472

    
1473
        if (value == null && !this.allowNull()) {
1474
            throw new DynFieldValidateException(value, this, null);
1475
        }
1476

    
1477
        try {
1478
            this.dataType.coerce(value);
1479
        } catch (CoercionException e) {
1480
            throw new DynFieldValidateException(value, this, e);
1481
        }
1482

    
1483
        /*
1484
         * Other checks will be needed
1485
         */
1486
    }
1487

    
1488
    @Override
1489
    public String getSubtype() {
1490
        if (featureAttributeGetter != null) {
1491
            return featureAttributeGetter.getDataType().getSubtype();
1492
        }
1493
        return this.dataType.getSubtype();
1494
    }
1495

    
1496
    @Override
1497
    public Object coerce(Object value) throws CoercionException {
1498
        if (value == null) {
1499
            return value; // O debe devolver this.defaultValue
1500
        }
1501
        try {
1502
            return this.getDataType().coerce(value, this.getCoercionContext());
1503
        } catch (Exception ex) {
1504
            throw new RuntimeException(ex);
1505
        }
1506
    }
1507

    
1508
    @Override
1509
    public DynField setAvailableValues(List values) {
1510
        if (values == null || values.isEmpty()) {
1511
            this.availableValues = null;
1512
        } else {
1513
            this.availableValues = (DynObjectValueItem[]) values.toArray(
1514
                    new DynObjectValueItem[values.size()]
1515
            );
1516
        }
1517
        return this;
1518
    }
1519

    
1520
    @Override
1521
    public String getGroup() {
1522
        return this.groupName;
1523
    }
1524

    
1525
    @Override
1526
    public int getOder() {
1527
        return this.order;
1528
    }
1529

    
1530
    @Override
1531
    public String getLabel() {
1532
        if (this.label == null) {
1533
            return this.getName();
1534
        }
1535
        return this.label;
1536
    }
1537

    
1538
    @Override
1539
    public String getLocalizedLabel() {
1540
        if (StringUtils.isBlank(this.label)) {
1541
            return this.getName();
1542
        }
1543
        I18nManager i18n = ToolsLocator.getI18nManager();
1544
        return i18n.getTranslation(this.label);
1545
    }
1546

    
1547
    @Override
1548
    public DynField setLabel(String label) {
1549
        this.label = label;
1550
        return this;
1551
    }
1552

    
1553
    @Override
1554
    public DynField setShortLabel(String shortLabel) {
1555
        this.shortLabel = shortLabel;
1556
        return this;
1557
    }
1558

    
1559
    @Override
1560
    public String getShortLabel() {
1561
        return StringUtils.isBlank(shortLabel) ? getLabel() : shortLabel;
1562
    }
1563

    
1564
    @Override
1565
    public String getLocalizedShortLabel() {
1566
        if (StringUtils.isBlank(shortLabel)) {
1567
            return this.getLocalizedLabel();
1568
        }
1569
        I18nManager i18n = ToolsLocator.getI18nManager();
1570
        return i18n.getTranslation(shortLabel);
1571
    }
1572

    
1573
    @Override
1574
    public DynField setGroup(String groupName) {
1575
        this.groupName = groupName;
1576
        return this;
1577
    }
1578

    
1579
    @Override
1580
    public DynField setOrder(int order) {
1581
        this.order = order;
1582
        return this;
1583
    }
1584

    
1585
    @Override
1586
    public DynField setHidden(boolean hidden) {
1587
        this.hidden = hidden;
1588
        return this;
1589
    }
1590

    
1591
    @Override
1592
    public boolean isHidden() {
1593
        return this.hidden;
1594
    }
1595

    
1596
    @Override
1597
    public DynField setReadOnly(boolean readOnly) {
1598
        this.readOnly = readOnly;
1599
        return this;
1600
    }
1601

    
1602
    @Override
1603
    public boolean isContainer() {
1604
        return false;
1605
    }
1606

    
1607
    @Override
1608
    public Class getClassOfItems() {
1609
        return null;
1610
    }
1611

    
1612
    @Override
1613
    public DynField setClassOfItems(Class theClass) {
1614
        throw new UnsupportedOperationException();
1615
    }
1616

    
1617
    @Override
1618
    public DynField setType(DataType type) {
1619
        throw new UnsupportedOperationException();
1620
    }
1621

    
1622
    @Override
1623
    public DynField setSubtype(String subtype) {
1624
        throw new UnsupportedOperationException();
1625
    }
1626

    
1627
    @Override
1628
    public boolean isTime() {
1629
        return isTime;
1630
    }
1631

    
1632
    @Override
1633
    public FeatureAttributeGetter getFeatureAttributeGetter() {
1634
        return featureAttributeGetter;
1635
    }
1636

    
1637
    @Override
1638
    public void setFeatureAttributeGetter(
1639
            FeatureAttributeGetter featureAttributeTransform) {
1640
        this.featureAttributeGetter = featureAttributeTransform;
1641
    }
1642

    
1643
    @Override
1644
    public FeatureAttributeEmulator getFeatureAttributeEmulator() {
1645
        return this.featureAttributeEmulator;
1646
    }
1647

    
1648
    public FeatureAttributeDescriptor setFeatureAttributeEmulator(FeatureAttributeEmulator featureAttributeEmulator) {
1649
        this.featureAttributeEmulator = featureAttributeEmulator;
1650
        return this;
1651
    }
1652

    
1653
    @Override
1654
    public boolean isIndexed() {
1655
        return this.indexed;
1656
    }
1657

    
1658
    @Override
1659
    public boolean isForeingKey() {
1660
        return this.foreingKey != null && this.foreingKey.isForeingKey();
1661
    }
1662

    
1663
    @Override
1664
    public ForeingKey getForeingKey() {
1665
        return this.foreingKey;
1666
    }
1667

    
1668
    @Override
1669
    public boolean allowIndexDuplicateds() {
1670
        return this.allowIndexDuplicateds;
1671
    }
1672

    
1673
    @Override
1674
    public boolean isIndexAscending() {
1675
        return this.isIndexAscending;
1676
    }
1677

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

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

    
1688
    @Override
1689
    public String getClassNameOfValue() {
1690
        return null;
1691
    }
1692

    
1693
    @Override
1694
    public DynStruct getDynClassOfValue() {
1695
        return null;
1696
    }
1697

    
1698
    @Override
1699
    public DynField setTypeOfItems(int type) {
1700
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
1701
    }
1702

    
1703
    @Override
1704
    public int getTypeOfItems() {
1705
        return DataTypes.INVALID;
1706
    }
1707

    
1708
    @Override
1709
    public DynField setClassOfItems(DynStruct dynStrct) {
1710
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
1711
    }
1712

    
1713
    @Override
1714
    public DynField setClassOfItems(String theClassNameOfValue) {
1715
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
1716
    }
1717

    
1718
    @Override
1719
    public String getClassNameOfItems() {
1720
        return null;
1721
    }
1722

    
1723
    @Override
1724
    public DynStruct getDynClassOfItems() {
1725
        return null;
1726
    }
1727

    
1728
    @Override
1729
    public DynField setRelationType(int relationType) {
1730
        this.relationType = relationType;
1731
        return this;
1732
    }
1733

    
1734
    @Override
1735
    public int getRelationType() {
1736
        return this.relationType;
1737
    }
1738

    
1739
    @Override
1740
    public DynField setAvailableValues(DynMethod availableValuesMethod) {
1741
        this.availableValuesMethod = availableValuesMethod;
1742
        return this;
1743
    }
1744

    
1745
    @Override
1746
    public DynMethod getAvailableValuesMethod() {
1747
        if (this.availableValuesMethod != null) {
1748
            return this.availableValuesMethod;
1749
        }
1750
        if (this.availableValuesFilter == null && !this.isForeingKey()) {
1751
            return null;
1752
        }
1753
        DynMethod method = new AbstractDynMethod("getAvailableValuesOf" + this.getName()) {
1754
            @Override
1755
            public Object invoke(DynObject context, Object[] args) throws DynMethodException {
1756
                return getAvailableValues(context);
1757
            }
1758
        };
1759
        return method;
1760
    }
1761

    
1762
    @Override
1763
    public DynMethod getCalculateMethod() {
1764
        return this.calculateMethod;
1765
    }
1766

    
1767
    @Override
1768
    public DynField setCalculateMethod(DynMethod method) {
1769
        this.calculateMethod = method;
1770
        return this;
1771
    }
1772

    
1773
    @Override
1774
    public boolean isCalculated() {
1775
        return this.calculateMethod != null;
1776
    }
1777

    
1778
    @Override
1779
    public Object getCalculatedValue(DynObject self) {
1780
        try {
1781
            return this.calculateMethod.invoke(self, new Object[]{this});
1782
        } catch (DynMethodException ex) {
1783
            throw new RuntimeException(ex);
1784
        }
1785
    }
1786

    
1787
    @Override
1788
    public DynField setValidateElements(boolean validate) {
1789
        return this;
1790
    }
1791

    
1792
    @Override
1793
    public boolean getValidateElements() {
1794
        return false;
1795
    }
1796

    
1797
    @Override
1798
    public boolean hasLabel() {
1799
        return StringUtils.isNotBlank(this.label);
1800
    }
1801

    
1802
    @Override
1803
    public boolean hasShortLabel() {
1804
        return StringUtils.isNotBlank(this.shortLabel);
1805
    }
1806

    
1807
    @Override
1808
    public boolean hasDescription() {
1809
        return StringUtils.isNotBlank(this.description);
1810
    }
1811

    
1812
    @Override
1813
    public FeatureAttributeDescriptor getValue() {
1814
        return this;
1815
    }
1816

    
1817
    @Override
1818
    public int getDisplaySize() {
1819
        return this.displaySize;
1820
    }
1821

    
1822
    @Override
1823
    public boolean isInAvailableValues(Object valueToCheck) {
1824
        if (this.getAvailableValues() != null) {
1825
            for (DynObjectValueItem availableValue : this.getAvailableValues()) {
1826
                if (Objects.equals(valueToCheck, availableValue.getValue())) {
1827
                    return true;
1828
                }
1829
            }
1830
        }
1831
        return false;
1832
    }
1833

    
1834
    private class ConstantValueEvaluator extends AbstractEvaluator {
1835

    
1836
        @Override
1837
        public Object evaluate(EvaluatorData data) throws EvaluatorException {
1838
            return defaultValue;
1839
        }
1840

    
1841
        @Override
1842
        public String getName() {
1843
            return "Constant attribute " + name;
1844
        }
1845
    }
1846

    
1847
    public void setConstantValue(boolean isConstantValue) {
1848
        if (isConstantValue) {
1849
            /* Cuando un attributo tiene asociado un evaluador, este se interpreta
1850
             * como que no debe cargarse de la fuente de datos subyacente, siendo
1851
             * el evaluador el que se encarga de proporcionar su valor.
1852
             * Nos limitamos a asignar un evaluador que retorna simpre el valor
1853
             * por defecto para ese attributo.
1854
             */
1855
            this.evaluator = new ConstantValueEvaluator();
1856
        } else {
1857
            this.evaluator = null;
1858
        }
1859
    }
1860

    
1861
    @Override
1862
    public boolean isComputed() {
1863
        return featureAttributeEmulator != null || evaluator != null || isCalculated();
1864
    }
1865

    
1866
    @Override
1867
    public FeatureStore getStore() {
1868
        FeatureType ftype = this.getFeatureType();
1869
        if (ftype == null) {
1870
            return null;
1871
        }
1872
        return ftype.getStore();
1873
    }
1874

    
1875
    @Override
1876
    public FeatureType getFeatureType() {
1877
        if (this.typeRef == null) {
1878
            return null;
1879
        }
1880
        FeatureType ftype = (FeatureType) this.typeRef.get();
1881
//        LOGGER.info(String.format("FeatureAttributeDescriptor[%08x] get FeatureType [%08x], ref [%08x].", this.hashCode(), ftype.hashCode(), typeRef.hashCode()));
1882
        return ftype;
1883
    }
1884

    
1885
    public FeatureAttributeDescriptor setInterval(Interval interval) {
1886
        this.interval = interval;
1887
        return this;
1888
    }
1889

    
1890
    public void fixAll() {
1891
        if (!this.getDataType().supportSize()) {
1892
            this.size = 0;
1893
        }
1894
        NumberPrecisionAndScale ps = this.getDataType().fixPrecisionAndScale(this.precision, this.scale);
1895
        this.precision = ps.getPrecision();
1896
        this.scale = ps.getScale();
1897

    
1898
        switch (this.getType()) {
1899
            case DataTypes.INSTANT:
1900
            case DataTypes.INTERVAL:
1901
            case DataTypes.DATE:
1902
            case DataTypes.TIME:
1903
            case DataTypes.TIMESTAMP:
1904
                if (this.getInterval() != null) {
1905
                    this.isTime = true;
1906
                }
1907
                break;
1908
        }
1909
//        TODO: Habria que meter este cambio en proximos builds 2022/11/16.
1910
//        if( this.isPrimaryKey() ) {
1911
//            this.allowNull = false;
1912
//        }
1913
        
1914
    }
1915

    
1916
    @Override
1917
    public String[] getRequiredFieldNames() {
1918
        FeatureAttributeEmulator emulator = this.getFeatureAttributeEmulator();
1919
        if (emulator == null) {
1920
            return null;
1921
        }
1922
        return emulator.getRequiredFieldNames();
1923
    }
1924

    
1925
    @Override
1926
    public void recentUsed() {
1927
        DefaultFeatureType.RECENTS_USEDS.add(this);
1928
    }
1929

    
1930
    @Override
1931
    public boolean hasOnlyMetadataChanges(FeatureAttributeDescriptor other) {
1932
        if (other == null) {
1933
            throw new NullPointerException();
1934
        }
1935
        DefaultFeatureAttributeDescriptor old = (DefaultFeatureAttributeDescriptor) other;
1936
        if (!StringUtils.equalsIgnoreCase(old.name, this.name)) {
1937
            return false;
1938
        }
1939
        if (old.isComputed() && old.isComputed() == this.isComputed()) {
1940
            return true;
1941
        }
1942
        if (this.dataType != old.dataType) {
1943
            return false;
1944
        }
1945
        if (this.size != old.size) {
1946
            return false;
1947
        }
1948
        if (this.precision != old.precision) {
1949
            return false;
1950
        }
1951
//        if( this.primaryKey != old.primaryKey ) {
1952
//            return false;
1953
//        }
1954
        if (this.geomType != old.geomType) {
1955
            return false;
1956
        }
1957
        if (this.SRS != old.SRS) {
1958
            return false;
1959
        }
1960
        if (this.isAutomatic != old.isAutomatic) {
1961
            return false;
1962
        }
1963
        return true;
1964
    }
1965

    
1966
    private class PropertiesBuilder {
1967

    
1968
        private String name;
1969
        private DataType type;
1970
        private Map<String, String> sets;
1971
        private String sep;
1972

    
1973
        public PropertiesBuilder() {
1974
            this.sets = new LinkedHashMap<>();
1975
        }
1976

    
1977
        public void separator(String sep) {
1978
            this.sep = sep;
1979
        }
1980

    
1981
        public void name(String name) {
1982
            this.name = name;
1983
        }
1984

    
1985
        public void type(DataType type) {
1986
            this.type = type;
1987
        }
1988

    
1989
        public void set(String name, ForeingKey fk) {
1990
            if (fk == null) {
1991
                return;
1992
            }
1993
            if (!fk.isForeingKey()) {
1994
                return;
1995
            }
1996
            this.set(name, fk.isForeingKey());
1997
            this.set(name + "_code", fk.getCodeName());
1998
            this.set(name + "_label", fk.getLabelFormula());
1999
            this.set(name + "_closedlist", fk.isClosedList());
2000
            this.set(name + "_table", fk.getTableName());
2001
        }
2002

    
2003
        public void set(String name, FeatureAttributeEmulator value) {
2004
            if (value == null) {
2005
                return;
2006
            }
2007
            if (value instanceof FeatureAttributeEmulatorExpression) {
2008
                this.set(name, ((FeatureAttributeEmulatorExpression) value).getExpression().getPhrase());
2009
            }
2010
        }
2011

    
2012
        public void set(String name, IProjection value) {
2013
            if (value == null) {
2014
                return;
2015
            }
2016
            this.set(name, value.getAbrev());
2017
        }
2018

    
2019
        public void set(String name, GeometryType value) {
2020
            if (value == null) {
2021
                return;
2022
            }
2023
            this.set(name, value.getFullName().replace(":", "@"));
2024
        }
2025

    
2026
        public void set(String name, Object value) {
2027
            if (value == null) {
2028
                return;
2029
            }
2030
            String s = Objects.toString(value, "");
2031
            if (StringUtils.isBlank(s)) {
2032
                return;
2033
            }
2034
            this.sets.put(name, s);
2035
        }
2036

    
2037
        public void set(String name, Object value, Object skipValue) {
2038
            if (value == null || value == skipValue) {
2039
                return;
2040
            }
2041
            String s = Objects.toString(value, "");
2042
            if (StringUtils.isBlank(s)) {
2043
                return;
2044
            }
2045
            this.sets.put(name, s);
2046
        }
2047

    
2048
        @Override
2049
        public String toString() {
2050
            StringBuilder builder = new StringBuilder();
2051
            builder.append(this.name);
2052
            builder.append(sep);
2053
            builder.append(this.type.getName());
2054
            for (String key : this.sets.keySet()) {
2055
                builder.append(sep);
2056
                builder.append("set");
2057
                builder.append(sep);
2058
                builder.append(key);
2059
                builder.append("=");
2060
                builder.append(this.sets.get(key));
2061
            }
2062
            return builder.toString();
2063
        }
2064
    }
2065

    
2066
    private String getAll() {
2067
        PropertiesBuilder builder = new PropertiesBuilder();
2068
        builder.separator("/");
2069
        builder.name(this.name);
2070
        builder.type(this.dataType);
2071
        builder.set("size", this.size, 0);
2072
        switch (this.getType()) {
2073
            case DataTypes.BYTE:
2074
            case DataTypes.INTEGER:
2075
            case DataTypes.LONG:
2076
                break;
2077
            case DataTypes.FLOAT:
2078
            case DataTypes.DOUBLE:
2079
                if(this.locale != null){
2080
                    builder.set("locale", this.getLocale());
2081
                }
2082
                break;
2083
            case DataTypes.DECIMAL:
2084
                builder.set("precision", this.precision);
2085
                builder.set("scale", this.scale);
2086
                builder.set("roundMode", this.getRoundMode());
2087
                if(this.locale != null){
2088
                    builder.set("locale", this.getLocale());
2089
                }
2090
                break;
2091
            case DataTypes.DATE:
2092
            case DataTypes.TIME:
2093
            case DataTypes.TIMESTAMP:
2094
                if(this.locale != null){
2095
                    builder.set("locale", this.getLocale());
2096
                }
2097
                break;
2098
            case DataTypes.GEOMETRY:
2099
                IProjection proj = this.getSRS();
2100
                if (proj != null) {
2101
                    builder.set("srs", proj.getAbrev().replace(":", "@"));
2102
                }
2103
                GeometryType theGeomType = this.getGeomType();
2104
                if (theGeomType != null) {
2105
                    String geomTypeName = GeometryUtils.getGeometryTypeName(this.getGeomType().getType());
2106
                    String geomSubtypeName = GeometryUtils.getGeometrySubtypeName(this.getGeomType().getSubType());
2107
                    builder.set("geomtype", geomTypeName + "@" + geomSubtypeName);
2108
                }
2109
                break;
2110
        }
2111
        builder.set("hidden", this.isHidden(), false);
2112
        builder.set("readOnly", this.isReadOnly(), false);
2113
        builder.set("allowNull", this.allowNull(), true);
2114
        builder.set("pk", this.isPrimaryKey(), false);
2115
        builder.set("automatic", this.isAutomatic(), false);
2116
        builder.set("isTime", this.isTime(), false);
2117
        builder.set("profile", this.getDataProfileName());
2118
        builder.set("group", this.getGroup());
2119
        builder.set("description", this.description);
2120
        builder.set("label", this.label);
2121
        builder.set("shortLabel", this.shortLabel);
2122
        builder.set("order", this.getOder());
2123
        if (this.getFeatureAttributeEmulator() instanceof FeatureAttributeEmulatorExpression) {
2124
            Expression exp = ((FeatureAttributeEmulatorExpression) this.getFeatureAttributeEmulator()).getExpression();
2125
            if (exp != null) {
2126
                builder.set("expression", exp.getPhrase());
2127
            }
2128
        }
2129
        builder.set("isAvoidCachingAvailableValues", this.isAvoidCachingAvailableValues(), false);
2130
        if (this.isForeingKey()) {
2131
            builder.set("fk", this.isForeingKey());
2132
            builder.set("fk_table", this.getForeingKey().getTableName());
2133
            builder.set("fk_code", this.getForeingKey().getCodeName());
2134
            builder.set("fk_label", this.getForeingKey().getLabelFormula());
2135
            builder.set("fk.closedlist", this.getForeingKey().isClosedList());
2136
        }
2137
        return builder.toString();
2138
    }
2139

    
2140
    @Override
2141
    public Object get(String name) {
2142
        if (StringUtils.isBlank(name)) {
2143
            throw new IllegalArgumentException("Name can't be empty");
2144
        }
2145
        switch (name.trim().toLowerCase()) {
2146
            case "all":
2147
                return this.getAll();
2148
            case "isreadonly":
2149
            case "readonly":
2150
                return this.isReadOnly();
2151
            case "hidden":
2152
                return this.isHidden();
2153
            case "allownull":
2154
                return this.allowNull();
2155
            case "pk":
2156
            case "ispk":
2157
            case "primarykey":
2158
            case "isprimarykey":
2159
                return this.isPrimaryKey();
2160
            case "isautomatic":
2161
            case "automatic":
2162
                return this.isAutomatic();
2163
            case "time":
2164
            case "istime":
2165
                return this.isTime();
2166
            case "profile":
2167
                return this.getDataProfile();
2168
            case "group":
2169
                return this.getGroup();
2170
            case "description":
2171
                return this.getDescription();
2172
            case "label":
2173
                return this.getLabel();
2174
            case "shortlabel":
2175
                return this.getShortLabel();
2176
            case "isavoidcachingavailablevalues":
2177
            case "avoidcachingavailablevalues":
2178
            case "nocachingavailablevalues":
2179
                return this.isAvoidCachingAvailableValues();
2180
            case "expression":
2181
                return this.getFeatureAttributeEmulator();
2182
            case "size":
2183
                return this.getSize();
2184
            case "precision":
2185
                return this.getPrecision();
2186
            case "scale":
2187
                return this.getScale();
2188
            case "roundmode":
2189
                return this.getRoundMode();
2190
            case "locale":
2191
                return this.getLocale();
2192
            case "order":
2193
                return this.getOder();
2194
            case "isfk":
2195
            case "isforeingkey":
2196
                return this.isForeingKey();
2197
            case "fk":
2198
            case "foreingkey":
2199
                return this.getForeingKey();
2200
            case "fk_code":
2201
            case "foreingkey_code":
2202
            case "foreingkey.code":
2203
                return this.getForeingKey().getCodeName();
2204
            case "fk_label":
2205
            case "foreingkey_label":
2206
            case "foreingkey.label":
2207
                return this.getForeingKey().getLabelFormula();
2208
            case "fk.closedlist":
2209
            case "foreingkey_closedlist":
2210
            case "foreingkey.closedlist":
2211
                return this.getForeingKey().isClosedList();
2212
            case "fk_table":
2213
            case "foreingkey_table":
2214
            case "foreingkey.table":
2215
                return this.getForeingKey().getTableName();
2216
            case "interval":
2217
                return this.getInterval();
2218
            case "geomtype":
2219
            case "geometrytype":
2220
                return this.getGeomType();
2221
            case "srs":
2222
                return this.getSRS();
2223
            default:
2224
                throw new IllegalArgumentException("Name attribute '" + name + "' not valid.");
2225
        }
2226
    }
2227

    
2228
    public void setSRSForced(IProjection SRS) {
2229
        this.SRS = SRS;
2230
    }
2231

    
2232
    @Override
2233
    public JsonObject toJson() {
2234
        return this.toJsonBuilder().build();
2235
    }
2236

    
2237
    @Override
2238
    public JsonObjectBuilder toJsonBuilder() {
2239
        JsonObjectBuilder builder = Json.createObjectBuilder();
2240
        builder.add_class(this);
2241
        builder.add("name", this.name);
2242
        builder.add("description", this.description);
2243
        builder.add("label", this.label);
2244
        builder.add("shortLabel", this.shortLabel);
2245
        builder.add("order", this.order);
2246
        builder.add("groupName", this.groupName);
2247
        builder.add("dataType", this.dataType);
2248
        builder.add("size", this.size);
2249
        builder.add("precision", this.precision);
2250
        builder.add("scale", this.scale);
2251
        builder.add("roundMode", this.roundMode);
2252

    
2253
        builder.add("allowNull", this.allowNull);
2254
        builder.add("primaryKey", this.primaryKey);
2255
        builder.add("readOnly", this.readOnly);
2256
        builder.add("isAutomatic", this.isAutomatic);
2257
        builder.add("isTime", this.isTime);
2258
        builder.add("indexed", this.indexed);
2259
        builder.add("isIndexAscending", this.isIndexAscending);
2260
        builder.add("allowIndexDuplicateds", this.allowIndexDuplicateds);
2261
        builder.add("hidden", this.hidden);
2262
        builder.add("avoidCachingAvailableValues", this.avoidCachingAvailableValues);
2263

    
2264
        builder.add("geometryType", this.getGeomType());
2265
        builder.add("srs", this.getSRS());
2266

    
2267
        builder.add("relationType", this.relationType);
2268
        builder.add("displaySize", this.displaySize);
2269
        if(this.locale == null){ //!this.hasLocale()
2270
            builder.addNull("locale");
2271
        } else {
2272
            builder.add("locale", this.getLocale());
2273
        }
2274
        builder.add("expression", this.getFeatureAttributeEmulator());
2275
        if (this.isForeingKey()) {
2276
            builder.add("fk", this.isForeingKey());
2277
            builder.add("fk_table", this.getForeingKey().getTableName());
2278
            builder.add("fk_code", this.getForeingKey().getCodeName());
2279
            builder.add("fk_label", this.getForeingKey().getLabelFormula());
2280
            builder.add("fk_closedlist", this.getForeingKey().isClosedList());
2281
        }
2282
        builder.add("availableValuesExpression", this.availableValuesExpression);
2283
        builder.add("defaultValue", Objects.toString(this.defaultValue, null));
2284
        builder.add("dataProfile", this.getDataProfileName());
2285
        builder.add("tags", tags);
2286
        builder.add("availableValues", availableValues);
2287
        builder.add("additionalInfo", this.additionalInfo);
2288
        builder.add("defaultFormat", this.defaultFormat);
2289
        return builder;
2290
    }
2291

    
2292
    public void fromJson(JsonObject json) {
2293
        this.name = json.getString("name");
2294
        this.description = json.getString("description");
2295
        this.label = json.getString("label");
2296
        this.shortLabel = json.getString("shortLabel");
2297
        this.order = json.getInt("order");
2298
        this.groupName = json.getString("groupName");
2299
        this.precision = json.getInt("precision");
2300
        this.size = json.getInt("size");
2301
        this.scale = json.getInt("scale");
2302
        this.roundMode = json.getInt("roundMode");
2303

    
2304
        this.allowNull = json.getBoolean("allowNull");
2305
        this.primaryKey = json.getBoolean("primaryKey");
2306
        this.readOnly = json.getBoolean("readOnly");
2307
        this.isAutomatic = json.getBoolean("isAutomatic");
2308
        this.isTime = json.getBoolean("isTime");
2309
        this.indexed = json.getBoolean("indexed");
2310
        this.isIndexAscending = json.getBoolean("isIndexAscending");
2311
        this.allowIndexDuplicateds = json.getBoolean("allowIndexDuplicateds");
2312
        this.hidden = json.getBoolean("hidden");
2313
        this.avoidCachingAvailableValues = json.getBoolean("avoidCachingAvailableValues");
2314

    
2315
        this.relationType = json.getInt("relationType");
2316
        this.displaySize = json.getInt("displaySize");
2317

    
2318
        this.dataType = (DataType) Json.toObject(json, "dataType");
2319
        this.geomType = (GeometryType) Json.toObject(json, "geometryType");
2320
        this.SRS = (IProjection) Json.toObject(json, "srs");
2321
        this.locale = (Locale) Json.toObject(json, "locale");
2322
        this.featureAttributeEmulator = (FeatureAttributeEmulator) Json.toObject(json, "expression");
2323

    
2324
        this.tags = (Tags) Json.toObject(json, "tags");
2325
        this.additionalInfo = Json.toMap(json, "additionalInfo");
2326
        this.availableValues = (DynObjectValueItem[]) Json.toArray(json, "availableValues", new DynObjectValueItem[0]);
2327
        this.dataProfile = json.getString("dataProfile", null);
2328
        try {
2329
            this.defaultValue = json.getString("defaultValue", null);
2330
            if(!(this.defaultValue instanceof String && ExpressionUtils.isDynamicText((String) this.defaultValue))){
2331
                this.defaultValue = this.coerce(this.defaultValue);
2332
            }
2333
        } catch (Exception ex) {
2334
            LOGGER.warn("Can't retrive default value for attribute '" + this.name + "'.", ex);
2335
        }
2336
        this.availableValuesExpression = (Expression) Json.toObject(json, "availableValuesExpression");
2337
        if (json.getBoolean("fk", false)) {
2338
            this.foreingKey = new DefaultForeingKey();
2339
            this.foreingKey.setForeingKey(true);
2340
            this.foreingKey.setTableName(json.getString("fk_table", null));
2341
            this.foreingKey.setCodeName(json.getString("fk_code", null));
2342
            this.foreingKey.setLabelFormula(json.getString("fk_label", null));
2343
            this.foreingKey.setClosedList(json.getBoolean("fk_closedlist", false));
2344
        } else {
2345
            this.foreingKey = null;
2346
        }
2347
        this.defaultFormat = json.getString("defaultFormat",null);
2348
    }
2349

    
2350
    private static class TheJsonSerializer implements JsonManager.JsonSerializer {
2351

    
2352
        public TheJsonSerializer() {
2353
        }
2354

    
2355
        @Override
2356
        public Class getObjectClass() {
2357
            return DefaultFeatureAttributeDescriptor.class;
2358
        }
2359

    
2360
        @Override
2361
        public Object toObject(JsonObject json) {
2362
            DefaultFeatureAttributeDescriptor o = new DefaultFeatureAttributeDescriptor();
2363
            o.fromJson(json);
2364
            return o;
2365
        }
2366

    
2367
        @Override
2368
        public JsonObjectBuilder toJsonBuilder(Object value) {
2369
            return ((SupportToJson) value).toJsonBuilder();
2370
        }
2371

    
2372
    }
2373

    
2374
    public static void selfRegister() {
2375
        Json.registerSerializer(new TheJsonSerializer());
2376
    }
2377

    
2378
    @Override
2379
    public String getDefaultFormat() {
2380
        return this.defaultFormat;
2381
    }
2382

    
2383
    @Override
2384
    public String format(Object value) {
2385
        if(value == null){
2386
            return "";
2387
        }
2388
        try {
2389
            if( StringUtils.isBlank(this.defaultFormat)) {
2390
                if( this.locale==null ) { // !this.hasLocale()
2391
                    return DataTypeUtils.toString(Locale.getDefault(), value, Objects.toString(value, ""));
2392
                } else {
2393
                    return DataTypeUtils.toString(this.locale, value, Objects.toString(value, ""));
2394
                }
2395
            }
2396
            return String.format(this.defaultFormat, value);
2397
        } catch(Exception ex) {
2398
            return Objects.toString(value, "");
2399
        }
2400
    }
2401

    
2402
    
2403
}