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

History | View | Annotate | Download (78.1 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
        return allowNull;
332
    }
333

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

    
349
    @Override
350
    public DataType getDataType() {
351
        if (featureAttributeGetter != null) {
352
            return featureAttributeGetter.getDataType();
353
        }
354
        return this.dataType;
355
    }
356

    
357
    public FeatureAttributeDescriptor setDataType(int type) {
358
        this.dataType = ToolsLocator.getDataTypesManager().get(type);
359
        return this;
360
    }
361

    
362
    @Override
363
    public DateFormat getDateFormat() {
364
        return this.dateFormat;
365
    }
366

    
367
    @Override
368
    public Object getDefaultValue() {
369
        return this.defaultValue;
370
    }
371

    
372
    @Override
373
    @Deprecated
374
    public Object getDefaultValueCoerced() {
375
        return getCoercedDefaultValue();
376
    }
377

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

    
394
    @Override
395
    public Supplier getDefaultValueSupplier() {
396
        return (Supplier) this::getDefaultValueCoerced;
397
    }
398

    
399
    @Override
400
    public DynField setDefaultValueSupplier(Supplier supplier) {
401
        //Do nothing
402
        return this;
403
    }
404

    
405
    @Override
406
    public Evaluator getEvaluator() {
407
        return this.evaluator;
408
    }
409

    
410
    @Override
411
    public int getGeometryType() {
412
        if (this.dataType.getType() != DataTypes.GEOMETRY) {
413
            return Geometry.TYPES.UNKNOWN;
414
        }
415
        return this.geometryType;
416
    }
417

    
418
    @Override
419
    public int getGeometrySubType() {
420
        if (this.dataType.getType() != DataTypes.GEOMETRY) {
421
            return Geometry.SUBTYPES.UNKNOWN;
422
        }
423
        return this.geometrySubType;
424
    }
425

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

    
446
    @Override
447
    public int getIndex() {
448
        return this.index;
449
    }
450

    
451
    protected FeatureAttributeDescriptor setIndex(int index) {
452
        this.index = index;
453
        return this;
454
    }
455

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

    
461
    @Override
462
    public int getMinimumOccurrences() {
463
        return this.minimumOccurrences;
464
    }
465

    
466
    @Override
467
    public String getName() {
468
        return this.name;
469
    }
470

    
471
    public FeatureAttributeDescriptor setName(String name) {
472
//        LOGGER.info(String.format("FeatureAttributeDescriptor[%08x] set name [%s].", this.hashCode(), name));
473
        this.name = name;
474
        return this;
475
    }
476

    
477
    @Override
478
    public Class getObjectClass() {
479
        if (getDataType().getType() == DataTypes.OBJECT) {
480
            return objectClass;
481
        }
482
        return getDataType().getDefaultClass();
483
    }
484

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

    
490
    @Override
491
    public int getScale() {
492
        return this.scale;
493
    }
494

    
495
    @Override
496
    public Coercion getCoercion() {
497
        return this.getDataType().getCoercion();
498
    }
499

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

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

    
539
    @Override
540
    public int getRoundMode() {
541
        return this.roundMode;
542
    }
543

    
544
    @Override
545
    public IProjection getSRS() {
546
        return this.SRS;
547
    }
548

    
549
    @Override
550
    public Interval getInterval() {
551
        return this.interval;
552
    }
553

    
554
    public IProjection getSRS(WeakReference storeRef) {
555
        if (this.SRS == null) {
556
            FeatureStore store = (FeatureStore) storeRef.get();
557
            this.SRS = (IProjection) store.getDynValue(DataStore.METADATA_CRS);
558
        }
559
        return this.SRS;
560
    }
561

    
562
    @Override
563
    public int getSize() {
564
        return this.size;
565
    }
566

    
567
    @Override
568
    public boolean isPrimaryKey() {
569
        return this.primaryKey;
570
    }
571

    
572
    @Override
573
    public boolean isReadOnly() {
574
        if (this.readOnly) {
575
            return true;
576
        }
577
        return this.isComputed();
578
    }
579

    
580
    @Override
581
    public String getAdditionalInfo(String infoName) {
582
        if (this.additionalInfo == null) {
583
            return null;
584
        }
585
        return this.additionalInfo.get(infoName);
586
    }
587

    
588
    @Override
589
    public boolean isAutomatic() {
590
        return this.isAutomatic;
591
    }
592

    
593
    @Override
594
    public boolean equals(Object obj) {
595
        if (this == obj) {
596
            return true;
597
        }
598
        if (!(obj instanceof DefaultFeatureAttributeDescriptor)) {
599
            return false;
600
        }
601
        DefaultFeatureAttributeDescriptor other
602
                = (DefaultFeatureAttributeDescriptor) obj;
603

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

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

    
612
        if (!Objects.equals(this.name, other.name)) {
613
            return false;
614
        }
615

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

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

    
624
        if (!Objects.equals(this.defaultValue, other.defaultValue)) {
625
            return false;
626
        }
627
        if (!Objects.equals(this.defaultFormat, other.defaultFormat)) {
628
            return false;
629
        }
630

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

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

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

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

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

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

    
655
        if (this.geometryType != other.geometryType) {
656
            return false;
657
        }
658

    
659
        if (this.geometrySubType != other.geometrySubType) {
660
            return false;
661
        }
662

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

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

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

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

    
679
        if (!Objects.equals(this.objectClass, other.objectClass)) {
680
            return false;
681
        }
682

    
683
        if (!Objects.equals(this.dataProfile, other.dataProfile)) {
684
            return false;
685
        }
686

    
687
        return true;
688
    }
689

    
690
    @Override
691
    public void loadFromState(PersistentState state)
692
            throws PersistenceException {
693
        allowNull = state.getBoolean("allowNull");
694
        dataType = ToolsLocator.getDataTypesManager().get(state.getInt("dataType"));
695
        dataProfile = state.getString("dataProfile");
696

    
697
//        FIXME: dateFormat;
698
        try {
699
            defaultValue = dataType.coerce(state.get("defaultValue"));
700
        } catch (CoercionException ex) {
701
        }
702

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

    
749
        Map<String, Object> values = state.getMap("availableValues");
750
        if (values == null || values.isEmpty()) {
751
            this.availableValues = null;
752
        } else {
753
            this.availableValues = new DynObjectValueItem[values.size()];
754
            int n = 0;
755
            Coercion coercion = this.getCoercion();
756
            for (Entry<String, Object> entry : values.entrySet()) {
757
                Object value;
758
                try {
759
                    value = coercion.coerce(entry.getValue());
760
                } catch (CoercionException ex) {
761
                    value = entry.getValue();
762
                }
763
                this.availableValues[n++] = new DynObjectValueItem(value, entry.getKey());
764
            }
765
        }
766

    
767
        description = state.getString("description");
768
        minValue = state.get("minValue");
769
        maxValue = state.get("maxValue");
770
        label = state.getString("label");
771
        order = state.getInt("order");
772
        hidden = state.getBoolean("hidden");
773
        groupName = state.getString("groupName");
774
        relationType = state.getInt("relationType", RELATION_TYPE_NONE);
775

    
776
        foreingKey = (DefaultForeingKey) state.get("foreingKey");
777
        if (foreingKey != null) {
778
            this.foreingKey.setDescriptor(this);
779
        }
780
        tags = (Tags) state.get("tags");
781
        if (tags == null) {
782
            this.tags = new DefaultTags();
783
        }
784
        displaySize = state.getInt("displaySize", 0);
785
        availableValuesExpression = (Expression) state.get("availableValuesExpression");
786
        avoidCachingAvailableValues = state.getBoolean("avoidCachingAvailableValues", false);
787
        availableValuesCache = null;
788
        defaultFormat = state.getString("defaultFormat");
789
    }
790

    
791
    @Override
792
    public void saveToState(PersistentState state) throws PersistenceException {
793
        Coercion toString = ToolsLocator.getDataTypesManager().getCoercion(DataTypes.STRING);
794

    
795
        state.set("allowNull", allowNull);
796
        state.set("dataType", dataType.getType());
797
        state.set("dataProfile", dataProfile);
798

    
799
//        FIXME: dateFormat;
800
        state.set("defaultValue", Objects.toString(defaultValue, null));
801

    
802
        state.set("index", index);
803
        state.set("maximumOccurrences", maximumOccurrences);
804
        state.set("minimumOccurrences", minimumOccurrences);
805
        state.set("size", size);
806
        state.set("name", name);
807
        state.set("objectClass", objectClass == null ? null : objectClass.getName());
808
        state.set("precision", precision);
809
        state.set("scale", scale);
810
        state.set("roundMode", roundMode);
811
        if (this.locale == null) {
812
            state.setNull("locale");
813
        } else {
814
            state.set("locale", this.locale.toLanguageTag()); //toString.coerce(this.locale));
815
        }
816
        state.set("evaluator", evaluator);
817

    
818
        state.set("primaryKey", primaryKey);
819
        state.set("readOnly", readOnly);
820
        state.set("SRS", SRS);
821
        GeometryType theGeomType = this.getGeomType();
822
        if (theGeomType == null) {
823
            state.set("geometryType", Geometry.TYPES.UNKNOWN);
824
            state.set("geometrySubType", Geometry.SUBTYPES.UNKNOWN);
825
        } else {
826
            state.set("geometryType", theGeomType.getType());
827
            state.set("geometrySubType", theGeomType.getSubType());
828
        }
829

    
830
//      FIXME: additionalInfo
831
        state.set("isAutomatic", isAutomatic);
832
        state.set("isTime", isTime);
833
        if (this.interval == null) {
834
            state.setNull("interval_start");
835
            state.setNull("interval_end");
836
        } else {
837
            state.set("interval_start", ((RelativeInterval) interval).getStart().toMillis());
838
            state.set("interval_end", ((RelativeInterval) interval).getEnd().toMillis());
839
        }
840
        state.set("SRS", SRS);
841

    
842
//      FIXME: featureAttributeGetter
843
        if (featureAttributeEmulator instanceof Persistent) {
844
            state.set("featureAttributeEmulator", featureAttributeEmulator);
845
        } else {
846
            state.setNull("featureAttributeEmulator");
847
        }
848

    
849
        state.set("indexed", indexed);
850
        state.set("isIndexAscending", isIndexAscending);
851
        state.set("allowIndexDuplicateds", allowIndexDuplicateds);
852

    
853
        if (this.availableValues == null) {
854
            state.setNull("availableValues");
855
        } else {
856
            Map<String, Object> values = new LinkedHashMap<>();
857
            for (DynObjectValueItem value : availableValues) {
858
                if( value!=null ) {
859
                    values.put(value.getLabel(), value.getValue());
860
                }
861
            }
862
            state.set("availableValues", values);
863
        }
864
        state.set("description", description);
865
        state.set("minValue", minValue);
866
        state.set("maxValue", maxValue);
867
        state.set("label", label);
868
        state.set("order", order);
869
        state.set("hidden", hidden);
870
        state.set("groupName", groupName);
871
        state.set("relationType", relationType);
872

    
873
        state.set("foreingKey", this.foreingKey);
874
        state.set("tags", this.tags);
875

    
876
        state.set("displaySize", displaySize);
877
        state.set("availableValuesExpression", availableValuesExpression);
878
        state.set("avoidCachingAvailableValues", avoidCachingAvailableValues);
879
        state.set("defaultFormat", defaultFormat);
880
    }
881

    
882
    private static final String FEATATTRDESC_PERSISTENCE_DEFINITION_NAME = "FeatureAttributeDescriptor";
883

    
884
    public static void registerPersistenceDefinition() {
885
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
886

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

    
940
            definition.addDynFieldObject("foreingKey")
941
                    .setClassOfValue(DefaultForeingKey.class);
942

    
943
            definition.addDynFieldObject("tags")
944
                    .setClassOfValue(Tags.class);
945

    
946
            definition.addDynFieldInt("displaySize").setMandatory(false);
947
            definition.addDynFieldObject("availableValuesExpression")
948
                    .setClassOfValue(Expression.class)
949
                    .setMandatory(false);
950
            definition.addDynFieldString("defaultFormat").setMandatory(false);
951
        }
952
    }
953

    
954
    /*
955
     * Start of DynField interface Implementation
956
     *
957
     */
958
    @Override
959
    public Tags getTags() {
960
        return tags;
961
    }
962

    
963
    private Expression availableValuesFilter;
964

    
965
    @Override
966
    public Expression getAvailableValuesFilter() {
967
        return this.availableValuesFilter;
968
    }
969

    
970
    public FeatureAttributeDescriptor setAvailableValuesFilter(Expression filter) {
971
        this.availableValuesFilter = filter;
972
        return this;
973
    }
974

    
975
    public FeatureAttributeDescriptor setAvailableValuesFilter(String filter) {
976
        this.availableValuesFilter = ExpressionUtils.createExpression(filter);
977
        return this;
978
    }
979

    
980
    @Override
981
    public boolean hasConstantAvailableValues() {
982
        return this.availableValues != null;
983
    }
984

    
985
    @Override
986
    public boolean isAvoidCachingAvailableValues() {
987
        return this.avoidCachingAvailableValues;
988
    }
989

    
990
    public boolean hasAvailableValues() {
991
        return getAvailableValues() != null;
992
    }
993

    
994
    @Override
995
    public DynObjectValueItem[] getAvailableValues(DynObject context) {
996
        if (this.availableValuesMethod != null) {
997
            DynObjectValueItem[] values;
998
            try {
999
                values = (DynObjectValueItem[]) this.availableValuesMethod.invoke(context, new Object[]{this});
1000
            } catch (DynMethodException ex) {
1001
                return this.getAvailableValues();
1002
            }
1003
            if (values != null) {
1004
                return values;
1005
            }
1006
        }
1007
        Expression filter = this.availableValuesFilter;
1008
        if (!ExpressionUtils.isEmpty(filter)) {
1009
            if (this.isForeingKey() && this.foreingKey.isClosedList()) {
1010
                ContextForeingKey foreingkeyContext = this.foreingKey.createContext();
1011
                foreingkeyContext.setContextValues(context);
1012
                DynObjectValueItem[] values = this.foreingKey.getAvailableValues(foreingkeyContext);
1013
                return values;
1014
            }
1015
            MutableSymbolTable contextSymbolTable = ExpressionUtils.createSymbolTable("feature", context);
1016
            MutableSymbolTable symbolTable = ExpressionUtils.createSymbolTable();
1017
            symbolTable.addSymbolTable(contextSymbolTable);
1018

    
1019
            DynObjectValueItem[] allValues = this.getAvailableValues();
1020
            List<DynObjectValueItem> filteredValues = new ArrayList<>();
1021
            for (DynObjectValueItem value : allValues) {
1022
                symbolTable.setVar("$value", value.getValue());
1023
                symbolTable.setVar("$label", value.getLabel());
1024
                Object include = filter.execute(symbolTable);
1025
                if (DataTypeUtils.isFalse(include, false)) {
1026
                    continue;
1027
                }
1028
                filteredValues.add(value);
1029
            }
1030
            DynObjectValueItem[] values = filteredValues.toArray(
1031
                    new DynObjectValueItem[filteredValues.size()]
1032
            );
1033
            return values;
1034
        }
1035
        return this.getAvailableValues();
1036
    }
1037

    
1038
    @Override
1039
    public boolean isAvailableValuesCalculated() {
1040
        if (this.availableValuesMethod != null) {
1041
            return true;
1042
        }
1043
        if (!ExpressionUtils.isEmpty(this.availableValuesFilter)) {
1044
            return true;
1045
        }
1046
        return false;
1047
    }
1048

    
1049
    @Override
1050
    public DynObjectValueItem[] getAvailableValues() {
1051
        DynObjectValueItem[] values = this.availableValues;
1052

    
1053
        if (values != null) {
1054
            return values;
1055
        }
1056
        values = this.availableValuesCache;
1057
        if (values != null) {
1058
            return values;
1059
        }
1060
        if (this.isForeingKey() && this.foreingKey.isClosedList()) {
1061
            values = this.foreingKey.getAvailableValues(null);
1062

    
1063
        } else if (this.availableValuesExpression != null) {
1064
            values = this.getAvailableValuesFromExpression();
1065
        }
1066
        if (!this.avoidCachingAvailableValues) {
1067
            this.availableValuesCache = values;
1068
        }
1069
        return values;
1070
    }
1071

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

    
1206
    private DynObjectValueItem[] getAvailableValuesFromExpression() {
1207
        if (this.availableValuesExpression == null || this.availableValuesExpression.isEmpty()) {
1208
            return null;
1209
        }
1210
        try {
1211
            Object value = this.availableValuesExpression.execute(null);
1212
            if (value instanceof DynObjectValueItem[]) {
1213
                return (DynObjectValueItem[]) value;
1214
            }
1215
            if (value instanceof List) {
1216
                return this.getAvailableValuesFrom(new GetItemWithSize() {
1217
                    @Override
1218
                    public Object get(int i) {
1219
                        return ((List) value).get(i);
1220
                    }
1221

    
1222
                    @Override
1223
                    public int size() {
1224
                        return ((List) value).size();
1225
                    }
1226
                });
1227
            }
1228
        } catch (Throwable th) {
1229
            LOGGER.warn("Can't get available values from expression", th);
1230
        }
1231
        return null;
1232
    }
1233

    
1234
    @Override
1235
    public Expression getAvailableValuesExpression() {
1236
        return this.availableValuesExpression;
1237
    }
1238

    
1239
    @Override
1240
    public FeatureAttributeDescriptor setAvailableValuesExpression(String expression) {
1241
        if (StringUtils.isBlank(expression)) {
1242
            this.availableValuesExpression = null;
1243
            return this;
1244
        }
1245
        this.availableValuesExpression = ExpressionUtils.createExpression(expression);
1246
        return this;
1247
    }
1248

    
1249
    @Override
1250
    public FeatureAttributeDescriptor setAvailableValuesExpression(Expression expression) {
1251
        this.availableValuesExpression = expression;
1252
        return this;
1253
    }
1254

    
1255
    @Override
1256
    public String getLabelOfValue(Object value) {
1257
        if (this.labelOfValueMap != null) {
1258
            String theLabel = this.labelOfValueMap.get(value);
1259
            if (theLabel == null) {
1260
                theLabel = Objects.toString(value, "");
1261
            }
1262
            return theLabel;
1263
        }
1264
        DynObjectValueItem[] values = this.getAvailableValues();
1265
        if (values == null) {
1266
            return Objects.toString(value, "");
1267
        }
1268
        Map<Object, String> map = new LinkedHashMap<>();
1269
        for (DynObjectValueItem theValue : values) {
1270
            map.put(theValue.getValue(), theValue.getLabel());
1271
        }
1272
        this.labelOfValueMap = map;
1273
        String theLabel = this.labelOfValueMap.get(value);
1274
        if (theLabel == null) {
1275
            theLabel = Objects.toString(value, "");
1276
        }
1277
        return theLabel;
1278
    }
1279

    
1280
    @Override
1281
    public String getDescription() {
1282
        if (this.description == null) {
1283
            return getName();
1284
        }
1285
        return this.description;
1286
    }
1287

    
1288
    @Override
1289
    public Object getMaxValue() {
1290
        return this.maxValue;
1291
    }
1292

    
1293
    @Override
1294
    public Object getMinValue() {
1295
        return this.minValue;
1296
    }
1297

    
1298
    @Override
1299
    public int getTheTypeOfAvailableValues() {
1300
        return 1;
1301
    }
1302

    
1303
    @Override
1304
    public int getType() {
1305
        if (featureAttributeGetter != null) {
1306
            return featureAttributeGetter.getDataType().getType();
1307
        }
1308
        return getDataType().getType();
1309
    }
1310

    
1311
    @Override
1312
    public boolean isMandatory() {
1313
        return !allowNull() || isPrimaryKey();
1314
    }
1315

    
1316
    @Override
1317
    public boolean isPersistent() {
1318
        return false;
1319
    }
1320

    
1321
    @Override
1322
    public DynField setAvailableValues(DynObjectValueItem[] values) {
1323
        if (ArrayUtils.isEmpty(values)) {
1324
            this.availableValues = null;
1325
        } else {
1326
            Coercion coercion = this.getCoercion();
1327
            this.availableValues = new DynObjectValueItem[values.length];
1328
            for (int i = 0; i < values.length; i++) {
1329
                DynObjectValueItem element = values[i];
1330
                Object value;
1331
                try {
1332
                    value = coercion.coerce(element.getValue());
1333
                } catch (CoercionException ex) {
1334
                    value = element.getValue();
1335
                }
1336
                this.availableValues[i] = new DynObjectValueItem(value, element.getLabel());
1337
            }
1338
        }
1339
        return this;
1340
    }
1341

    
1342
    @Override
1343
    public DynField setDescription(String description) {
1344
        this.description = description;
1345
        return this;
1346
    }
1347

    
1348
    @Override
1349
    public DynField setMandatory(boolean mandatory) {
1350
        throw new UnsupportedOperationException();
1351
    }
1352

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

    
1363
    @Override
1364
    public DynField setMinValue(Object minValue) {
1365
        try {
1366
            this.maxValue = this.coerce(minValue);
1367
        } catch (CoercionException e) {
1368
            throw new IllegalArgumentException(e);
1369
        }
1370
        return this;
1371
    }
1372

    
1373
    @Override
1374
    public DynField setPersistent(boolean persistent) {
1375
        throw new UnsupportedOperationException();
1376
    }
1377

    
1378
    @Override
1379
    public DynField setTheTypeOfAvailableValues(int type) {
1380
        throw new UnsupportedOperationException();
1381
    }
1382

    
1383
    @Override
1384
    public DynField setType(int type) {
1385
        throw new UnsupportedOperationException();
1386
    }
1387

    
1388
    @Override
1389
    @Deprecated
1390
    public DynField setDefaultDynValue(Object defaultValue) {
1391
        return this.setDefaultFieldValue(defaultValue);
1392
    }
1393

    
1394
    @Override
1395
    public DynField setDefaultFieldValue(Object defaultValue) {
1396
        this.defaultValue = defaultValue;
1397
        return this;
1398
    }
1399

    
1400
    @Override
1401
    public Class getClassOfValue() {
1402
        return null;
1403
    }
1404

    
1405
    @Override
1406
    public DynField getElementsType() {
1407
        return null;
1408
    }
1409

    
1410
    @Override
1411
    public DynField setClassOfValue(Class theClass)
1412
            throws DynFieldIsNotAContainerException {
1413
        throw new UnsupportedOperationException();
1414
    }
1415

    
1416
    @Override
1417
    public DynField setElementsType(DynStruct type)
1418
            throws DynFieldIsNotAContainerException {
1419
        throw new UnsupportedOperationException();
1420
    }
1421

    
1422
    @Override
1423
    public DynField setElementsType(int type)
1424
            throws DynFieldIsNotAContainerException {
1425
        throw new UnsupportedOperationException();
1426
    }
1427

    
1428
    public FeatureAttributeDescriptor setDataProfileName(String dataProfile) {
1429
        this.dataProfile = dataProfile;
1430
        return this;
1431
    }
1432

    
1433
    @Override
1434
    public String getDataProfileName() {
1435
        return dataProfile;
1436
    }
1437

    
1438
    @Override
1439
    public DataProfile getDataProfile() {
1440
        if (StringUtils.isBlank(dataProfile)) {
1441
            return null;
1442
        }
1443
        DataProfile profile = DALLocator.getDataManager().getDataProfile(dataProfile);
1444
        return profile;
1445
    }
1446

    
1447
    @Override
1448
    public void validate(Object value) throws DynFieldValidateException {
1449

    
1450
        if (value == null && !this.allowNull()) {
1451
            throw new DynFieldValidateException(value, this, null);
1452
        }
1453

    
1454
        try {
1455
            this.dataType.coerce(value);
1456
        } catch (CoercionException e) {
1457
            throw new DynFieldValidateException(value, this, e);
1458
        }
1459

    
1460
        /*
1461
         * Other checks will be needed
1462
         */
1463
    }
1464

    
1465
    @Override
1466
    public String getSubtype() {
1467
        if (featureAttributeGetter != null) {
1468
            return featureAttributeGetter.getDataType().getSubtype();
1469
        }
1470
        return this.dataType.getSubtype();
1471
    }
1472

    
1473
    @Override
1474
    public Object coerce(Object value) throws CoercionException {
1475
        if (value == null) {
1476
            return value; // O debe devolver this.defaultValue
1477
        }
1478
        try {
1479
            return this.getDataType().coerce(value, this.getCoercionContext());
1480
        } catch (Exception ex) {
1481
            throw new RuntimeException(ex);
1482
        }
1483
    }
1484

    
1485
    @Override
1486
    public DynField setAvailableValues(List values) {
1487
        if (values == null || values.isEmpty()) {
1488
            this.availableValues = null;
1489
        } else {
1490
            this.availableValues = (DynObjectValueItem[]) values.toArray(
1491
                    new DynObjectValueItem[values.size()]
1492
            );
1493
        }
1494
        return this;
1495
    }
1496

    
1497
    @Override
1498
    public String getGroup() {
1499
        return this.groupName;
1500
    }
1501

    
1502
    @Override
1503
    public int getOder() {
1504
        return this.order;
1505
    }
1506

    
1507
    @Override
1508
    public String getLabel() {
1509
        if (this.label == null) {
1510
            return this.getName();
1511
        }
1512
        return this.label;
1513
    }
1514

    
1515
    @Override
1516
    public String getLocalizedLabel() {
1517
        if (StringUtils.isBlank(this.label)) {
1518
            return this.getName();
1519
        }
1520
        I18nManager i18n = ToolsLocator.getI18nManager();
1521
        return i18n.getTranslation(this.label);
1522
    }
1523

    
1524
    @Override
1525
    public DynField setLabel(String label) {
1526
        this.label = label;
1527
        return this;
1528
    }
1529

    
1530
    @Override
1531
    public DynField setShortLabel(String shortLabel) {
1532
        this.shortLabel = shortLabel;
1533
        return this;
1534
    }
1535

    
1536
    @Override
1537
    public String getShortLabel() {
1538
        return StringUtils.isBlank(shortLabel) ? getLabel() : shortLabel;
1539
    }
1540

    
1541
    @Override
1542
    public String getLocalizedShortLabel() {
1543
        if (StringUtils.isBlank(shortLabel)) {
1544
            return this.getLocalizedLabel();
1545
        }
1546
        I18nManager i18n = ToolsLocator.getI18nManager();
1547
        return i18n.getTranslation(shortLabel);
1548
    }
1549

    
1550
    @Override
1551
    public DynField setGroup(String groupName) {
1552
        this.groupName = groupName;
1553
        return this;
1554
    }
1555

    
1556
    @Override
1557
    public DynField setOrder(int order) {
1558
        this.order = order;
1559
        return this;
1560
    }
1561

    
1562
    @Override
1563
    public DynField setHidden(boolean hidden) {
1564
        this.hidden = hidden;
1565
        return this;
1566
    }
1567

    
1568
    @Override
1569
    public boolean isHidden() {
1570
        return this.hidden;
1571
    }
1572

    
1573
    @Override
1574
    public DynField setReadOnly(boolean readOnly) {
1575
        this.readOnly = readOnly;
1576
        return this;
1577
    }
1578

    
1579
    @Override
1580
    public boolean isContainer() {
1581
        return false;
1582
    }
1583

    
1584
    @Override
1585
    public Class getClassOfItems() {
1586
        return null;
1587
    }
1588

    
1589
    @Override
1590
    public DynField setClassOfItems(Class theClass) {
1591
        throw new UnsupportedOperationException();
1592
    }
1593

    
1594
    @Override
1595
    public DynField setType(DataType type) {
1596
        throw new UnsupportedOperationException();
1597
    }
1598

    
1599
    @Override
1600
    public DynField setSubtype(String subtype) {
1601
        throw new UnsupportedOperationException();
1602
    }
1603

    
1604
    @Override
1605
    public boolean isTime() {
1606
        return isTime;
1607
    }
1608

    
1609
    @Override
1610
    public FeatureAttributeGetter getFeatureAttributeGetter() {
1611
        return featureAttributeGetter;
1612
    }
1613

    
1614
    @Override
1615
    public void setFeatureAttributeGetter(
1616
            FeatureAttributeGetter featureAttributeTransform) {
1617
        this.featureAttributeGetter = featureAttributeTransform;
1618
    }
1619

    
1620
    @Override
1621
    public FeatureAttributeEmulator getFeatureAttributeEmulator() {
1622
        return this.featureAttributeEmulator;
1623
    }
1624

    
1625
    public FeatureAttributeDescriptor setFeatureAttributeEmulator(FeatureAttributeEmulator featureAttributeEmulator) {
1626
        this.featureAttributeEmulator = featureAttributeEmulator;
1627
        return this;
1628
    }
1629

    
1630
    @Override
1631
    public boolean isIndexed() {
1632
        return this.indexed;
1633
    }
1634

    
1635
    @Override
1636
    public boolean isForeingKey() {
1637
        return this.foreingKey != null && this.foreingKey.isForeingKey();
1638
    }
1639

    
1640
    @Override
1641
    public ForeingKey getForeingKey() {
1642
        return this.foreingKey;
1643
    }
1644

    
1645
    @Override
1646
    public boolean allowIndexDuplicateds() {
1647
        return this.allowIndexDuplicateds;
1648
    }
1649

    
1650
    @Override
1651
    public boolean isIndexAscending() {
1652
        return this.isIndexAscending;
1653
    }
1654

    
1655
    @Override
1656
    public DynField setClassOfValue(DynStruct dynStrct) {
1657
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
1658
    }
1659

    
1660
    @Override
1661
    public DynField setClassOfValue(String theClassNameOfValue) {
1662
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
1663
    }
1664

    
1665
    @Override
1666
    public String getClassNameOfValue() {
1667
        return null;
1668
    }
1669

    
1670
    @Override
1671
    public DynStruct getDynClassOfValue() {
1672
        return null;
1673
    }
1674

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

    
1680
    @Override
1681
    public int getTypeOfItems() {
1682
        return DataTypes.INVALID;
1683
    }
1684

    
1685
    @Override
1686
    public DynField setClassOfItems(DynStruct dynStrct) {
1687
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
1688
    }
1689

    
1690
    @Override
1691
    public DynField setClassOfItems(String theClassNameOfValue) {
1692
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
1693
    }
1694

    
1695
    @Override
1696
    public String getClassNameOfItems() {
1697
        return null;
1698
    }
1699

    
1700
    @Override
1701
    public DynStruct getDynClassOfItems() {
1702
        return null;
1703
    }
1704

    
1705
    @Override
1706
    public DynField setRelationType(int relationType) {
1707
        this.relationType = relationType;
1708
        return this;
1709
    }
1710

    
1711
    @Override
1712
    public int getRelationType() {
1713
        return this.relationType;
1714
    }
1715

    
1716
    @Override
1717
    public DynField setAvailableValues(DynMethod availableValuesMethod) {
1718
        this.availableValuesMethod = availableValuesMethod;
1719
        return this;
1720
    }
1721

    
1722
    @Override
1723
    public DynMethod getAvailableValuesMethod() {
1724
        if (this.availableValuesMethod != null) {
1725
            return this.availableValuesMethod;
1726
        }
1727
        if (this.availableValuesFilter == null && !this.isForeingKey()) {
1728
            return null;
1729
        }
1730
        DynMethod method = new AbstractDynMethod("getAvailableValuesOf" + this.getName()) {
1731
            @Override
1732
            public Object invoke(DynObject context, Object[] args) throws DynMethodException {
1733
                return getAvailableValues(context);
1734
            }
1735
        };
1736
        return method;
1737
    }
1738

    
1739
    @Override
1740
    public DynMethod getCalculateMethod() {
1741
        return this.calculateMethod;
1742
    }
1743

    
1744
    @Override
1745
    public DynField setCalculateMethod(DynMethod method) {
1746
        this.calculateMethod = method;
1747
        return this;
1748
    }
1749

    
1750
    @Override
1751
    public boolean isCalculated() {
1752
        return this.calculateMethod != null;
1753
    }
1754

    
1755
    @Override
1756
    public Object getCalculatedValue(DynObject self) {
1757
        try {
1758
            return this.calculateMethod.invoke(self, new Object[]{this});
1759
        } catch (DynMethodException ex) {
1760
            throw new RuntimeException(ex);
1761
        }
1762
    }
1763

    
1764
    @Override
1765
    public DynField setValidateElements(boolean validate) {
1766
        return this;
1767
    }
1768

    
1769
    @Override
1770
    public boolean getValidateElements() {
1771
        return false;
1772
    }
1773

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

    
1779
    @Override
1780
    public boolean hasShortLabel() {
1781
        return StringUtils.isNotBlank(this.shortLabel);
1782
    }
1783

    
1784
    @Override
1785
    public boolean hasDescription() {
1786
        return StringUtils.isNotBlank(this.description);
1787
    }
1788

    
1789
    @Override
1790
    public FeatureAttributeDescriptor getValue() {
1791
        return this;
1792
    }
1793

    
1794
    @Override
1795
    public int getDisplaySize() {
1796
        return this.displaySize;
1797
    }
1798

    
1799
    @Override
1800
    public boolean isInAvailableValues(Object valueToCheck) {
1801
        if (this.getAvailableValues() != null) {
1802
            for (DynObjectValueItem availableValue : this.getAvailableValues()) {
1803
                if (Objects.equals(valueToCheck, availableValue.getValue())) {
1804
                    return true;
1805
                }
1806
            }
1807
        }
1808
        return false;
1809
    }
1810

    
1811
    private class ConstantValueEvaluator extends AbstractEvaluator {
1812

    
1813
        @Override
1814
        public Object evaluate(EvaluatorData data) throws EvaluatorException {
1815
            return defaultValue;
1816
        }
1817

    
1818
        @Override
1819
        public String getName() {
1820
            return "Constant attribute " + name;
1821
        }
1822
    }
1823

    
1824
    public void setConstantValue(boolean isConstantValue) {
1825
        if (isConstantValue) {
1826
            /* Cuando un attributo tiene asociado un evaluador, este se interpreta
1827
             * como que no debe cargarse de la fuente de datos subyacente, siendo
1828
             * el evaluador el que se encarga de proporcionar su valor.
1829
             * Nos limitamos a asignar un evaluador que retorna simpre el valor
1830
             * por defecto para ese attributo.
1831
             */
1832
            this.evaluator = new ConstantValueEvaluator();
1833
        } else {
1834
            this.evaluator = null;
1835
        }
1836
    }
1837

    
1838
    @Override
1839
    public boolean isComputed() {
1840
        return featureAttributeEmulator != null || evaluator != null || isCalculated();
1841
    }
1842

    
1843
    @Override
1844
    public FeatureStore getStore() {
1845
        FeatureType ftype = this.getFeatureType();
1846
        if (ftype == null) {
1847
            return null;
1848
        }
1849
        return ftype.getStore();
1850
    }
1851

    
1852
    @Override
1853
    public FeatureType getFeatureType() {
1854
        if (this.typeRef == null) {
1855
            return null;
1856
        }
1857
        FeatureType ftype = (FeatureType) this.typeRef.get();
1858
//        LOGGER.info(String.format("FeatureAttributeDescriptor[%08x] get FeatureType [%08x], ref [%08x].", this.hashCode(), ftype.hashCode(), typeRef.hashCode()));
1859
        return ftype;
1860
    }
1861

    
1862
    public FeatureAttributeDescriptor setInterval(Interval interval) {
1863
        this.interval = interval;
1864
        return this;
1865
    }
1866

    
1867
    public void fixAll() {
1868
        if (!this.getDataType().supportSize()) {
1869
            this.size = 0;
1870
        }
1871
        NumberPrecisionAndScale ps = this.getDataType().fixPrecisionAndScale(this.precision, this.scale);
1872
        this.precision = ps.getPrecision();
1873
        this.scale = ps.getScale();
1874

    
1875
        switch (this.getType()) {
1876
            case DataTypes.INSTANT:
1877
            case DataTypes.INTERVAL:
1878
            case DataTypes.DATE:
1879
            case DataTypes.TIME:
1880
            case DataTypes.TIMESTAMP:
1881
                if (this.getInterval() != null) {
1882
                    this.isTime = true;
1883
                }
1884
                break;
1885
        }
1886
    }
1887

    
1888
    @Override
1889
    public String[] getRequiredFieldNames() {
1890
        FeatureAttributeEmulator emulator = this.getFeatureAttributeEmulator();
1891
        if (emulator == null) {
1892
            return null;
1893
        }
1894
        return emulator.getRequiredFieldNames();
1895
    }
1896

    
1897
    @Override
1898
    public void recentUsed() {
1899
        DefaultFeatureType.RECENTS_USEDS.add(this);
1900
    }
1901

    
1902
    @Override
1903
    public boolean hasOnlyMetadataChanges(FeatureAttributeDescriptor other) {
1904
        if (other == null) {
1905
            throw new NullPointerException();
1906
        }
1907
        DefaultFeatureAttributeDescriptor old = (DefaultFeatureAttributeDescriptor) other;
1908
        if (!StringUtils.equalsIgnoreCase(old.name, this.name)) {
1909
            return false;
1910
        }
1911
        if (old.isComputed() && old.isComputed() == this.isComputed()) {
1912
            return true;
1913
        }
1914
        if (this.dataType != old.dataType) {
1915
            return false;
1916
        }
1917
        if (this.size != old.size) {
1918
            return false;
1919
        }
1920
        if (this.precision != old.precision) {
1921
            return false;
1922
        }
1923
//        if( this.primaryKey != old.primaryKey ) {
1924
//            return false;
1925
//        }
1926
        if (this.geomType != old.geomType) {
1927
            return false;
1928
        }
1929
        if (this.SRS != old.SRS) {
1930
            return false;
1931
        }
1932
        if (this.isAutomatic != old.isAutomatic) {
1933
            return false;
1934
        }
1935
        return true;
1936
    }
1937

    
1938
    private class PropertiesBuilder {
1939

    
1940
        private String name;
1941
        private DataType type;
1942
        private Map<String, String> sets;
1943
        private String sep;
1944

    
1945
        public PropertiesBuilder() {
1946
            this.sets = new LinkedHashMap<>();
1947
        }
1948

    
1949
        public void separator(String sep) {
1950
            this.sep = sep;
1951
        }
1952

    
1953
        public void name(String name) {
1954
            this.name = name;
1955
        }
1956

    
1957
        public void type(DataType type) {
1958
            this.type = type;
1959
        }
1960

    
1961
        public void set(String name, ForeingKey fk) {
1962
            if (fk == null) {
1963
                return;
1964
            }
1965
            if (!fk.isForeingKey()) {
1966
                return;
1967
            }
1968
            this.set(name, fk.isForeingKey());
1969
            this.set(name + "_code", fk.getCodeName());
1970
            this.set(name + "_label", fk.getLabelFormula());
1971
            this.set(name + "_closedlist", fk.isClosedList());
1972
            this.set(name + "_table", fk.getTableName());
1973
        }
1974

    
1975
        public void set(String name, FeatureAttributeEmulator value) {
1976
            if (value == null) {
1977
                return;
1978
            }
1979
            if (value instanceof FeatureAttributeEmulatorExpression) {
1980
                this.set(name, ((FeatureAttributeEmulatorExpression) value).getExpression().getPhrase());
1981
            }
1982
        }
1983

    
1984
        public void set(String name, IProjection value) {
1985
            if (value == null) {
1986
                return;
1987
            }
1988
            this.set(name, value.getAbrev());
1989
        }
1990

    
1991
        public void set(String name, GeometryType value) {
1992
            if (value == null) {
1993
                return;
1994
            }
1995
            this.set(name, value.getFullName().replace(":", "@"));
1996
        }
1997

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

    
2009
        public void set(String name, Object value, Object skipValue) {
2010
            if (value == null || value == skipValue) {
2011
                return;
2012
            }
2013
            String s = Objects.toString(value, "");
2014
            if (StringUtils.isBlank(s)) {
2015
                return;
2016
            }
2017
            this.sets.put(name, s);
2018
        }
2019

    
2020
        @Override
2021
        public String toString() {
2022
            StringBuilder builder = new StringBuilder();
2023
            builder.append(this.name);
2024
            builder.append(sep);
2025
            builder.append(this.type.getName());
2026
            for (String key : this.sets.keySet()) {
2027
                builder.append(sep);
2028
                builder.append("set");
2029
                builder.append(sep);
2030
                builder.append(key);
2031
                builder.append("=");
2032
                builder.append(this.sets.get(key));
2033
            }
2034
            return builder.toString();
2035
        }
2036
    }
2037

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

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

    
2194
    public void setSRSForced(IProjection SRS) {
2195
        this.SRS = SRS;
2196
    }
2197

    
2198
    @Override
2199
    public JsonObject toJson() {
2200
        return this.toJsonBuilder().build();
2201
    }
2202

    
2203
    @Override
2204
    public JsonObjectBuilder toJsonBuilder() {
2205
        JsonObjectBuilder builder = Json.createObjectBuilder();
2206
        builder.add_class(this);
2207
        builder.add("name", this.name);
2208
        builder.add("description", this.description);
2209
        builder.add("label", this.label);
2210
        builder.add("shortLabel", this.shortLabel);
2211
        builder.add("order", this.order);
2212
        builder.add("groupName", this.groupName);
2213
        builder.add("dataType", this.dataType);
2214
        builder.add("size", this.size);
2215
        builder.add("precision", this.precision);
2216
        builder.add("scale", this.scale);
2217
        builder.add("roundMode", this.roundMode);
2218

    
2219
        builder.add("allowNull", this.allowNull);
2220
        builder.add("primaryKey", this.primaryKey);
2221
        builder.add("readOnly", this.readOnly);
2222
        builder.add("isAutomatic", this.isAutomatic);
2223
        builder.add("isTime", this.isTime);
2224
        builder.add("indexed", this.indexed);
2225
        builder.add("isIndexAscending", this.isIndexAscending);
2226
        builder.add("allowIndexDuplicateds", this.allowIndexDuplicateds);
2227
        builder.add("hidden", this.hidden);
2228
        builder.add("avoidCachingAvailableValues", this.avoidCachingAvailableValues);
2229

    
2230
        builder.add("geometryType", this.getGeomType());
2231
        builder.add("srs", this.getSRS());
2232

    
2233
        builder.add("relationType", this.relationType);
2234
        builder.add("displaySize", this.displaySize);
2235
        builder.add("locale", this.getLocale());
2236
        builder.add("expression", this.getFeatureAttributeEmulator());
2237
        if (this.isForeingKey()) {
2238
            builder.add("fk", this.isForeingKey());
2239
            builder.add("fk_table", this.getForeingKey().getTableName());
2240
            builder.add("fk_code", this.getForeingKey().getCodeName());
2241
            builder.add("fk_label", this.getForeingKey().getLabelFormula());
2242
            builder.add("fk_closedlist", this.getForeingKey().isClosedList());
2243
        }
2244
        builder.add("availableValuesExpression", this.availableValuesExpression);
2245
        builder.add("defaultValue", Objects.toString(this.defaultValue, null));
2246
        builder.add("dataProfile", this.getDataProfileName());
2247
        builder.add("tags", tags);
2248
        builder.add("availableValues", availableValues);
2249
        builder.add("additionalInfo", this.additionalInfo);
2250
        builder.add("defaultFormat", this.defaultFormat);
2251
        return builder;
2252
    }
2253

    
2254
    public void fromJson(JsonObject json) {
2255
        this.name = json.getString("name");
2256
        this.description = json.getString("description");
2257
        this.label = json.getString("label");
2258
        this.shortLabel = json.getString("shortLabel");
2259
        this.order = json.getInt("order");
2260
        this.groupName = json.getString("groupName");
2261
        this.precision = json.getInt("precision");
2262
        this.size = json.getInt("size");
2263
        this.scale = json.getInt("scale");
2264
        this.roundMode = json.getInt("roundMode");
2265

    
2266
        this.allowNull = json.getBoolean("allowNull");
2267
        this.primaryKey = json.getBoolean("primaryKey");
2268
        this.readOnly = json.getBoolean("readOnly");
2269
        this.isAutomatic = json.getBoolean("isAutomatic");
2270
        this.isTime = json.getBoolean("isTime");
2271
        this.indexed = json.getBoolean("indexed");
2272
        this.isIndexAscending = json.getBoolean("isIndexAscending");
2273
        this.allowIndexDuplicateds = json.getBoolean("allowIndexDuplicateds");
2274
        this.hidden = json.getBoolean("hidden");
2275
        this.avoidCachingAvailableValues = json.getBoolean("avoidCachingAvailableValues");
2276

    
2277
        this.relationType = json.getInt("relationType");
2278
        this.displaySize = json.getInt("displaySize");
2279

    
2280
        this.dataType = (DataType) Json.toObject(json, "dataType");
2281
        this.geomType = (GeometryType) Json.toObject(json, "geometryType");
2282
        this.SRS = (IProjection) Json.toObject(json, "srs");
2283
        this.locale = (Locale) Json.toObject(json, "locale");
2284
        this.featureAttributeEmulator = (FeatureAttributeEmulator) Json.toObject(json, "expression");
2285

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

    
2312
    private static class TheJsonSerializer implements JsonManager.JsonSerializer {
2313

    
2314
        public TheJsonSerializer() {
2315
        }
2316

    
2317
        @Override
2318
        public Class getObjectClass() {
2319
            return DefaultFeatureAttributeDescriptor.class;
2320
        }
2321

    
2322
        @Override
2323
        public Object toObject(JsonObject json) {
2324
            DefaultFeatureAttributeDescriptor o = new DefaultFeatureAttributeDescriptor();
2325
            o.fromJson(json);
2326
            return o;
2327
        }
2328

    
2329
        @Override
2330
        public JsonObjectBuilder toJsonBuilder(Object value) {
2331
            return ((SupportToJson) value).toJsonBuilder();
2332
        }
2333

    
2334
    }
2335

    
2336
    public static void selfRegister() {
2337
        Json.registerSerializer(new TheJsonSerializer());
2338
    }
2339

    
2340
    @Override
2341
    public String getDefaultFormat() {
2342
        return this.defaultFormat;
2343
    }
2344

    
2345
    @Override
2346
    public String format(Object value) {
2347
        try {
2348
            if( StringUtils.isBlank(this.defaultFormat)) {
2349
                if( this.locale==null ) { // !this.hasLocale()
2350
                    return DataTypeUtils.toString(Locale.getDefault(), value, Objects.toString(value, ""));
2351
                } else {
2352
                    return DataTypeUtils.toString(this.locale, value, Objects.toString(value, ""));
2353
                }
2354
            }
2355
            return String.format(this.defaultFormat, value);
2356
        } catch(Exception ex) {
2357
            return Objects.toString(value, "");
2358
        }
2359
    }
2360

    
2361
    
2362
}