-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMetaData.java
More file actions
1624 lines (1387 loc) · 57.7 KB
/
Copy pathMetaData.java
File metadata and controls
1624 lines (1387 loc) · 57.7 KB
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
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2003 Doug Mealing LLC dba Meta Objects. All Rights Reserved.
*
* This software is the proprietary information of Doug Mealing LLC dba Meta Objects.
* Use is subject to license terms.
*/
package com.metaobjects;
import com.metaobjects.attr.MetaAttribute;
import com.metaobjects.field.MetaField;
// ✅ MIGRATED: MetaKey import removed - using MetaRelationship instead
import com.metaobjects.object.MetaObject;
import com.metaobjects.validator.MetaValidator;
import com.metaobjects.view.MetaView;
import com.metaobjects.loader.MetaDataLoader;
// Using unified registry instead
import com.metaobjects.registry.MetaDataRegistry;
import com.metaobjects.constraint.ConstraintEnforcer;
import com.metaobjects.constraint.PlacementConstraint;
import com.metaobjects.cache.CacheStrategy;
import com.metaobjects.cache.HybridCache;
import com.metaobjects.collections.IndexedMetaDataCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Stream;
/**
* MetaData represents the core metadata definition in the MetaObjects framework.
*
* <p>MetaData follows a <strong>READ-OPTIMIZED WITH CONTROLLED MUTABILITY</strong> design pattern
* analogous to Java's Class/Field reflection system with dynamic class loading. MetaData objects
* are loaded once during application startup and optimized for heavy read access throughout
* the application lifetime.</p>
*
* <strong>Architecture Pattern:</strong>
* <ul>
* <li><strong>Load Once</strong>: Like ClassLoader, expensive startup for permanent benefit</li>
* <li><strong>Read Many</strong>: Optimized for thousands of concurrent read operations</li>
* <li><strong>Thread Safe</strong>: Immutable after loading, no synchronization needed for reads</li>
* <li><strong>OSGI Ready</strong>: WeakHashMap and service patterns handle dynamic class loading</li>
* <li><strong>Memory Efficient</strong>: Smart caching balances performance with memory cleanup</li>
* </ul>
*
* <strong>Usage Examples:</strong>
* <pre>{@code
* // Loading Phase - Happens once at startup
* MetaDataLoader loader = new SimpleLoader("myLoader");
* loader.setSourceURIs(Arrays.asList(URI.create("metadata.json")));
* loader.init(); // Loads ALL metadata into permanent memory structures
*
* // Runtime Phase - All operations are READ-ONLY
* MetaObject userMeta = loader.getMetaObjectByName("User"); // O(1) lookup
* MetaField field = userMeta.getMetaField("email"); // Cached access
* }</pre>
*
* <strong>Performance Characteristics:</strong>
* <ul>
* <li><strong>Loading Phase</strong>: 100ms-1s (acceptable one-time cost)</li>
* <li><strong>Runtime Reads</strong>: 1-10μs (cached, immutable access)</li>
* <li><strong>Memory Overhead</strong>: 10-50MB (permanent metadata residence)</li>
* <li><strong>Concurrent Readers</strong>: Unlimited (no lock contention)</li>
* </ul>
*
* @author Doug Mealing
* @version 6.0.0
* @since 1.0
* @see MetaDataLoader
* @see com.metaobjects.object.MetaObject
* @see com.metaobjects.field.MetaField
*/
public class MetaData implements Cloneable, Serializable {
private static final Logger log = LoggerFactory.getLogger(MetaData.class);
// Type-safe class constants for common usage
public static final Class<MetaData> METADATA_CLASS = MetaData.class;
// === SEPARATORS ===
public final static String PKG_SEPARATOR = "::";
public final static String SEPARATOR = PKG_SEPARATOR;
// === UNIVERSAL ATTRIBUTE NAMES (apply to all MetaData) ===
/** Universal attribute for abstract metadata marker */
public static final String ATTR_IS_ABSTRACT = "isAbstract";
/** Standard attribute name for 'name' */
public static final String ATTR_NAME = "name";
/** Standard attribute name for 'type' */
public static final String ATTR_TYPE = "type";
/** Standard attribute name for 'subType' */
public static final String ATTR_SUBTYPE = "subType";
/** Standard attribute name for 'package' */
public static final String ATTR_PACKAGE = "package";
/** Standard attribute name for 'children' */
public static final String ATTR_CHILDREN = "children";
/** Standard attribute name for 'metadata' (root element) */
public static final String ATTR_METADATA = "metadata";
// === VALIDATION PATTERNS ===
/** Valid name pattern for MetaData identifiers */
public static final String VALID_NAME_PATTERN = "^[a-zA-Z][a-zA-Z0-9_]*$";
// === ROOT TYPE CONSTANTS ===
/** Root metadata type constant - MetaData owns this concept */
public static final String TYPE_METADATA = "metadata";
/** Root metadata subtype for metadata file structure */
public static final String SUBTYPE_BASE = "base";
// Unified registry self-registration for root metadata type
/**
* Register MetaData as metadata.base with abstract requirements constraints.
* This creates metadata.base which defines metadata file structure and enforces
* that most metadata types must be abstract under the root (except objects).
*
* @param registry The MetaDataRegistry to register with
*/
public static void registerTypes(MetaDataRegistry registry) {
try {
MetaDataRegistry.getInstance().registerType(MetaData.class, def -> def
.type(TYPE_METADATA).subType(SUBTYPE_BASE)
.description("Base metadata type for inheritance hierarchy - enforces abstract requirements")
// ROOT LEVEL can contain top-level metadata types
.optionalChild("object", "*", "*") // Any object type
.optionalChild("field", "*", "*") // Any field type (if abstract)
.optionalChild("attr", "*", "*") // Any attribute (if abstract)
.optionalChild("validator", "*", "*") // Any validator (if abstract)
.optionalChild("view", "*", "*") // Any view (if abstract)
.optionalChild("key", "*", "*") // Any key (if abstract)
);
log.debug("Registered root MetaData type (metadata.base) with unified registry");
// Setup abstract requirements constraints
setupRootAbstractConstraints();
} catch (Exception e) {
log.error("Failed to register root MetaData type with unified registry", e);
}
}
/**
* Setup abstract requirements constraints for metadata.base children.
* Future defaults: new metadata types must be abstract under metadata.base.
*/
private static void setupRootAbstractConstraints() {
MetaDataRegistry registry = MetaDataRegistry.getInstance();
// Check if constraints are already registered to prevent duplicates during Maven plugin execution
if (registry.hasConstraint("metadata.base.objects")) {
log.debug("Root abstract constraints already registered, skipping");
return;
}
// OBJECTS can be abstract or concrete under metadata.base
registry.addConstraint(PlacementConstraint.allowChildType(
"metadata.base.objects",
"metadata.base can contain objects",
TYPE_METADATA, SUBTYPE_BASE, // Parent: metadata.base
MetaObject.TYPE_OBJECT, "*" // Child: object.*
));
// FIELDS under metadata.base
registry.addConstraint(PlacementConstraint.allowChildType(
"metadata.base.fields",
"metadata.base can contain fields",
TYPE_METADATA, SUBTYPE_BASE, // Parent: metadata.base
MetaField.TYPE_FIELD, "*" // Child: field.*
));
// ATTRIBUTES under metadata.base
registry.addConstraint(new PlacementConstraint(
"metadata.base.attributes",
"metadata.base can contain attributes",
TYPE_METADATA, SUBTYPE_BASE, // Parent: metadata.base
MetaAttribute.TYPE_ATTR, "*", // Child: attr.*
null, // No name constraint
true // Allowed
));
// VALIDATORS under metadata.base
registry.addConstraint(new PlacementConstraint(
"metadata.base.validators",
"metadata.base can contain validators",
TYPE_METADATA, SUBTYPE_BASE, // Parent: metadata.base
MetaValidator.TYPE_VALIDATOR, "*", // Child: validator.*
null, // No name constraint
true // Allowed
));
// VIEWS under metadata.base
registry.addConstraint(new PlacementConstraint(
"metadata.base.views",
"metadata.base can contain views",
TYPE_METADATA, SUBTYPE_BASE, // Parent: metadata.base
MetaView.TYPE_VIEW, "*", // Child: view.*
null, // No name constraint
true // Allowed
));
// ✅ MIGRATED: MetaKey constraint removed - keys are now handled via:
// - MetaIdentity children (for primary and secondary keys)
// - MetaRelationship children (for foreign key relationships)
// FUTURE DEFAULT: Any new metadata types must be abstract under metadata.base
// (Individual new types can override this by adding their own constraints)
log.debug("Set up abstract requirements constraints for metadata.base");
}
/**
* Alternative registerTypes() method with no parameters for backward compatibility.
*/
public static void registerTypes() {
registerTypes(MetaDataRegistry.getInstance());
}
// Static registration block - automatically registers the root metadata type when class is loaded
static {
try {
registerTypes(MetaDataRegistry.getInstance());
} catch (Exception e) {
log.error("Failed to register root MetaData type during class loading", e);
}
}
// Unified caching strategy
private final CacheStrategy cache = new HybridCache();
// Indexed collection for O(1) child lookups
private final IndexedMetaDataCollection children = new IndexedMetaDataCollection();
// NEW v6.0: Type/subtype as first-class concept
private final MetaDataTypeId typeId;
// LEGACY: Keep for backward compatibility during transition
private final String type;
private final String subType;
private final String name;
private final String shortName;
private final String pkg;
// Type system integration
private MetaData superData = null;
// WeakReference prevents circular references and memory leaks in parent-child relationships
private WeakReference<MetaData> parentRef = null;
private MetaDataLoader loader = null;
private ClassLoader metaDataClassLoader=null;
/**
* Constructs a MetaData object with enhanced type system integration.
*
* <p>This constructor creates a new MetaData instance that will be optimized for
* read-heavy access patterns throughout its lifetime. The metadata is designed to
* be loaded once during application startup and accessed frequently at runtime.</p>
*
* <p><strong>Architecture Note:</strong> This is a loading-phase operation. After construction
* and initialization, the MetaData object becomes effectively immutable for optimal
* concurrent read performance.</p>
*
* @param type the type identifier for this metadata (e.g., "object", "field", "loader")
* @param subType the subtype identifier providing more specific categorization
* (e.g., "string", "integer", "mapped", "proxy")
* @param name the fully qualified name of this metadata, may include package separators (::)
* for hierarchical organization (e.g., "com::example::User", "email")
*
* @see MetaDataTypeId
* @see #getType()
* @see #getSubType()
* @see #getName()
* @since 1.0
*/
public MetaData(String type, String subType, String name ) {
// Allow null values for testing - validation happens in validate() method
// if ( type == null ) throw new NullPointerException( "MetaData Type cannot be null" );
// if ( subType == null ) throw new NullPointerException( "MetaData SubType cannot be null" );
// if ( name == null ) throw new NullPointerException( "MetaData Name cannot be null" );
// NEW v6.0: Create MetaDataTypeId (allows nulls for testing)
this.typeId = (type != null && subType != null) ?
new MetaDataTypeId(type, subType) : null;
// LEGACY: Keep for backward compatibility during transition
this.type = type;
this.subType = subType;
this.name = name;
// v6.0.0: Validate name during construction
if (name != null && type != null) {
validateName(name);
}
// Type definition removed - using unified registry
// Cache the shortName and packageName (handle null name)
if (name != null) {
int i = name.lastIndexOf(PKG_SEPARATOR);
if (i >= 0) {
shortName = name.substring(i + PKG_SEPARATOR.length());
pkg = name.substring(0, i);
} else {
shortName = name;
pkg = "";
}
} else {
shortName = null;
pkg = null;
}
log.debug("Created MetaData: {}:{}:{}",
type != null ? type : "null",
subType != null ? subType : "null",
name != null ? name : "null");
}
// ========== ENHANCED TYPE SYSTEM METHODS ==========
// Type definition methods removed - using unified registry with static self-registration
/**
* Validate MetaData name during construction
*/
private void validateName(String name) {
// Loaders and views can have more flexible naming (allow hyphens)
if ("loader".equals(type) || "view".equals(type)) {
// Allow hyphens for loaders and views
if (!name.matches("^[a-zA-Z][a-zA-Z0-9_-]*$")) {
throw new IllegalArgumentException(
"Invalid " + type + " name '" + name + "': must follow pattern ^[a-zA-Z][a-zA-Z0-9_-]*$");
}
} else {
// Check if this is a package-qualified name
if (name.contains("::")) {
// Package-qualified name - validate each part separately
String[] parts = name.split("::");
for (String part : parts) {
if (!part.matches("^[a-zA-Z][a-zA-Z0-9_]*$")) {
throw new IllegalArgumentException(
"Constraint violation: Invalid MetaData name part '" + part + "' in '" + name + "': must follow identifier pattern ^[a-zA-Z][a-zA-Z0-9_]*$");
}
}
} else {
// Simple name - strict identifier pattern for fields and objects
if (!name.matches("^[a-zA-Z][a-zA-Z0-9_]*$")) {
throw new IllegalArgumentException(
"Constraint violation: Invalid MetaData name '" + name + "': must follow identifier pattern ^[a-zA-Z][a-zA-Z0-9_]*$");
}
}
}
}
// ========== MODERN COLLECTION APIS ==========
/**
* Get children as a Stream for functional operations
*/
public Stream<MetaData> getChildrenStream() {
return children.stream();
}
/**
* Find children matching a predicate
*/
public Stream<MetaData> findChildren(Predicate<MetaData> predicate) {
return children.findMatching(predicate);
}
/**
* Find children of a specific type
*/
public <T extends MetaData> Stream<T> findChildren(Class<T> type) {
return children.findByClass(type).stream();
}
/**
* Find child by name (modern Optional-based API) - O(1) operation
*/
public Optional<MetaData> findChild(String name) {
return children.findByName(name);
}
/**
* Find child by name and type - O(1) operation
*/
public <T extends MetaData> Optional<T> findChild(String name, Class<T> type) {
return children.findByName(name)
.filter(type::isInstance)
.map(type::cast);
}
/**
* Require child by name (throws if not found)
*/
public MetaData requireChild(String name) {
return findChild(name)
.orElseThrow(() -> new MetaDataNotFoundException("Child not found: " + name, name));
}
/**
* Require child by name and type
*/
public <T extends MetaData> T requireChild(String name, Class<T> type) {
return findChild(name, type)
.orElseThrow(() -> new MetaDataNotFoundException(
"Child of type " + type.getSimpleName() + " not found: " + name, name));
}
// ========== UNIFIED CACHING ==========
/**
* Get cached value with type safety
*/
public <T> Optional<T> getCacheValue(String key, Class<T> type) {
return cache.get(key, type);
}
/**
* Set cache value
*/
public void setCacheValue(String key, Object value) {
cache.put(key, value);
}
/**
* Compute cache value if absent
*/
public <T> T computeCacheValue(String key, Class<T> type, java.util.function.Supplier<T> supplier) {
return cache.computeIfAbsent(key, type, supplier);
}
/**
* Check if cache contains key
*/
public boolean hasCacheValue(String key) {
return cache.containsKey(key);
}
/**
* Remove cached value
*/
public Object removeCacheValue(String key) {
return cache.remove(key);
}
/**
* Get cache statistics
*/
public Optional<Object> getCacheStats() {
return cache.getStats().map(stats -> (Object) stats);
}
// ========== ENHANCED ATTRIBUTE MANAGEMENT ==========
/**
* Modern attribute access with Optional
*/
public Optional<MetaAttribute> findAttribute(String name) {
return findChild(name, MetaAttribute.class);
}
/**
* Require attribute (throws if not found)
*/
public MetaAttribute requireAttribute(String name) {
return findAttribute(name)
.orElseThrow(() -> MetaDataNotFoundException.forAttribute(name, this));
}
/**
* Get all attributes as stream
*/
public Stream<MetaAttribute> getAttributesStream() {
return findChildren(MetaAttribute.class);
}
/**
* Check if attribute exists (enhanced version)
*/
public boolean hasAttributeEnhanced(String name) {
return findAttribute(name).isPresent();
}
/**
* Checks whether this MetaData is of the specified type.
*
* <p>This is a high-performance comparison method optimized for frequent
* type checking during runtime operations.</p>
*
* @param type the type to check against
* @return true if this MetaData has the specified type, false otherwise
* @throws NullPointerException if type parameter is null
* @since 1.0
*/
public boolean isType( String type ) {
return this.type.equals( type );
}
// ========== NEW v6.0 TYPE SYSTEM METHODS ==========
/**
* Get the type of this MetaData (modern API)
*
* @return The primary type (e.g., "field", "view", "validator")
* @since 6.0.0
*/
public String getType() {
return typeId != null ? typeId.type() : type;
}
/**
* Get the subtype of this MetaData (modern API)
*
* @return The specific implementation subtype (e.g., "int", "string", "currency")
* @since 6.0.0
*/
public String getSubType() {
return typeId != null ? typeId.subType() : subType;
}
/**
* Get the type ID of this MetaData (modern API)
*
* @return MetaDataTypeId containing both type and subtype
* @since 6.0.0
*/
public MetaDataTypeId getTypeId() {
return typeId;
}
/**
* Check if this MetaData matches a type pattern
*
* @param pattern Pattern like "field.*" or "field.int" where "*" means any
* @return true if this MetaData matches the pattern
* @since 6.0.0
*/
public boolean matchesType(String pattern) {
return typeId != null && typeId.matches(pattern);
}
/**
* Check if this MetaData matches a type pattern
*
* @param pattern MetaDataTypeId pattern (type or subtype can be "*")
* @return true if this MetaData matches the pattern
* @since 6.0.0
*/
public boolean matchesType(MetaDataTypeId pattern) {
return typeId != null && typeId.matches(pattern);
}
/**
* Returns whether this MetaData matches specified Type, SubType, and Name
*/
public boolean isSameType( MetaData md ) {
return isType( md.type );
}
/**
* Returns whether MetaData is of the specified Type
*/
public boolean isTypeSubType( String type, String subType ) {
return this.type.equals( type ) && this.subType.equals( subType );
}
/**
* Returns whether this MetaData matches specified Type, SubType, and Name
*/
public boolean isSameTypeSubType( MetaData md ) {
return isTypeSubType( md.type, md.subType );
}
/**
* Returns the fully qualified name of this MetaData.
*
* <p>The name may include package separators (::) for hierarchical organization.
* For example: "com::example::User" for an object, or "email" for a simple field.</p>
*
* <p><strong>Performance Note:</strong> This is a cached O(1) operation optimized for
* frequent access during runtime read operations.</p>
*
* @return the fully qualified name, may contain package separators, or null if not set
* @see #getShortName()
* @see #getPackage()
* @see #PKG_SEPARATOR
* @since 1.0
*/
public String getName() {
return name;
}
/**
* Returns whether this MetaData matches specified Type, SubType, and Name
*/
public boolean isTypeSubTypeName( String type, String subType, String name ) {
return this.type.equals( type ) && this.subType.equals( subType ) && this.name.equals( name );
}
/**
* Returns whether this MetaData matches specified Type, SubType, and Name
* @param md the metadata to compare against
* @return true if this metadata has the same type, subtype, and name as the specified metadata
*/
public boolean isSameTypeSubTypeName( MetaData md ) {
return isTypeSubTypeName( md.type, md.subType, md.name);
}
/////////////////////////////////////////////////////
// Object Instantiation Helpers
/**
* Sets the ClassLoader to use for metadata class loading
* @param <T> the type of metadata to return
* @param classLoader the ClassLoader to set for metadata operations
* @return this metadata instance cast to the specified type
*/
@SuppressWarnings("unchecked")
public <T extends MetaData> T setMetaDataClassLoader( ClassLoader classLoader ) {
metaDataClassLoader = classLoader;
return (T) this;
}
protected ClassLoader getDefaultMetaDataClassLoader() {
return getClass().getClassLoader();
}
public ClassLoader getMetaDataClassLoader() {
if (metaDataClassLoader != null) {
return metaDataClassLoader;
}
else if (!(this instanceof MetaDataLoader)) {
if ( getLoader() != null ) {
return getLoader().getMetaDataClassLoader();
}
}
return getDefaultMetaDataClassLoader();
}
// Loads the specified Class using the proper ClassLoader
@SuppressWarnings("unchecked")
public <T> Class<T> loadClass( Class<T> clazz, String name ) throws ClassNotFoundException {
try {
Class<?> c = getMetaDataClassLoader().loadClass(name);
if (!clazz.isAssignableFrom(c)) {
throw new InvalidValueException("Class [" + c.getName() + "] is not assignable from [" + clazz.getName() + "]");
}
return (Class<T>) c;
}
catch (ClassNotFoundException e ) {
log.error( "Could not find class ["+name+"] in MetaDataClassLoader: "+getMetaDataClassLoader());
throw e;
}
}
// Loads the specified Class using the proper ClassLoader
public Class<?> loadClass( String name ) throws ClassNotFoundException {
return loadClass(name, true);
}
// Loads the specified Class using the proper ClassLoader
public Class<?> loadClass( String name, boolean throwError ) throws ClassNotFoundException {
try {
return getMetaDataClassLoader().loadClass(name);
}
catch (ClassNotFoundException e ) {
if ( throwError ) {
log.error("Could not find class [" + name + "] in MetaDataClassLoader: " + getMetaDataClassLoader());
throw e;
}
}
return null;
}
////////////////////////////////////////////////////
// SETTER / GETTER METHODS
/**
* Type-safe utility methods for common type checks
* @return true if this metadata is a field type, false otherwise
*/
public boolean isFieldMetaData() {
return this instanceof com.metaobjects.field.MetaField;
}
public boolean isObjectMetaData() {
return this instanceof com.metaobjects.object.MetaObject;
}
public boolean isAttributeMetaData() {
return this instanceof com.metaobjects.attr.MetaAttribute;
}
public boolean isValidatorMetaData() {
return this instanceof com.metaobjects.validator.MetaValidator;
}
public boolean isViewMetaData() {
return this instanceof com.metaobjects.view.MetaView;
}
public boolean isLoaderMetaData() {
return this instanceof com.metaobjects.loader.MetaDataLoader;
}
/**
* Iterates up the Super Data until it finds the MetaDataLoader
* @return the MetaDataLoader that contains this metadata, or null if none found
*/
public MetaDataLoader getLoader() {
if (loader == null) {
synchronized (this) {
MetaData d = this;
while (d != null) {
if (d instanceof MetaDataLoader) {
loader = (MetaDataLoader) d;
break;
}
d = d.getParent();
}
}
}
return loader;
}
/**
* Retrieve the MetaObject package
* @return the package name of this metadata, or null if not set
*/
public String getPackage() {
return pkg;
}
/**
* Retrieve the MetaObject short name
* @return the short name of this metadata without package prefix
*/
public String getShortName() {
return shortName;
}
/**
* Sets the parent of the attribute
* @param parent the parent metadata to attach to this metadata
*/
protected void attachParent(MetaData parent) {
parentRef = new WeakReference<>(parent);
}
/**
* Gets the parent MetaData. Be careful as this might not be the
* same as the metadata you retrieved this from as a child due to
* inheritance. Use with care!
* @return the parent metadata, or null if no parent is set
*/
public MetaData getParent() {
if (parentRef == null) {
return null;
}
return parentRef.get();
}
/**
* Sets the Super Data
* @param superData the super metadata to set
*/
public void setSuperData(MetaData superData) {
this.superData = superData;
}
/**
* Gets the Super Data
* @param <T> the type of metadata to return
* @return the super metadata cast to the specified type
*/
@SuppressWarnings("unchecked")
public <T extends MetaData> T getSuperData() {
return (T) superData;
}
/**
* Gets the Super Data with type safety - returns Optional to avoid ClassCastException
* @param <T> the type of metadata to return
* @param type The expected type of the super data
* @return Optional containing the super data if it matches the expected type
*/
public <T extends MetaData> Optional<T> getSuperDataSafe(Class<T> type) {
return type.isInstance(superData) ? Optional.of(type.cast(superData)) : Optional.empty();
}
/**
* Returns whether this MetaData has a Super MetaData
* @return SuperData exists
*/
public boolean hasSuperData() {
return superData != null;
}
////////////////////////////////////////////////////
// ATTRIBUTE METHODS
/**
* Sets an attribute of the MetaClass
* @param attr the attribute to add to this metadata
*/
public void addMetaAttr(MetaAttribute attr) {
addChild(attr);
}
/**
* Sets an attribute of the MetaClass (type-safe version)
* @param attr The attribute to add
*/
public void addMetaAttrSafe(MetaAttribute attr) {
addChild(attr);
}
/**
* Retrieves an attribute value of the MetaData
* @param name the name of the attribute to retrieve
* @return the MetaAttribute with the specified name
* @throws MetaDataNotFoundException if the attribute is not found
*/
public MetaAttribute getMetaAttr(String name) throws MetaDataNotFoundException {
return getMetaAttr(name,true);
}
/**
* Retrieves an attribute value of the MetaData
* @param name the name of the attribute to retrieve
* @param includeParentData whether to search parent metadata for the attribute
* @return the MetaAttribute with the specified name
* @throws MetaDataNotFoundException if the attribute is not found
*/
public MetaAttribute getMetaAttr(String name, boolean includeParentData) throws MetaDataNotFoundException {
try {
return (MetaAttribute) getChild( name, MetaAttribute.class, includeParentData);
} catch (MetaDataNotFoundException e) {
throw MetaDataNotFoundException.forAttribute(name, this);
}
}
/**
* Checks if this metadata has an attribute with the specified name
* @param name the name of the attribute to check
* @return true if the attribute exists, false otherwise
*/
public boolean hasMetaAttr(String name) {
return hasMetaAttr(name,true);
}
/**
* Checks if this metadata has an attribute with the specified name
* @param name the name of the attribute to check
* @param includeParentData true to include parent data in the search, false to search only this metadata
* @return true if the attribute exists, false otherwise
*/
public boolean hasMetaAttr(String name, boolean includeParentData) {
try {
if (getChild(name, MetaAttribute.class, includeParentData, false) != null) {
return true;
}
} catch (MetaDataNotFoundException ignored) {}
return false;
}
/**
* Retrieves all attributes for this metadata
* @return list of all MetaAttribute objects, including parent data
*/
public List<MetaAttribute> getMetaAttrs() {
return getMetaAttrs(true);
}
/**
* Retrieves all attributes for this metadata
* @param includeParentData true to include attributes from parent data, false for only this metadata
* @return list of MetaAttribute objects based on the includeParentData flag
*/
public List<MetaAttribute> getMetaAttrs( boolean includeParentData ) {
return getChildren(MetaAttribute.class, includeParentData);
}
/////////////////////////////////////////////////////////////////////////////
// CHILDREN METHODS
/**
* Filters for parent data
* @param d the metadata to filter
* @return true if this metadata should be filtered when accessing parent data
*/
protected boolean filterWhenParentData( MetaData d ) {
return ( d instanceof MetaAttribute && d.getName().startsWith("_") );
}
/**
* Determines if this MetaData instance should be deleted when a new one with the same name is added.
* Subclasses can override this to control replacement behavior.
*
* @return true if this instance should be replaced, false to keep existing
*/
protected boolean shouldDeleteOnAdd() {
return false; // Most MetaData types retain existing instances by default
}
/**
* Whether to delete the MetaData if a new one is added (delegates to polymorphic method)
* @param d MetaData to check
* @return true if should delete
*/
protected boolean deleteOnAdd( MetaData d) {
return d.shouldDeleteOnAdd();
}
/**
* Whether the child data exists
* @param type the type of child to check for
* @param name the name of the child to check for
* @return true if a child of the specified type and name exists, false otherwise
*/
protected boolean hasChildOfType(String type, String name) {
try {
getChildOfType( type, name );
return true;
} catch (MetaDataNotFoundException e) {
return false;
}
}
/**
* Whether the child data exists
* @param name the name of the child to check for
* @param c the class type of the child to check for
* @return true if a child with the specified name and type exists, false otherwise
*/
public boolean hasChild(String name, Class<? extends MetaData> c) {
try {
getChild(name, c);
return true;
} catch (MetaDataNotFoundException e) {
return false;
}
}
/**
* Adds a child MetaData object of the specified class type. If no class
* type is set, then a child of the same type is not checked against.
* @param data the child metadata to add
*/
public void addChild(MetaData data) throws InvalidMetaDataException {
addChild(data, true);
}
/**
* Adds a child MetaData object (type-safe version)
* @param data The child MetaData to add
*/
public void addChildSafe(MetaData data) throws InvalidMetaDataException {
addChild(data, true);
}
/**
* Check whether this MetaData is a valid Child to add
* @param data MetaData to add as a Child
*/
protected void checkValidChild( MetaData data ) {
if (data == null) {