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

History | View | Annotate | Download (75.3 KB)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
677
        return true;
678
    }
679

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

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

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

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

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

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

    
772
    }
773

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
942
    private Expression availableValuesFilter;
943

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

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

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

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

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

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

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

    
1012
    @Override
1013
    public boolean isAvailableValuesCalculated() {
1014
        return true; //this.availableValuesMethod != null;
1015
    }
1016

    
1017
    @Override
1018
    public DynObjectValueItem[] getAvailableValues() {
1019
        DynObjectValueItem[] values = this.availableValues;
1020

    
1021
        if (values != null) {
1022
            return values;
1023
        }
1024
        values = this.availableValuesCache;
1025
        if (values != null) {
1026
            return values;
1027
        }
1028
        if (this.isForeingKey() && this.foreingKey.isClosedList()) {
1029
            values = this.foreingKey.getAvailableValues(null);
1030

    
1031
        } else if (this.availableValuesExpression != null) {
1032
            values = this.getAvailableValuesFromExpression();
1033
        }
1034
        if (!this.avoidCachingAvailableValues) {
1035
            this.availableValuesCache = values;
1036
        }
1037
        return values;
1038
    }
1039

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

    
1174
    private DynObjectValueItem[] getAvailableValuesFromExpression() {
1175
        if (this.availableValuesExpression == null || this.availableValuesExpression.isEmpty()) {
1176
            return null;
1177
        }
1178
        try {
1179
            Object value = this.availableValuesExpression.execute(null);
1180
            if (value instanceof DynObjectValueItem[]) {
1181
                return (DynObjectValueItem[]) value;
1182
            }
1183
            if (value instanceof List) {
1184
                return this.getAvailableValuesFrom(new GetItemWithSize() {
1185
                    @Override
1186
                    public Object get(int i) {
1187
                        return ((List) value).get(i);
1188
                    }
1189

    
1190
                    @Override
1191
                    public int size() {
1192
                        return ((List) value).size();
1193
                    }
1194
                });
1195
            }
1196
        } catch (Throwable th) {
1197
            LOGGER.warn("Can't get available values from expression", th);
1198
        }
1199
        return null;
1200
    }
1201

    
1202
    @Override
1203
    public Expression getAvailableValuesExpression() {
1204
        return this.availableValuesExpression;
1205
    }
1206

    
1207
    @Override
1208
    public FeatureAttributeDescriptor setAvailableValuesExpression(String expression) {
1209
        if (StringUtils.isBlank(expression)) {
1210
            this.availableValuesExpression = null;
1211
            return this;
1212
        }
1213
        this.availableValuesExpression = ExpressionUtils.createExpression(expression);
1214
        return this;
1215
    }
1216

    
1217
    @Override
1218
    public FeatureAttributeDescriptor setAvailableValuesExpression(Expression expression) {
1219
        this.availableValuesExpression = expression;
1220
        return this;
1221
    }
1222

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

    
1248
    @Override
1249
    public String getDescription() {
1250
        if (this.description == null) {
1251
            return getName();
1252
        }
1253
        return this.description;
1254
    }
1255

    
1256
    @Override
1257
    public Object getMaxValue() {
1258
        return this.maxValue;
1259
    }
1260

    
1261
    @Override
1262
    public Object getMinValue() {
1263
        return this.minValue;
1264
    }
1265

    
1266
    @Override
1267
    public int getTheTypeOfAvailableValues() {
1268
        return 1;
1269
    }
1270

    
1271
    @Override
1272
    public int getType() {
1273
        if (featureAttributeGetter != null) {
1274
            return featureAttributeGetter.getDataType().getType();
1275
        }
1276
        return getDataType().getType();
1277
    }
1278

    
1279
    @Override
1280
    public boolean isMandatory() {
1281
        return !allowNull() || isPrimaryKey();
1282
    }
1283

    
1284
    @Override
1285
    public boolean isPersistent() {
1286
        return false;
1287
    }
1288

    
1289
    @Override
1290
    public DynField setAvailableValues(DynObjectValueItem[] values) {
1291
        if (ArrayUtils.isEmpty(values)) {
1292
            this.availableValues = null;
1293
        } else {
1294
            this.availableValues = values;
1295
        }
1296
        return this;
1297
    }
1298

    
1299
    @Override
1300
    public DynField setDescription(String description) {
1301
        this.description = description;
1302
        return this;
1303
    }
1304

    
1305
    @Override
1306
    public DynField setMandatory(boolean mandatory) {
1307
        throw new UnsupportedOperationException();
1308
    }
1309

    
1310
    @Override
1311
    public DynField setMaxValue(Object maxValue) {
1312
        try {
1313
            this.maxValue = this.coerce(maxValue);
1314
        } catch (CoercionException e) {
1315
            throw new IllegalArgumentException(e);
1316
        }
1317
        return this;
1318
    }
1319

    
1320
    @Override
1321
    public DynField setMinValue(Object minValue) {
1322
        try {
1323
            this.maxValue = this.coerce(minValue);
1324
        } catch (CoercionException e) {
1325
            throw new IllegalArgumentException(e);
1326
        }
1327
        return this;
1328
    }
1329

    
1330
    @Override
1331
    public DynField setPersistent(boolean persistent) {
1332
        throw new UnsupportedOperationException();
1333
    }
1334

    
1335
    @Override
1336
    public DynField setTheTypeOfAvailableValues(int type) {
1337
        throw new UnsupportedOperationException();
1338
    }
1339

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

    
1345
    @Override
1346
    @Deprecated
1347
    public DynField setDefaultDynValue(Object defaultValue) {
1348
        return this.setDefaultFieldValue(defaultValue);
1349
    }
1350

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

    
1357
    @Override
1358
    public Class getClassOfValue() {
1359
        return null;
1360
    }
1361

    
1362
    @Override
1363
    public DynField getElementsType() {
1364
        return null;
1365
    }
1366

    
1367
    @Override
1368
    public DynField setClassOfValue(Class theClass)
1369
            throws DynFieldIsNotAContainerException {
1370
        throw new UnsupportedOperationException();
1371
    }
1372

    
1373
    @Override
1374
    public DynField setElementsType(DynStruct type)
1375
            throws DynFieldIsNotAContainerException {
1376
        throw new UnsupportedOperationException();
1377
    }
1378

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

    
1385
    public FeatureAttributeDescriptor setDataProfileName(String dataProfile) {
1386
        this.dataProfile = dataProfile;
1387
        return this;
1388
    }
1389

    
1390
    @Override
1391
    public String getDataProfileName() {
1392
        return dataProfile;
1393
    }
1394

    
1395
    @Override
1396
    public DataProfile getDataProfile() {
1397
        if (StringUtils.isBlank(dataProfile)) {
1398
            return null;
1399
        }
1400
        DataProfile profile = DALLocator.getDataManager().getDataProfile(dataProfile);
1401
        return profile;
1402
    }
1403

    
1404
    @Override
1405
    public void validate(Object value) throws DynFieldValidateException {
1406

    
1407
        if (value == null && !this.allowNull()) {
1408
            throw new DynFieldValidateException(value, this, null);
1409
        }
1410

    
1411
        try {
1412
            this.dataType.coerce(value);
1413
        } catch (CoercionException e) {
1414
            throw new DynFieldValidateException(value, this, e);
1415
        }
1416

    
1417
        /*
1418
         * Other checks will be needed
1419
         */
1420
    }
1421

    
1422
    @Override
1423
    public String getSubtype() {
1424
        if (featureAttributeGetter != null) {
1425
            return featureAttributeGetter.getDataType().getSubtype();
1426
        }
1427
        return this.dataType.getSubtype();
1428
    }
1429

    
1430
    @Override
1431
    public Object coerce(Object value) throws CoercionException {
1432
        if (value == null) {
1433
            return value; // O debe devolver this.defaultValue
1434
        }
1435
        try {
1436
            return this.getDataType().coerce(value, this.getCoercionContext());
1437
        } catch (Exception ex) {
1438
            throw new RuntimeException(ex);
1439
        }
1440
    }
1441

    
1442
    @Override
1443
    public DynField setAvailableValues(List values) {
1444
        if (values == null || values.isEmpty()) {
1445
            this.availableValues = null;
1446
        } else {
1447
            this.availableValues = (DynObjectValueItem[]) values.toArray(
1448
                    new DynObjectValueItem[values.size()]
1449
            );
1450
        }
1451
        return this;
1452
    }
1453

    
1454
    @Override
1455
    public String getGroup() {
1456
        return this.groupName;
1457
    }
1458

    
1459
    @Override
1460
    public int getOder() {
1461
        return this.order;
1462
    }
1463

    
1464
    @Override
1465
    public String getLabel() {
1466
        if (this.label == null) {
1467
            return this.getName();
1468
        }
1469
        return this.label;
1470
    }
1471

    
1472
    @Override
1473
    public String getLocalizedLabel() {
1474
        if (StringUtils.isBlank(this.label)) {
1475
            return this.getName();
1476
        }
1477
        I18nManager i18n = ToolsLocator.getI18nManager();
1478
        return i18n.getTranslation(this.label);
1479
    }
1480

    
1481
    @Override
1482
    public DynField setLabel(String label) {
1483
        this.label = label;
1484
        return this;
1485
    }
1486

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

    
1493
    @Override
1494
    public String getShortLabel() {
1495
        return StringUtils.isBlank(shortLabel) ? getLabel() : shortLabel;
1496
    }
1497

    
1498
    @Override
1499
    public String getLocalizedShortLabel() {
1500
        if (StringUtils.isBlank(shortLabel)) {
1501
            return this.getLocalizedLabel();
1502
        }
1503
        I18nManager i18n = ToolsLocator.getI18nManager();
1504
        return i18n.getTranslation(shortLabel);
1505
    }
1506

    
1507
    @Override
1508
    public DynField setGroup(String groupName) {
1509
        this.groupName = groupName;
1510
        return this;
1511
    }
1512

    
1513
    @Override
1514
    public DynField setOrder(int order) {
1515
        this.order = order;
1516
        return this;
1517
    }
1518

    
1519
    @Override
1520
    public DynField setHidden(boolean hidden) {
1521
        this.hidden = hidden;
1522
        return this;
1523
    }
1524

    
1525
    @Override
1526
    public boolean isHidden() {
1527
        return this.hidden;
1528
    }
1529

    
1530
    @Override
1531
    public DynField setReadOnly(boolean readOnly) {
1532
        this.readOnly = readOnly;
1533
        return this;
1534
    }
1535

    
1536
    @Override
1537
    public boolean isContainer() {
1538
        return false;
1539
    }
1540

    
1541
    @Override
1542
    public Class getClassOfItems() {
1543
        return null;
1544
    }
1545

    
1546
    @Override
1547
    public DynField setClassOfItems(Class theClass) {
1548
        throw new UnsupportedOperationException();
1549
    }
1550

    
1551
    @Override
1552
    public DynField setType(DataType type) {
1553
        throw new UnsupportedOperationException();
1554
    }
1555

    
1556
    @Override
1557
    public DynField setSubtype(String subtype) {
1558
        throw new UnsupportedOperationException();
1559
    }
1560

    
1561
    @Override
1562
    public boolean isTime() {
1563
        return isTime;
1564
    }
1565

    
1566
    @Override
1567
    public FeatureAttributeGetter getFeatureAttributeGetter() {
1568
        return featureAttributeGetter;
1569
    }
1570

    
1571
    @Override
1572
    public void setFeatureAttributeGetter(
1573
            FeatureAttributeGetter featureAttributeTransform) {
1574
        this.featureAttributeGetter = featureAttributeTransform;
1575
    }
1576

    
1577
    @Override
1578
    public FeatureAttributeEmulator getFeatureAttributeEmulator() {
1579
        return this.featureAttributeEmulator;
1580
    }
1581

    
1582
    public FeatureAttributeDescriptor setFeatureAttributeEmulator(FeatureAttributeEmulator featureAttributeEmulator) {
1583
        this.featureAttributeEmulator = featureAttributeEmulator;
1584
        return this;
1585
    }
1586

    
1587
    @Override
1588
    public boolean isIndexed() {
1589
        return this.indexed;
1590
    }
1591

    
1592
    @Override
1593
    public boolean isForeingKey() {
1594
        return this.foreingKey != null && this.foreingKey.isForeingKey();
1595
    }
1596

    
1597
    @Override
1598
    public ForeingKey getForeingKey() {
1599
        return this.foreingKey;
1600
    }
1601

    
1602
    @Override
1603
    public boolean allowIndexDuplicateds() {
1604
        return this.allowIndexDuplicateds;
1605
    }
1606

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

    
1612
    @Override
1613
    public DynField setClassOfValue(DynStruct dynStrct) {
1614
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
1615
    }
1616

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

    
1622
    @Override
1623
    public String getClassNameOfValue() {
1624
        return null;
1625
    }
1626

    
1627
    @Override
1628
    public DynStruct getDynClassOfValue() {
1629
        return null;
1630
    }
1631

    
1632
    @Override
1633
    public DynField setTypeOfItems(int type) {
1634
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
1635
    }
1636

    
1637
    @Override
1638
    public int getTypeOfItems() {
1639
        return DataTypes.INVALID;
1640
    }
1641

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

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

    
1652
    @Override
1653
    public String getClassNameOfItems() {
1654
        return null;
1655
    }
1656

    
1657
    @Override
1658
    public DynStruct getDynClassOfItems() {
1659
        return null;
1660
    }
1661

    
1662
    @Override
1663
    public DynField setRelationType(int relationType) {
1664
        this.relationType = relationType;
1665
        return this;
1666
    }
1667

    
1668
    @Override
1669
    public int getRelationType() {
1670
        return this.relationType;
1671
    }
1672

    
1673
    @Override
1674
    public DynField setAvailableValues(DynMethod availableValuesMethod) {
1675
        this.availableValuesMethod = availableValuesMethod;
1676
        return this;
1677
    }
1678

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

    
1696
    @Override
1697
    public DynMethod getCalculateMethod() {
1698
        return this.calculateMethod;
1699
    }
1700

    
1701
    @Override
1702
    public DynField setCalculateMethod(DynMethod method) {
1703
        this.calculateMethod = method;
1704
        return this;
1705
    }
1706

    
1707
    @Override
1708
    public boolean isCalculated() {
1709
        return this.calculateMethod != null;
1710
    }
1711

    
1712
    @Override
1713
    public Object getCalculatedValue(DynObject self) {
1714
        try {
1715
            return this.calculateMethod.invoke(self, new Object[]{this});
1716
        } catch (DynMethodException ex) {
1717
            throw new RuntimeException(ex);
1718
        }
1719
    }
1720

    
1721
    @Override
1722
    public DynField setValidateElements(boolean validate) {
1723
        return this;
1724
    }
1725

    
1726
    @Override
1727
    public boolean getValidateElements() {
1728
        return false;
1729
    }
1730

    
1731
    @Override
1732
    public boolean hasLabel() {
1733
        return StringUtils.isNotBlank(this.label);
1734
    }
1735

    
1736
    @Override
1737
    public boolean hasShortLabel() {
1738
        return StringUtils.isNotBlank(this.shortLabel);
1739
    }
1740

    
1741
    @Override
1742
    public boolean hasDescription() {
1743
        return StringUtils.isNotBlank(this.description);
1744
    }
1745

    
1746
    @Override
1747
    public FeatureAttributeDescriptor getValue() {
1748
        return this;
1749
    }
1750

    
1751
    @Override
1752
    public int getDisplaySize() {
1753
        return this.displaySize;
1754
    }
1755

    
1756
    @Override
1757
    public boolean isInAvailableValues(Object valueToCheck) {
1758
        if (this.getAvailableValues() != null) {
1759
            for (DynObjectValueItem availableValue : this.getAvailableValues()) {
1760
                if (Objects.equals(valueToCheck, availableValue.getValue())) {
1761
                    return true;
1762
                }
1763
            }
1764
        }
1765
        return false;
1766
    }
1767

    
1768
    private class ConstantValueEvaluator extends AbstractEvaluator {
1769

    
1770
        @Override
1771
        public Object evaluate(EvaluatorData data) throws EvaluatorException {
1772
            return defaultValue;
1773
        }
1774

    
1775
        @Override
1776
        public String getName() {
1777
            return "Constant attribute " + name;
1778
        }
1779
    }
1780

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

    
1795
    @Override
1796
    public boolean isComputed() {
1797
        return featureAttributeEmulator != null || evaluator != null || isCalculated();
1798
    }
1799

    
1800
    @Override
1801
    public FeatureStore getStore() {
1802
        FeatureType ftype = this.getFeatureType();
1803
        if (ftype == null) {
1804
            return null;
1805
        }
1806
        return ftype.getStore();
1807
    }
1808

    
1809
    @Override
1810
    public FeatureType getFeatureType() {
1811
        if (this.typeRef == null) {
1812
            return null;
1813
        }
1814
        FeatureType ftype = (FeatureType) this.typeRef.get();
1815
//        LOGGER.info(String.format("FeatureAttributeDescriptor[%08x] get FeatureType [%08x], ref [%08x].", this.hashCode(), ftype.hashCode(), typeRef.hashCode()));
1816
        return ftype;
1817
    }
1818

    
1819
    public FeatureAttributeDescriptor setInterval(Interval interval) {
1820
        this.interval = interval;
1821
        return this;
1822
    }
1823

    
1824
    public void fixAll() {
1825
        if (!this.getDataType().supportSize()) {
1826
            this.size = 0;
1827
        }
1828
        NumberPrecisionAndScale ps = this.getDataType().fixPrecisionAndScale(this.precision, this.scale);
1829
        this.precision = ps.getPrecision();
1830
        this.scale = ps.getScale();
1831

    
1832
        switch (this.getType()) {
1833
            case DataTypes.INSTANT:
1834
            case DataTypes.INTERVAL:
1835
            case DataTypes.DATE:
1836
            case DataTypes.TIME:
1837
            case DataTypes.TIMESTAMP:
1838
                if (this.getInterval() != null) {
1839
                    this.isTime = true;
1840
                }
1841
                break;
1842
        }
1843
    }
1844

    
1845
    @Override
1846
    public String[] getRequiredFieldNames() {
1847
        FeatureAttributeEmulator emulator = this.getFeatureAttributeEmulator();
1848
        if (emulator == null) {
1849
            return null;
1850
        }
1851
        return emulator.getRequiredFieldNames();
1852
    }
1853

    
1854
    @Override
1855
    public void recentUsed() {
1856
        DefaultFeatureType.RECENTS_USEDS.add(this);
1857
    }
1858

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

    
1895
    private class PropertiesBuilder {
1896

    
1897
        private String name;
1898
        private DataType type;
1899
        private Map<String, String> sets;
1900
        private String sep;
1901

    
1902
        public PropertiesBuilder() {
1903
            this.sets = new LinkedHashMap<>();
1904
        }
1905

    
1906
        public void separator(String sep) {
1907
            this.sep = sep;
1908
        }
1909

    
1910
        public void name(String name) {
1911
            this.name = name;
1912
        }
1913

    
1914
        public void type(DataType type) {
1915
            this.type = type;
1916
        }
1917

    
1918
        public void set(String name, ForeingKey fk) {
1919
            if (fk == null) {
1920
                return;
1921
            }
1922
            if (!fk.isForeingKey()) {
1923
                return;
1924
            }
1925
            this.set(name, fk.isForeingKey());
1926
            this.set(name + "_code", fk.getCodeName());
1927
            this.set(name + "_label", fk.getLabelFormula());
1928
            this.set(name + "_closedlist", fk.isClosedList());
1929
            this.set(name + "_table", fk.getTableName());
1930
        }
1931

    
1932
        public void set(String name, FeatureAttributeEmulator value) {
1933
            if (value == null) {
1934
                return;
1935
            }
1936
            if (value instanceof FeatureAttributeEmulatorExpression) {
1937
                this.set(name, ((FeatureAttributeEmulatorExpression) value).getExpression().getPhrase());
1938
            }
1939
        }
1940

    
1941
        public void set(String name, IProjection value) {
1942
            if (value == null) {
1943
                return;
1944
            }
1945
            this.set(name, value.getAbrev());
1946
        }
1947

    
1948
        public void set(String name, GeometryType value) {
1949
            if (value == null) {
1950
                return;
1951
            }
1952
            this.set(name, value.getFullName().replace(":", "@"));
1953
        }
1954

    
1955
        public void set(String name, Object value) {
1956
            if (value == null) {
1957
                return;
1958
            }
1959
            String s = Objects.toString(value, "");
1960
            if (StringUtils.isBlank(s)) {
1961
                return;
1962
            }
1963
            this.sets.put(name, s);
1964
        }
1965

    
1966
        public void set(String name, Object value, Object skipValue) {
1967
            if (value == null || value == skipValue) {
1968
                return;
1969
            }
1970
            String s = Objects.toString(value, "");
1971
            if (StringUtils.isBlank(s)) {
1972
                return;
1973
            }
1974
            this.sets.put(name, s);
1975
        }
1976

    
1977
        @Override
1978
        public String toString() {
1979
            StringBuilder builder = new StringBuilder();
1980
            builder.append(this.name);
1981
            builder.append(sep);
1982
            builder.append(this.type.getName());
1983
            for (String key : this.sets.keySet()) {
1984
                builder.append(sep);
1985
                builder.append("set");
1986
                builder.append(sep);
1987
                builder.append(key);
1988
                builder.append("=");
1989
                builder.append(this.sets.get(key));
1990
            }
1991
            return builder.toString();
1992
        }
1993
    }
1994

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

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

    
2151
    public void setSRSForced(IProjection SRS) {
2152
        this.SRS = SRS;
2153
    }
2154

    
2155
    @Override
2156
    public JsonObject toJson() {
2157
        return this.toJsonBuilder().build();
2158
    }
2159

    
2160
    @Override
2161
    public JsonObjectBuilder toJsonBuilder() {
2162
        JsonObjectBuilder builder = Json.createObjectBuilder();
2163
        builder.add_class(this);
2164
        builder.add("name", this.name);
2165
        builder.add("description", this.description);
2166
        builder.add("label", this.label);
2167
        builder.add("shortLabel", this.shortLabel);
2168
        builder.add("order", this.order);
2169
        builder.add("groupName", this.groupName);
2170
        builder.add("dataType", this.dataType);
2171
        builder.add("size", this.size);
2172
        builder.add("precision", this.precision);
2173
        builder.add("scale", this.scale);
2174
        builder.add("roundMode", this.roundMode);
2175

    
2176
        builder.add("allowNull", this.allowNull);
2177
        builder.add("primaryKey", this.primaryKey);
2178
        builder.add("readOnly", this.readOnly);
2179
        builder.add("isAutomatic", this.isAutomatic);
2180
        builder.add("isTime", this.isTime);
2181
        builder.add("indexed", this.indexed);
2182
        builder.add("isIndexAscending", this.isIndexAscending);
2183
        builder.add("allowIndexDuplicateds", this.allowIndexDuplicateds);
2184
        builder.add("hidden", this.hidden);
2185
        builder.add("avoidCachingAvailableValues", this.avoidCachingAvailableValues);
2186

    
2187
        builder.add("geometryType", this.getGeomType());
2188
        builder.add("srs", this.getSRS());
2189

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

    
2210
    public void fromJson(JsonObject json) {
2211
        this.name = json.getString("name");
2212
        this.description = json.getString("description");
2213
        this.label = json.getString("label");
2214
        this.shortLabel = json.getString("shortLabel");
2215
        this.order = json.getInt("order");
2216
        this.groupName = json.getString("groupName");
2217
        this.precision = json.getInt("precision");
2218
        this.size = json.getInt("size");
2219
        this.scale = json.getInt("scale");
2220
        this.roundMode = json.getInt("roundMode");
2221

    
2222
        this.allowNull = json.getBoolean("allowNull");
2223
        this.primaryKey = json.getBoolean("primaryKey");
2224
        this.readOnly = json.getBoolean("readOnly");
2225
        this.isAutomatic = json.getBoolean("isAutomatic");
2226
        this.isTime = json.getBoolean("isTime");
2227
        this.indexed = json.getBoolean("indexed");
2228
        this.isIndexAscending = json.getBoolean("isIndexAscending");
2229
        this.allowIndexDuplicateds = json.getBoolean("allowIndexDuplicateds");
2230
        this.hidden = json.getBoolean("hidden");
2231
        this.avoidCachingAvailableValues = json.getBoolean("avoidCachingAvailableValues");
2232

    
2233
        this.relationType = json.getInt("relationType");
2234
        this.displaySize = json.getInt("displaySize");
2235

    
2236
        this.dataType = (DataType) Json.toObject(json, "dataType");
2237
        this.geomType = (GeometryType) Json.toObject(json, "geometryType");
2238
        this.SRS = (IProjection) Json.toObject(json, "srs");
2239
        this.locale = (Locale) Json.toObject(json, "locale");
2240
        this.featureAttributeEmulator = (FeatureAttributeEmulator) Json.toObject(json, "expression");
2241

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

    
2264
    private static class TheJsonSerializer implements JsonManager.JsonSerializer {
2265

    
2266
        public TheJsonSerializer() {
2267
        }
2268

    
2269
        @Override
2270
        public Class getObjectClass() {
2271
            return DefaultFeatureAttributeDescriptor.class;
2272
        }
2273

    
2274
        @Override
2275
        public Object toObject(JsonObject json) {
2276
            DefaultFeatureAttributeDescriptor o = new DefaultFeatureAttributeDescriptor();
2277
            o.fromJson(json);
2278
            return o;
2279
        }
2280

    
2281
        @Override
2282
        public JsonObjectBuilder toJsonBuilder(Object value) {
2283
            return ((SupportToJson) value).toJsonBuilder();
2284
        }
2285

    
2286
    }
2287

    
2288
    public static void selfRegister() {
2289
        Json.registerSerializer(new TheJsonSerializer());
2290
    }
2291

    
2292
}