-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathProperty.java
929 lines (840 loc) · 33.4 KB
/
Property.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
/*
* Made with all the love in the world
* by scireum in Remshalden, Germany
*
* Copyright by scireum GmbH
* http://www.scireum.de - [email protected]
*/
package sirius.db.mixing;
import sirius.db.es.Elastic;
import sirius.db.jdbc.OMA;
import sirius.db.mixing.annotations.DefaultValue;
import sirius.db.mixing.annotations.Length;
import sirius.db.mixing.annotations.NullAllowed;
import sirius.db.mixing.annotations.Unique;
import sirius.db.mixing.annotations.ValidatedBy;
import sirius.db.mongo.Mango;
import sirius.kernel.commons.Strings;
import sirius.kernel.commons.Value;
import sirius.kernel.commons.Values;
import sirius.kernel.di.GlobalContext;
import sirius.kernel.di.std.Part;
import sirius.kernel.di.transformers.Composable;
import sirius.kernel.health.Exceptions;
import sirius.kernel.health.HandledException;
import sirius.kernel.nls.NLS;
import javax.annotation.Nonnull;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
/**
* Maps a field, which is either defined in an entity, a composite or a mixin to a mapped property.
* <p>
* A property is responsible for mapping (converting) a value between a field ({@link Field} and a database column.
* It is also responsible for checking the consistency of this field.
*/
public abstract class Property extends Composable {
@Part
private static GlobalContext globalContext;
/**
* Contains the effective property name. If the field, for which this property was created, resides
* inside a mixin or composite, the name will be prefixed appropriately. Names are separated by
* {@link Mapping#SUBFIELD_SEPARATOR} which is a <tt>_</tt>.
*/
protected String name;
/**
* Contains the effective property name. This is normally the same as {@link #name} but can be re-written
* to support legacy table and column names.
*/
protected String propertyName;
/**
* Represents the name of the property a {@link Mapping}
*/
protected Mapping nameAsMapping;
/**
* Contains the i18n key used to determine the label (official name) of the property.
* <p>
* This is built like <tt>SimpleClassNameDefiningTheField.fieldName</tt>
*
* @see #getLabel()
*/
protected String propertyKey;
/**
* Contains a class local i18n key used to determine the label (official name) of the property.
* <p>
* This is built like <tt>EntityTypeName.compositeOrMixinField_fieldName</tt>
* <p>
* This can be used to provide different labels for the same field of a composite based on
* the class where the composite is included.
*
* @see #getLabel()
*/
protected String localPropertyKey;
/**
* Contains a class local i18n key used to determine the fullLabel of the property.
* <p>
* The fullLabel is the label which is used in error messages.
* <p>
* If this property resides in a composite or mixin, this parent property key is filled
* and will be used build a full name.
*/
protected String parentPropertyKey;
/**
* Contains the alternative i18n key used to determine the label (official name) of the property.
* <p>
* This is built like <tt>Model.fieldName</tt>.
*
* @see #getLabel()
*/
protected String alternativePropertyKey;
/**
* Contains the descriptor to which this property belongs
*/
protected EntityDescriptor descriptor;
/**
* Contains the access path used to obtain the target object containing the field
*/
protected AccessPath accessPath;
/**
* The field which generated the property (which stores the column value in the Java world)
*/
protected Field field;
/**
* Contains the default value of this property
* <p>
* For the string representation that can be used in JDBC statements see {@link #getColumnDefaultValue()}
*/
protected Value defaultValue = Value.EMPTY;
/**
* Contains the length of this property
*/
protected int length = 0;
/**
* Determines the nullability of the property
*/
protected boolean nullable;
protected PropertyValidator propertyValidator;
/**
* Determines if the {@link #propertyValidator} should be also executed when the value has not changed.
* <p>
* This is only relevant when a validator was specified via {@link ValidatedBy}.
*/
protected boolean strictValidation = true;
/**
* Creates a new property for the given descriptor, access path and field.
*
* @param descriptor the descriptor which owns the property
* @param accessPath the access path required to obtain the target object which contains the field
* @param field the field which stores the database value
*/
protected Property(@Nonnull EntityDescriptor descriptor, @Nonnull AccessPath accessPath, @Nonnull Field field) {
this.descriptor = descriptor;
this.accessPath = accessPath;
this.field = field;
this.propertyKey = EntityDescriptor.determineTranslationSource(field.getDeclaringClass()).getSimpleName()
+ "."
+ field.getName();
this.alternativePropertyKey = "Model." + field.getName();
this.field.setAccessible(true);
this.name = accessPath.qualify(field.getName());
if (Strings.isFilled(accessPath.prefix())) {
this.localPropertyKey = descriptor.getTranslationSource().getSimpleName() + "." + name;
this.parentPropertyKey = descriptor.getTranslationSource().getSimpleName() + "." + accessPath.prefix();
}
this.propertyName = descriptor.rewritePropertyName(name);
this.nameAsMapping = Mapping.named(name);
determineNullability();
determineLengths();
determineDefaultValue();
determinePropertyValidator();
}
/**
* Determines the default value of the property by checking for a {@link DefaultValue} annotation on the field, or its initial value.
*/
protected void determineDefaultValue() {
DefaultValue defaultValueAnnotation = field.getAnnotation(DefaultValue.class);
if (defaultValueAnnotation != null) {
this.defaultValue = Value.of(transformValueFromImport(Value.of(defaultValueAnnotation.value())));
} else {
Object initialValue = getValue(getDescriptor().getReferenceInstance());
if (!isConsideredNull(initialValue)) {
this.defaultValue = Value.of(initialValue);
}
}
}
/**
* Determines the column length by checking for a {@link Length} annotation on the field.
*/
protected void determineLengths() {
Length lengthAnnotation = field.getAnnotation(Length.class);
if (lengthAnnotation != null) {
this.length = lengthAnnotation.value();
}
}
/**
* Determines the nullability of the column by checking for a {@link NullAllowed} annotation on the field.
* <p>
* Note that subclasses might overwrite this value if they do not accept null values (like properties
* for primitive types).
*/
protected void determineNullability() {
this.nullable = !field.getType().isPrimitive() && checkNullabilityAnnotation();
}
/**
* Determines the property validator by checking for a {@link PropertyValidator} annotation on the field.
*/
protected void determinePropertyValidator() {
if (field.isAnnotationPresent(ValidatedBy.class)) {
PropertyValidator validator = globalContext.getPartByType(PropertyValidator.class,
field.getAnnotation(ValidatedBy.class).value());
if (validator == null) {
Mixing.LOG.WARN("Cannot find validator: %s for field: %s in class: %s",
field.getAnnotation(ValidatedBy.class).value(),
field.getName(),
field.getDeclaringClass().getName());
} else {
this.strictValidation = field.getAnnotation(ValidatedBy.class).strictValidation();
this.propertyValidator = validator;
}
}
}
private boolean checkNullabilityAnnotation() {
if (Arrays.stream(field.getDeclaredAnnotations())
.map(Annotation::annotationType)
.map(Class::getSimpleName)
.anyMatch("Nullable"::equals)) {
Mixing.LOG.WARN(
"A @Nullable annotation was detected on field %s of entity %s. This is most likely a mistake. Please use @NullAllowed instead.",
field.getName(),
field.getDeclaringClass().getName());
// We warn about this, but we still accept it, because the intent of the annotation usage is clear.
return true;
}
return field.isAnnotationPresent(NullAllowed.class);
}
/**
* Returns the annotation of the given type.
*
* @param type the type of the annotation to fetch
* @param <A> the annotation to fetch
* @return the annotation as optional or <tt>null</tt>, if the field defining the property doesn't wear an
* annotation of the given type
*/
public <A extends Annotation> Optional<A> getAnnotation(Class<A> type) {
return Optional.ofNullable(field.getAnnotation(type));
}
/**
* Determines if an annotation of the given type is present.
*
* @param type the type of the annotation to fetch
* @return <tt>true</tt> if an annotation of the given type is present, <tt>false</tt> otherwise
*/
public boolean isAnnotationPresent(Class<? extends Annotation> type) {
return field.isAnnotationPresent(type);
}
/**
* Returns the name of the property.
*
* @return the name of the property.
*/
public String getName() {
return name;
}
/**
* Returns the effective property name.
*
* @return the name of the property in the database
*/
public String getPropertyName() {
return propertyName;
}
/**
* Returns the field which will store the database value.
*
* @return the field in the target object which stores the database value
*/
@Nonnull
public Field getField() {
return field;
}
/**
* Executes the underlying access path to obtain the object out of the entity which actually contains the field.
* <p>
* This object might differ from the entity itself for composites and mixins.
*
* @param entity the entity to read the target object from
* @return the target object which actually contains the property
*/
public Object getTarget(Object entity) {
return accessPath.apply(entity);
}
/**
* Returns the name of the key used to determine the label of the property.
* <p>
* The label can be set in three ways:
* <ol>
* <li>
* Define a local i18n value for <tt>localPropertyKey</tt>, which is normally <tt>[entityClass].[compositeName]_[field]</tt>.
* So for <tt>com.acme.model.Address.street</tt> in <tt>com.acme.model.Customer</tt> this would be
* <tt>Customer.address_street</tt>. This can be used to give the same composite field different
* names of a per-entity basis.
* </li>
* <li>
* Define an i18n value for <tt>propertyKey</tt>, which is normally <tt>[declaringClass].[field]</tt>.
* So for <tt>com.acme.model.Address.street</tt> this would be <tt>Address.street</tt>
* </li>
* <li>
* Define an i18n value for <tt>alternativePropertyKey</tt>, which is normally <tt>Model.[field]</tt>.
* So for <tt>com.acme.model.Address.street</tt> this would be <tt>Model.street</tt>. That
* way, common names across different entities can share the same translation.
* </li>
* </ol>
*
* @return the key used to determine the label of the property
*/
public String getLabelKey() {
String currentLanguage = NLS.getCurrentLanguage();
if (NLS.exists(localPropertyKey, currentLanguage)) {
return localPropertyKey;
}
if (NLS.exists(propertyKey, currentLanguage)) {
return propertyKey;
}
if (NLS.exists(alternativePropertyKey, currentLanguage)) {
return alternativePropertyKey;
}
return propertyKey;
}
/**
* Returns the name of the property which is shown to the user.
* <p>
* This method relies on {@link #getLabelKey()}. See the documentation there for how the label is determined.
*
* @return the effective label of the property
* @see #getLabelKey()
* @see #getFullLabel()
*/
public String getLabel() {
return NLS.get(getLabelKey());
}
/**
* Returns the full label or name of the property which is shown in error messages etc.
* <p>
* This will only differ from {@link #getLabel()} for field in composites or mixins. In this case,
* we try to look up the "parent" name (<tt>[entityClass].[compositeName]</tt>), that is the access path leading
* to this field. If a property is available for this and none is present for the fully qualified name
* (<tt>[entityClass].[compositeName]_[field]</tt>), a label in the form of <tt>getLabel() (NLS.get(parent))</tt>
* is shown.
*
* @return the effective full label for the property
* @see #getLabel()
*/
public String getFullLabel() {
String currentLanguage = NLS.getCurrentLanguage();
String result = NLS.getIfExists(localPropertyKey, currentLanguage).orElse(null);
if (Strings.isFilled(result)) {
return result;
}
if (Strings.isFilled(parentPropertyKey)) {
String parentLabel = NLS.getIfExists(parentPropertyKey, currentLanguage).orElse(null);
if (Strings.isFilled(parentLabel)) {
return Strings.apply("%s (%s)", getLabel(), parentLabel);
}
}
return getLabel();
}
/**
* Returns the class name and field name which "defined" this property.
* <p>
* This is mainly used to report errors for duplicate names etc.
*
* @return the "qualified" field name which "defined" this property
*/
protected String getDefinition() {
return field.getDeclaringClass().getName() + "." + field.getName();
}
/**
* Applies the given value to the given entity.
* <p>
* The internal access path will be used to find the target object which contains the field.
* <p>
* Note that no further value conversion will be performed, therefore the given object must match the expected value.
* Use {@link #parseValue(Object, Value)} to utilize automatic transformations.
*
* @param entity the entity to write to
* @param object the value to write to the field
*/
public void setValue(Object entity, Object object) {
Object target = accessPath.apply(entity);
setValueToField(object, target);
}
/**
* Applies the given value to the field in the given target object
*
* @param value the database value to store
* @param target the target object determined by the access path
*/
protected void setValueToField(Object value, Object target) {
try {
field.set(target, value);
} catch (IllegalAccessException | IllegalArgumentException e) {
throw Exceptions.handle()
.to(Mixing.LOG)
.error(e)
.withSystemErrorMessage("Cannot write property '%s' (from '%s'): %s (%s)",
getName(),
getDefinition())
.handle();
}
}
/**
* Applies the given database value to the given entity.
* <p>
* The internal access path will be used to find the target object which contains the field.
* <p>
* If the underlying field of this property is primitive, but the given value is <tt>null</tt> or transformed to
* <tt>null</tt>, this will be ignored. A scenario like this might happen, if we join-fetch a value, which is not
* present.
*
* @param mapperType the mapper which is currently active. This can be used to determine which kind of database is
* active and therefore which data format will be available.
* @param entity the entity to write to
* @param data the database value to store
*/
protected void setValueFromDatasource(Class<? extends BaseMapper<?, ?, ?>> mapperType, Object entity, Value data) {
Object effectiveValue = transformFromDatasource(mapperType, data);
if (field.getType().isPrimitive() && effectiveValue == null) {
return;
}
setValue(entity, effectiveValue);
}
/**
* Converts the database value to the appropriate field value.
*
* @param mapperType the mapper which is currently active. This can be used to determine which kind of database is
* active and therefore which data format will be available.
* @param object the database value
* @return the value which can be stored in the associated field
*/
public Object transformFromDatasource(Class<? extends BaseMapper<?, ?, ?>> mapperType, Value object) {
if (mapperType == OMA.class) {
return transformFromJDBC(object);
} else if (mapperType == Elastic.class) {
return transformFromElastic(object);
} else if (mapperType == Mango.class) {
return transformFromMongo(object);
} else {
throw new UnsupportedOperationException(getClass().getName()
+ " does not yet support: "
+ mapperType.getName());
}
}
/**
* Loads a value from a JDBC datasource.
*
* @param object the database value
* @return the value which can be stored in the associated field
*/
protected Object transformFromJDBC(Value object) {
throw new UnsupportedOperationException(getClass().getName() + " does not yet support JDBC!");
}
/**
* Loads a value from an Elasticsearch database.
*
* @param object the database value
* @return the value which can be stored in the associated field
*/
protected Object transformFromElastic(Value object) {
throw new UnsupportedOperationException(getClass().getName() + " does not yet support Elastic!");
}
/**
* Loads a value from a MongoDB datasource.
*
* @param object the database value
* @return the value which can be stored in the associated field
*/
protected Object transformFromMongo(Value object) {
throw new UnsupportedOperationException(getClass().getName() + " does not yet support MongoDB!");
}
/**
* Obtains the field value from the given entity.
* <p>
* The internal access path will be used to find the target object which contains the field.
*
* @param entity the entity to fetch the value from
* @return the value which is currently stored in the field
*/
public Object getValue(Object entity) {
Object target = accessPath.apply(entity);
return getValueFromField(target);
}
/**
* Obtains a translated value to be included into error messages.
*
* @param entity the entity to extract the value from
* @return the extracted and translated value to include in messages shown to the user
*/
public String getValueForUserMessage(Object entity) {
return NLS.toUserString(getValue(entity));
}
/**
* For modifiable datatypes like collections, this returns the value as copy so that further modifications
* will not change the returned value.
*
* @param entity the entity to fetch the value from
* @return the as copy of the value which is currently stored in the field
*/
public Object getValueAsCopy(Object entity) {
return getValue(entity);
}
/**
* Obtains the value from the field in the given target object
*
* @param target the target object determined by the access path
* @return the object to be stored in the database
*/
protected Object getValueFromField(Object target) {
try {
return field.get(target);
} catch (IllegalAccessException e) {
throw Exceptions.handle()
.to(Mixing.LOG)
.error(e)
.withSystemErrorMessage("Cannot read property '%s' (from '%s'): %s (%s)",
getName(),
getDefinition())
.handle();
}
}
/**
* Obtains the database value from the given entity.
* <p>
* The internal access path will be used to find the target object which contains the field.
*
* @param mapperType the mapper which is currently active. This can be used to determine which kind of database is
* active and therefore which data format will be required.
* @param entity the entity to write to
* @return the database value to store in the db
*/
public Object getValueForDatasource(Class<? extends BaseMapper<?, ?, ?>> mapperType, Object entity) {
return transformToDatasource(mapperType, getValue(entity));
}
/**
* Converts the Java object which resides in the associated field to the database value which is to be
* written into the database.
*
* @param mapperType the mapper which is currently active. This can be used to determine which kind of database is
* active and therefore which data format will be required.
* @param object the current field value
* @return the value which is to be written to the database
*/
protected Object transformToDatasource(Class<? extends BaseMapper<?, ?, ?>> mapperType, Object object) {
if (mapperType == OMA.class) {
return transformToJDBC(object);
} else if (mapperType == Elastic.class) {
return transformToElastic(object);
} else if (mapperType == Mango.class) {
return transformToMongo(object);
} else {
throw new UnsupportedOperationException(getClass().getName()
+ " does not yet support: "
+ mapperType.getName());
}
}
/**
* Generates a value for a JDBC datasource.
*
* @param object the database value
* @return the value which can be stored in the associated field
*/
protected Object transformToJDBC(Object object) {
throw new UnsupportedOperationException(getClass().getName() + " does not yet support JDBC!");
}
/**
* Generates a value for an Elasticsearch database.
*
* @param object the database value
* @return the value which can be stored in the associated field
*/
protected Object transformToElastic(Object object) {
throw new UnsupportedOperationException(getClass().getName() + " does not yet support Elastic!");
}
/**
* Generates a value for a MongoDB datasource.
*
* @param object the database value
* @return the value which can be stored in the associated field
*/
protected Object transformToMongo(Object object) {
throw new UnsupportedOperationException(getClass().getName() + " does not yet support MongoDB!");
}
/**
* Parses the given value and applies it to the given entity if possible.
*
* @param e the entity to receive the parsed value
* @param value the value to parse and apply
*/
public void parseValue(Object e, Value value) {
try {
setValue(e, transformValue(value));
} catch (IllegalArgumentException exception) {
throw Exceptions.createHandled()
.error(new InvalidFieldException(getName()))
.withNLSKey("Property.parseValueErrorMessage")
.set("message", exception.getMessage())
.error(exception)
.handle();
}
}
/**
* Parses the given values and applies it to the given entity if possible.
*
* @param e the entity to receive the parsed value
* @param values the values to parse and apply
*/
public void parseValues(Object e, Values values) {
parseValue(e, values.at(0));
}
/**
* Converts the given value, which most probably contains user input as string into the target type of this
* property.
*
* @param value the value to convert
* @return the converted value
*/
public abstract Object transformValue(Value value);
/**
* Parses the given value read from an import and applies it to the given entity if possible.
* <p>
* In contrast to {@link #parseValue(Object, Value)} which is intended for user input, this method should
* be used to process data from an import (e.g. an Excel import).
*
* @param e the entity to receive the parsed value
* @param value the value to parse and apply
*/
public void parseValueFromImport(Object e, Value value) {
try {
setValue(e, transformValueFromImport(value));
} catch (IllegalArgumentException exception) {
throw Exceptions.createHandled()
.error(new InvalidFieldException(getName()))
.withNLSKey("Property.parseValueErrorMessage")
.set("message", exception.getMessage())
.error(exception)
.handle();
}
}
/**
* Converts the given value, which is read from an import (e.g. an Excel import) into the target type of this
* property.
* <p>
* By default, this will use the logic provided by {@link #transformValue(Value)} but can be overwritten by
* properties.
*
* @param value the value to convert
* @return the converted value
*/
protected Object transformValueFromImport(Value value) {
return transformValue(value);
}
/**
* Creates an exception which represents an illegal value for this property
*
* @param value the illegal value itself
* @return an exception filled with an appropriate message
*/
public HandledException illegalFieldValue(Value value) {
return Exceptions.createHandled()
.error(new InvalidFieldException(getName()))
.withNLSKey("Property.illegalValue")
.set("property", getFullLabel())
.set("value", NLS.toUserString(value.get()))
.handle();
}
/**
* Returns the entity descriptor to which this property belongs
*
* @return the descriptor which owns this property
*/
public EntityDescriptor getDescriptor() {
return descriptor;
}
/**
* Invoked before an entity is written to the database.
* <p>
* Checks the nullability and uniqueness of the property.
*
* @param entity the entity to check
*/
protected final void onBeforeSave(Object entity) {
onBeforeSaveChecks(entity);
Object propertyValue = getValue(entity);
checkNullability(propertyValue);
boolean valueChanged = entity instanceof BaseEntity<?> && (((BaseEntity<?>) entity).isNew()
|| ((BaseEntity<?>) entity).isChanged(nameAsMapping));
if (propertyValidator != null && (strictValidation || valueChanged)) {
// Only enforce validity if the value actually changed or in strict validation mode
propertyValidator.beforeSave(this, getValue(entity));
}
checkUniqueness(entity, propertyValue);
}
/**
* Invoked during validation of an entity.
* <p>
* This method is intended to be overwritten with custom logic.
*
* @param entity the entity to check
* @param validationConsumer the consumer collecting the validation messages
*/
protected void onValidate(Object entity, Consumer<String> validationConsumer) {
if (propertyValidator != null) {
propertyValidator.validate(this, getValue(entity), validationConsumer);
}
}
/**
* Invoked before an entity is written to the database.
* <p>
* This method is intended to be overwritten with custom logic.
*
* @param entity the entity to check
*/
protected void onBeforeSaveChecks(Object entity) {
// this method does nothing by default
}
/**
* Checks if the value is non-null or the property accepts null values.
*
* @param propertyValue the value to check
*/
protected void checkNullability(Object propertyValue) {
if (!isNullable() && isConsideredNull(propertyValue)) {
throw Exceptions.createHandled()
.error(new InvalidFieldException(getName()))
.withNLSKey("Property.fieldNotNullable")
.set("field", getFullLabel())
.handle();
}
}
/**
* Determines if the given value is considered to be <tt>null</tt>.
*
* @param propertyValue the value to check
*/
protected boolean isConsideredNull(Object propertyValue) {
return propertyValue == null;
}
/**
* Checks the uniqueness of the given value and entity if an {@link Unique} annotation is present
*
* @param entity the entity to check
* @param propertyValue the value to check
*/
protected void checkUniqueness(Object entity, Object propertyValue) {
Unique unique = field.getAnnotation(Unique.class);
if (unique == null) {
return;
}
if (!unique.includingNull() && propertyValue == null) {
return;
}
if (!(entity instanceof BaseEntity<?> baseEntity)) {
throw new IllegalArgumentException("Only subclasses of BaseEntity can have unique fields!");
}
List<Mapping> withinColumns = Arrays.stream(unique.within()).map(Mapping::named).toList();
List<Mapping> changedWithinColumns = withinColumns.stream().filter(baseEntity::isChanged).toList();
// Only enforce uniqueness if the value has changed or if any of the within column values have changed
if (baseEntity.isChanged(nameAsMapping) || !changedWithinColumns.isEmpty()) {
baseEntity.assertUnique(nameAsMapping, propertyValue, withinColumns.toArray(Mapping[]::new));
}
}
/**
* Invoked after an entity was written to the database
*
* @param entity the entity which was written to the database
*/
protected void onAfterSave(Object entity) {
}
/**
* Invoked before an entity is deleted from the database
*
* @param entity the entity to be deleted
*/
protected void onBeforeDelete(Object entity) {
}
/**
* Invoked after an entity was deleted from the database
*
* @param entity the entity which was deleted
*/
protected void onAfterDelete(Object entity) {
}
/**
* Links this property.
* <p>
* This is invoked once all <tt>EntityDescriptors</tt> are loaded and can be used to build references to
* other descriptors / properties.
*/
protected void link() {
}
/**
* Determines if this property accepts null values
*
* @return <tt>true</tt> if this property accepts null values, <tt>false</tt> otherwise
*/
public boolean isNullable() {
return nullable;
}
/**
* Returns the length of the generated column.
*
* @return the length of the column or 0 if the associated column has no length
*/
public int getLength() {
return length;
}
/**
* Returns the default value to use.
*
* @return the default value of this property
*/
public Value getDefaultValue() {
return defaultValue;
}
/**
* Returns the default value to use as String to be used as column default value.
*
* @return the default value to use as column default
*/
public String getColumnDefaultValue() {
if (defaultValue.isNull()) {
return null;
}
Object defaultData = transformToDatasource(OMA.class, defaultValue.get());
return defaultData == null ? null : NLS.toMachineString(defaultData);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (!(obj instanceof Property)) {
return false;
}
return descriptor.equals(((Property) obj).descriptor) && Strings.areEqual(name, ((Property) obj).name);
}
@Override
public int hashCode() {
return Objects.hash(descriptor, name);
}
@Override
public String toString() {
return name + " [" + getClass().getSimpleName() + "/" + getDefinition() + "]";
}
}