-
Notifications
You must be signed in to change notification settings - Fork 188
/
SchemaRegistryImpl.java
1350 lines (1212 loc) · 46.8 KB
/
SchemaRegistryImpl.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
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 (c) 2010-2015 Evolveum
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.evolveum.midpoint.prism.schema;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.transform.Source;
import javax.xml.validation.SchemaFactory;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.xml.XmlTypeConverter;
import com.evolveum.midpoint.prism.xml.XsdTypeMapper;
import com.evolveum.midpoint.util.QNameUtil;
import com.evolveum.prism.xml.ns._public.types_3.ObjectType;
import com.evolveum.prism.xml.ns._public.types_3.PolyStringType;
import org.apache.commons.lang.StringUtils;
import org.apache.xml.resolver.Catalog;
import org.apache.xml.resolver.CatalogManager;
import org.apache.xml.resolver.tools.CatalogResolver;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.EntityResolver;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.xml.DynamicNamespacePrefixMapper;
import com.evolveum.midpoint.util.ClassPathUtil;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.DebugDumpable;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.JAXBUtil;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
/**
* Registry and resolver of schema files and resources.
*
*
* @author Radovan Semancik
*
*/
public class SchemaRegistryImpl implements DebugDumpable, SchemaRegistry {
private static final QName DEFAULT_XSD_TYPE = DOMUtil.XSD_STRING;
private static final String DEFAULT_RUNTIME_CATALOG_RESOURCE = "META-INF/catalog-runtime.xml";
private File[] catalogFiles; // overrides catalog resource name
private String catalogResourceName = DEFAULT_RUNTIME_CATALOG_RESOURCE;
private javax.xml.validation.SchemaFactory schemaFactory;
private javax.xml.validation.Schema javaxSchema;
private EntityResolver builtinSchemaResolver;
final private List<SchemaDescription> schemaDescriptions = new ArrayList<>();
final private Map<String,SchemaDescription> parsedSchemas = new HashMap<>();
final private Map<QName,ComplexTypeDefinition> extensionSchemas = new HashMap<>();
private boolean initialized = false;
private DynamicNamespacePrefixMapper namespacePrefixMapper;
private String defaultNamespace;
private XmlEntityResolver entityResolver = new XmlEntityResolverImpl(this);
@Autowired // TODO does this work?
private PrismContext prismContext;
private static final Trace LOGGER = TraceManager.getTrace(SchemaRegistry.class);
@Override
public DynamicNamespacePrefixMapper getNamespacePrefixMapper() {
return namespacePrefixMapper;
}
public void setNamespacePrefixMapper(DynamicNamespacePrefixMapper namespacePrefixMapper) {
this.namespacePrefixMapper = namespacePrefixMapper;
}
@Override
public PrismContext getPrismContext() {
return prismContext;
}
public void setPrismContext(PrismContext prismContext) {
this.prismContext = prismContext;
}
public XmlEntityResolver getEntityResolver() {
return entityResolver;
}
public Map<String, SchemaDescription> getParsedSchemas() {
return parsedSchemas;
}
public EntityResolver getBuiltinSchemaResolver() {
return builtinSchemaResolver;
}
public File[] getCatalogFiles() {
return catalogFiles;
}
public void setCatalogFiles(File[] catalogFiles) {
this.catalogFiles = catalogFiles;
}
public String getCatalogResourceName() {
return catalogResourceName;
}
public void setCatalogResourceName(String catalogResourceName) {
this.catalogResourceName = catalogResourceName;
}
@Override
public String getDefaultNamespace() {
return defaultNamespace;
}
public void setDefaultNamespace(String defaultNamespace) {
this.defaultNamespace = defaultNamespace;
}
//region Registering resources and initialization
/**
* Must be called before call to initialize()
*/
public void registerSchemaResource(String resourcePath, String usualPrefix) throws SchemaException {
SchemaDescription desc = SchemaDescription.parseResource(resourcePath);
desc.setUsualPrefix(usualPrefix);
registerSchemaDescription(desc);
}
/**
* Must be called before call to initialize()
*/
public void registerPrismSchemaResource(String resourcePath, String usualPrefix) throws SchemaException {
SchemaDescription desc = SchemaDescription.parseResource(resourcePath);
desc.setUsualPrefix(usualPrefix);
desc.setPrismSchema(true);
registerSchemaDescription(desc);
}
public void registerPrismSchemasFromWsdlResource(String resourcePath, List<Package> compileTimeClassesPackages) throws SchemaException {
List<SchemaDescription> descriptions = SchemaDescription.parseWsdlResource(resourcePath);
Iterator<Package> pkgIterator = null;
if (compileTimeClassesPackages != null) {
if (descriptions.size() != compileTimeClassesPackages.size()) {
throw new SchemaException("Mismatch between the size of compileTimeClassesPackages ("+compileTimeClassesPackages.size()
+" and schemas in "+resourcePath+" ("+descriptions.size()+")");
}
pkgIterator = compileTimeClassesPackages.iterator();
}
for (SchemaDescription desc : descriptions) {
desc.setPrismSchema(true);
if (pkgIterator != null) {
desc.setCompileTimeClassesPackage(pkgIterator.next());
}
registerSchemaDescription(desc);
}
}
/**
* Must be called before call to initialize()
*/
public void registerPrismSchemaResource(String resourcePath, String usualPrefix, Package compileTimeClassesPackage) throws SchemaException {
registerPrismSchemaResource(resourcePath, usualPrefix, compileTimeClassesPackage, false, false);
}
/**
* Must be called before call to initialize()
*/
public void registerPrismSchemaResource(String resourcePath, String usualPrefix, Package compileTimeClassesPackage, boolean prefixDeclaredByDefault) throws SchemaException {
registerPrismSchemaResource(resourcePath, usualPrefix, compileTimeClassesPackage, false, prefixDeclaredByDefault);
}
/**
* Must be called before call to initialize()
*/
public void registerPrismDefaultSchemaResource(String resourcePath, String usualPrefix, Package compileTimeClassesPackage) throws SchemaException {
registerPrismSchemaResource(resourcePath, usualPrefix, compileTimeClassesPackage, true, true);
}
/**
* Must be called before call to initialize()
*
* @param prefixDeclaredByDefault Whether this prefix will be declared in top element in all XML serializations (MID-2198)
*/
public void registerPrismSchemaResource(String resourcePath, String usualPrefix, Package compileTimeClassesPackage,
boolean defaultSchema, boolean prefixDeclaredByDefault) throws SchemaException {
SchemaDescription desc = SchemaDescription.parseResource(resourcePath);
desc.setUsualPrefix(usualPrefix);
desc.setPrismSchema(true);
desc.setDefault(defaultSchema);
desc.setDeclaredByDefault(prefixDeclaredByDefault);
desc.setCompileTimeClassesPackage(compileTimeClassesPackage);
registerSchemaDescription(desc);
}
/**
* Must be called before call to initialize()
* @param node
*/
public void registerSchema(Node node, String sourceDescription) throws SchemaException {
SchemaDescription desc = SchemaDescription.parseNode(node, sourceDescription);
registerSchemaDescription(desc);
}
/**
* Must be called before call to initialize()
* @param node
*/
public void registerSchema(Node node, String sourceDescription, String usualPrefix) throws SchemaException {
SchemaDescription desc = SchemaDescription.parseNode(node, sourceDescription);
desc.setUsualPrefix(usualPrefix);
registerSchemaDescription(desc);
}
public void registerPrismSchemaFile(File file) throws FileNotFoundException, SchemaException {
loadPrismSchemaFileDescription(file);
}
public SchemaDescription loadPrismSchemaFileDescription(File file) throws FileNotFoundException, SchemaException {
if (!(file.getName().matches(".*\\.xsd$"))){
LOGGER.trace("Skipping registering {}, because it is not schema definition.", file.getAbsolutePath());
return null;
}
SchemaDescription desc = SchemaDescription.parseFile(file);
desc.setPrismSchema(true);
registerSchemaDescription(desc);
return desc;
}
private void registerSchemaDescription(SchemaDescription desc) {
if (desc.getUsualPrefix() != null) {
namespacePrefixMapper.registerPrefix(desc.getNamespace(), desc.getUsualPrefix(), desc.isDefault());
if (desc.isDeclaredByDefault()) {
namespacePrefixMapper.addDeclaredByDefault(desc.getUsualPrefix());
}
}
parsedSchemas.put(desc.getNamespace(), desc);
schemaDescriptions.add(desc);
}
public void registerPrismSchemasFromDirectory(File directory) throws FileNotFoundException, SchemaException {
File[] fileArray = directory.listFiles();
if (fileArray != null) {
List<File> files = Arrays.asList(fileArray);
// Sort the filenames so we have deterministic order of loading
// This is useful in tests but may come handy also during customization
Collections.sort(files);
for (File file: files) {
if (file.getName().startsWith(".")) {
// skip dotfiles. this will skip SVN data and similar things
continue;
}
if (file.isDirectory()) {
registerPrismSchemasFromDirectory(file);
}
if (file.isFile()) {
registerPrismSchemaFile(file);
}
}
}
}
/**
* This can be used to read additional schemas even after the registry was initialized.
*/
public void loadPrismSchemasFromDirectory(File directory) throws FileNotFoundException, SchemaException {
List<File> files = Arrays.asList(directory.listFiles());
// Sort the filenames so we have deterministic order of loading
// This is useful in tests but may come handy also during customization
Collections.sort(files);
for (File file: files) {
if (file.getName().startsWith(".")) {
// skip dotfiles. this will skip SVN data and similar things
continue;
}
if (file.isDirectory()) {
loadPrismSchemasFromDirectory(file);
}
if (file.isFile()) {
loadPrismSchemaFile(file);
}
}
}
public void loadPrismSchemaFile(File file) throws FileNotFoundException, SchemaException {
SchemaDescription desc = loadPrismSchemaFileDescription(file);
parsePrismSchema(desc);
}
public void loadPrismSchemaResource(String resourcePath) throws SchemaException {
SchemaDescription desc = SchemaDescription.parseResource(resourcePath);
desc.setPrismSchema(true);
registerSchemaDescription(desc);
parsePrismSchema(desc);
}
/**
* This can be used to read additional schemas even after the registry was initialized.
*/
@Override
public void initialize() throws SAXException, IOException, SchemaException {
if (prismContext == null) {
throw new IllegalStateException("Prism context not set");
}
if (namespacePrefixMapper == null) {
throw new IllegalStateException("Namespace prefix mapper not set");
}
try {
initResolver();
parsePrismSchemas();
parseJavaxSchema();
compileCompileTimeClassList();
initialized = true;
} catch (SAXException ex) {
if (ex instanceof SAXParseException) {
SAXParseException sex = (SAXParseException)ex;
throw new SchemaException("Error parsing schema "+sex.getSystemId()+" line "+sex.getLineNumber()+": "+sex.getMessage(), sex);
}
throw ex;
}
}
private void parseJavaxSchema() throws SAXException, IOException {
schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source[] sources = new Source[schemaDescriptions.size()];
int i = 0;
for (SchemaDescription schemaDescription : schemaDescriptions) {
Source source = schemaDescription.getSource();
sources[i] = source;
i++;
}
schemaFactory.setResourceResolver(entityResolver);
javaxSchema = schemaFactory.newSchema(sources);
}
private void parsePrismSchemas() throws SchemaException {
for (SchemaDescription schemaDescription : schemaDescriptions) {
if (schemaDescription.isPrismSchema()) {
parsePrismSchema(schemaDescription);
}
}
applySchemaExtensions();
}
private void parsePrismSchema(SchemaDescription schemaDescription) throws SchemaException {
String namespace = schemaDescription.getNamespace();
Element domElement = schemaDescription.getDomElement();
boolean isRuntime = schemaDescription.getCompileTimeClassesPackage() == null;
// System.out.println("Parsing schema " + schemaDescription.getNamespace());
LOGGER.trace("Parsing schema {}, namespace: {}, isRuntime: {}",
schemaDescription.getSourceDescription(), namespace, isRuntime);
PrismSchema schema = PrismSchemaImpl.parse(domElement, entityResolver, isRuntime, schemaDescription.getSourceDescription(), getPrismContext());
if (StringUtils.isEmpty(namespace)) {
namespace = schema.getNamespace();
}
LOGGER.trace("Parsed schema {}, namespace: {}, isRuntime: {}",
schemaDescription.getSourceDescription(), namespace, isRuntime);
schemaDescription.setSchema(schema);
detectExtensionSchema(schema);
}
private void detectExtensionSchema(PrismSchema schema) throws SchemaException {
for (ComplexTypeDefinition def: schema.getDefinitions(ComplexTypeDefinition.class)) {
QName extType = def.getExtensionForType();
if (extType != null) {
if (extensionSchemas.containsKey(extType)) {
ComplexTypeDefinition existingExtension = extensionSchemas.get(extType);
existingExtension.merge(def);
// throw new SchemaException("Duplicate definition of extension for type "+extType+": "+def+" and "+extensionSchemas.get(extType));
} else {
extensionSchemas.put(extType, def.clone());
}
}
}
}
private void applySchemaExtensions() throws SchemaException {
for (Entry<QName,ComplexTypeDefinition> entry: extensionSchemas.entrySet()) {
QName typeQName = entry.getKey();
ComplexTypeDefinition extensionCtd = entry.getValue();
ComplexTypeDefinition primaryCtd = findComplexTypeDefinition(typeQName);
PrismContainerDefinition extensionContainer = primaryCtd.findContainerDefinition(
new QName(primaryCtd.getTypeName().getNamespaceURI(), PrismConstants.EXTENSION_LOCAL_NAME));
if (extensionContainer == null) {
throw new SchemaException("Attempt to extend type "+typeQName+" with "+extensionCtd.getTypeClass()+" but the original type does not have extension container");
}
((PrismContainerDefinitionImpl) extensionContainer).setComplexTypeDefinition(extensionCtd.clone());
((PrismContainerDefinitionImpl) extensionContainer).setTypeName(extensionCtd.getTypeName());
}
}
private void compileCompileTimeClassList() {
for (SchemaDescription schemaDescription : schemaDescriptions) {
Package pkg = schemaDescription.getCompileTimeClassesPackage();
if (pkg != null) {
Map<QName, Class<?>> map = createXsdTypeMap(pkg);
schemaDescription.setXsdTypeTocompileTimeClassMap(map);
}
}
}
private void initResolver() throws IOException {
CatalogManager catalogManager = new CatalogManager();
catalogManager.setUseStaticCatalog(true);
catalogManager.setIgnoreMissingProperties(true);
catalogManager.setVerbosity(1);
catalogManager.setPreferPublic(true);
CatalogResolver catalogResolver = new CatalogResolver(catalogManager);
Catalog catalog = catalogResolver.getCatalog();
if (catalogFiles != null && catalogFiles.length > 0) {
for (File catalogFile : catalogFiles) {
LOGGER.trace("Using catalog file {}", catalogFile);
catalog.parseCatalog(catalogFile.getPath());
}
} else if (catalogResourceName != null) {
LOGGER.trace("Using catalog from resource: {}", catalogResourceName);
Enumeration<URL> catalogs = Thread.currentThread().getContextClassLoader().getResources(catalogResourceName);
while (catalogs.hasMoreElements()) {
URL catalogResourceUrl = catalogs.nextElement();
LOGGER.trace("Parsing catalog from URL: {}", catalogResourceUrl);
catalog.parseCatalog(catalogResourceUrl);
}
} else {
throw new IllegalStateException("Catalog is not defined");
}
builtinSchemaResolver = catalogResolver;
}
//endregion
//region Schemas and type maps (TODO)
@Override
public javax.xml.validation.Schema getJavaxSchema() {
return javaxSchema;
}
@Override
public Collection<Package> getCompileTimePackages() {
Collection<Package> compileTimePackages = new ArrayList<Package>(schemaDescriptions.size());
for (SchemaDescription desc : schemaDescriptions) {
if (desc.getCompileTimeClassesPackage() != null) {
compileTimePackages.add(desc.getCompileTimeClassesPackage());
}
}
return compileTimePackages;
}
private Map<QName, Class<?>> createXsdTypeMap(Package pkg) {
Map<QName, Class<?>> map = new HashMap<QName, Class<?>>();
for (Class clazz: ClassPathUtil.listClasses(pkg)) {
QName typeName = JAXBUtil.getTypeQName(clazz);
if (typeName != null) {
map.put(typeName, clazz);
}
}
return map;
}
private SchemaDescription lookupSchemaDescription(String namespace) {
for (SchemaDescription desc : schemaDescriptions) {
if (namespace.equals(desc.getNamespace())) {
return desc;
}
}
return null;
}
//endregion
@Override
public String debugDump() {
return debugDump(0);
}
@Override
public String debugDump(int indent) {
StringBuilder sb = new StringBuilder();
DebugUtil.indentDebugDump(sb, indent);
sb.append("SchemaRegistry:");
sb.append(" Parsed Schemas:");
for (String namespace: parsedSchemas.keySet()) {
sb.append("\n");
DebugUtil.indentDebugDump(sb, indent + 1);
sb.append(namespace);
sb.append(": ");
sb.append(parsedSchemas.get(namespace));
}
return sb.toString();
}
//region applyDefinition(..) methods
@Override
public <C extends Containerable> void applyDefinition(PrismContainer<C> container, Class<C> type) throws SchemaException {
applyDefinition(container, type, true);
}
@Override
public <C extends Containerable> void applyDefinition(PrismContainer<C> container, Class<C> compileTimeClass, boolean force) throws SchemaException {
PrismContainerDefinition<C> definition = determineDefinitionFromClass(compileTimeClass);
container.applyDefinition(definition, force);
}
@Override
public <O extends Objectable> void applyDefinition(ObjectDelta<O> objectDelta, Class<O> compileTimeClass, boolean force) throws SchemaException {
PrismObjectDefinition<O> objectDefinition = determineDefinitionFromClass(compileTimeClass);
objectDelta.applyDefinition(objectDefinition, force);
}
@Override
public <C extends Containerable, O extends Objectable> void applyDefinition(PrismContainerValue<C> prismContainerValue,
Class<O> compileTimeClass, ItemPath path, boolean force) throws SchemaException {
PrismObjectDefinition<O> objectDefinition = determineDefinitionFromClass(compileTimeClass);
PrismContainerDefinition<C> containerDefinition = objectDefinition.findContainerDefinition(path);
prismContainerValue.applyDefinition(containerDefinition, force);
}
@Override
public <C extends Containerable> void applyDefinition(PrismContainerValue<C> prismContainerValue, QName typeName,
ItemPath path, boolean force) throws SchemaException {
PrismObjectDefinition objectDefinition = findObjectDefinitionByType(typeName);
if (objectDefinition != null) {
PrismContainerDefinition<C> containerDefinition = objectDefinition.findContainerDefinition(path);
prismContainerValue.applyDefinition(containerDefinition, force);
return;
}
PrismContainerDefinition typeDefinition = findContainerDefinitionByType(typeName);
if (typeDefinition != null) {
PrismContainerDefinition<C> containerDefinition = typeDefinition.findContainerDefinition(path);
prismContainerValue.applyDefinition(containerDefinition, force);
return;
}
ComplexTypeDefinition complexTypeDefinition = findComplexTypeDefinition(typeName);
if (complexTypeDefinition != null) {
PrismContainerDefinition<C> containerDefinition = complexTypeDefinition.findContainerDefinition(path);
prismContainerValue.applyDefinition(containerDefinition, force);
return;
}
throw new SchemaException("No definition for container "+path+" in type "+typeName);
}
//endregion
private boolean namespaceMatches(String namespace, @Nullable List<String> ignoredNamespaces) {
if (ignoredNamespaces == null) {
return false;
}
for (String ignored : ignoredNamespaces) {
if (namespace.startsWith(ignored)) {
return true;
}
}
return false;
}
//region Finding items (standard cases - core methods)
// @Override
// public <T extends Objectable> PrismObjectDefinition<T> findObjectDefinitionByType(@NotNull QName typeName) {
// if (StringUtils.isEmpty(typeName.getNamespaceURI())) {
// // a quick hack (todo do it seriously)
// ComplexTypeDefinition ctd = resolveGlobalTypeDefinitionWithoutNamespace(typeName.getLocalPart());
// if (ctd == null) {
// return null;
// }
// typeName = ctd.getTypeName();
// }
// PrismSchema schema = findSchemaByNamespace(typeName.getNamespaceURI());
// if (schema == null){
// //TODO: check for confilicted objects
// // Iterator<PrismSchema> schemaIterator = getSchemas().iterator();
// // while (schemaIterator.hasNext()){
// // schema = schemaIterator.next();
// // if (schema == null){
// // continue;
// // }
// // PrismObjectDefinition<T> def = schema.findObjectDefinitionByTypeAssumeNs(typeName);
// // if (def != null){
// // return def;
// // }
// //
// // }
// return null;
// }
// return (PrismObjectDefinition) schema.findObjectDefinitionByType(typeName);
// }
//
// @Override
// public <T extends Objectable> PrismObjectDefinition<T> findObjectDefinitionByElementName(@NotNull QName elementName) {
// if (StringUtils.isEmpty(elementName.getNamespaceURI())) {
// return resolveGlobalItemDefinitionWithoutNamespace(elementName.getLocalPart(), PrismObjectDefinition.class);
// }
// PrismSchema schema = findSchemaByNamespace(elementName.getNamespaceURI());
// if (schema == null) {
// return null;
// }
// return (PrismObjectDefinition) schema.findObjectDefinitionByElementName(elementName);
// }
//
// @Override
// public <C extends Containerable> PrismContainerDefinition<C> findContainerDefinitionByType(QName typeName) {
// if (StringUtils.isEmpty(typeName.getNamespaceURI())) {
// // Maybe not optimal but sufficient way: we resolve complex type definition, and from it we get qualified type name.
// // This is then used to find container definition in the traditional way.
// ComplexTypeDefinition complexTypeDefinition = resolveGlobalTypeDefinitionWithoutNamespace(typeName.getLocalPart());
// if (complexTypeDefinition == null) {
// return null;
// }
// typeName = complexTypeDefinition.getTypeName();
// }
// PrismSchema schema = findSchemaByNamespace(typeName.getNamespaceURI());
// if (schema == null) {
// return null;
// }
// return schema.findContainerDefinitionByType(typeName);
// }
//
// @Override
// public <C extends Containerable> PrismContainerDefinition<C> findContainerDefinitionByElementName(QName elementName) {
// if (StringUtils.isEmpty(elementName.getNamespaceURI())) {
// return resolveGlobalItemDefinitionWithoutNamespace(elementName.getLocalPart(), PrismContainerDefinition.class);
// }
// PrismSchema schema = findSchemaByNamespace(elementName.getNamespaceURI());
// if (schema == null) {
// return null;
// }
// return schema.findContainerDefinitionByElementName(elementName);
// }
//
@NotNull
@Override
public <ID extends ItemDefinition> List<ID> findItemDefinitionsByCompileTimeClass(
@NotNull Class<?> compileTimeClass, @NotNull Class<ID> definitionClass) {
PrismSchema schema = findSchemaByCompileTimeClass(compileTimeClass);
if (schema == null) {
return Collections.emptyList();
}
@SuppressWarnings("unchecked")
List<ID> list = schema.findItemDefinitionsByCompileTimeClass(compileTimeClass, definitionClass);
return list;
}
@Nullable
@Override
public <ID extends ItemDefinition> ID findItemDefinitionByType(@NotNull QName typeName, @NotNull Class<ID> definitionClass) {
if (QNameUtil.noNamespace(typeName)) {
ComplexTypeDefinition ctd = resolveGlobalTypeDefinitionWithoutNamespace(typeName.getLocalPart());
if (ctd == null) {
return null;
}
typeName = ctd.getTypeName();
}
PrismSchema schema = findSchemaByNamespace(typeName.getNamespaceURI());
if (schema == null) {
return null;
}
return schema.findItemDefinitionByType(typeName, definitionClass);
}
@NotNull
@Override
public <ID extends ItemDefinition> List<ID> findItemDefinitionsByElementName(@NotNull QName elementName, @NotNull Class<ID> definitionClass) {
if (QNameUtil.noNamespace(elementName)) {
return resolveGlobalItemDefinitionsWithoutNamespace(elementName.getLocalPart(), definitionClass);
} else {
PrismSchema schema = findSchemaByNamespace(elementName.getNamespaceURI());
if (schema == null) {
return new ArrayList<>();
}
return schema.findItemDefinitionsByElementName(elementName, definitionClass);
}
}
@Nullable
@Override
public <C extends Containerable> ComplexTypeDefinition findComplexTypeDefinitionByCompileTimeClass(@NotNull Class<C> compileTimeClass) {
PrismSchema schema = findSchemaByCompileTimeClass(compileTimeClass);
if (schema == null) {
return null;
}
return schema.findComplexTypeDefinitionByCompileTimeClass(compileTimeClass);
}
@Nullable
@Override
public ComplexTypeDefinition findComplexTypeDefinitionByType(@NotNull QName typeName) {
if (QNameUtil.noNamespace(typeName)) {
return resolveGlobalTypeDefinitionWithoutNamespace(typeName.getLocalPart());
}
PrismSchema schema = findSchemaByNamespace(typeName.getNamespaceURI());
if (schema == null) {
return null;
}
return schema.findComplexTypeDefinitionByType(typeName);
}
//endregion
//region Finding items (nonstandard cases)
@Override
public <T extends ItemDefinition> T findItemDefinitionByFullPath(Class<? extends Objectable> objectClass, Class<T> defClass,
QName... itemNames)
throws SchemaException {
PrismObjectDefinition objectDefinition = findObjectDefinitionByCompileTimeClass(objectClass);
if (objectDefinition == null) {
throw new SchemaException("No object definition for " + objectClass);
}
return (T) objectDefinition.findItemDefinition(new ItemPath(itemNames), defClass);
}
@Override
public ItemDefinition findItemDefinitionByElementName(QName elementName, @Nullable List<String> ignoredNamespaces) {
if (StringUtils.isEmpty(elementName.getNamespaceURI())) {
return resolveGlobalItemDefinitionWithoutNamespace(elementName.getLocalPart(), ItemDefinition.class, true, ignoredNamespaces);
}
PrismSchema schema = findSchemaByNamespace(elementName.getNamespaceURI());
if (schema == null) {
return null;
}
return schema.findItemDefinitionByElementName(elementName, ItemDefinition.class);
}
@Override
public <T> Class<T> determineCompileTimeClass(QName typeName) {
if (QNameUtil.noNamespace(typeName)) {
ComplexTypeDefinition ctd = resolveGlobalTypeDefinitionWithoutNamespace(typeName.getLocalPart());
if (ctd == null) {
return null;
}
return (Class<T>) ctd.getCompileTimeClass();
}
SchemaDescription desc = findSchemaDescriptionByNamespace(typeName.getNamespaceURI());
if (desc == null) {
return null;
}
Package pkg = desc.getCompileTimeClassesPackage();
if (pkg == null) {
return null;
}
return JAXBUtil.findClassForType(typeName, pkg);
}
@NotNull
public <T> Class<T> determineCompileTimeClassNotNull(QName typeName) {
Class<T> clazz = determineCompileTimeClass(typeName);
if (clazz != null) {
return clazz;
} else {
throw new IllegalStateException("No class for " + typeName);
}
}
@Override
public <T> Class<T> getCompileTimeClass(QName xsdType) {
return determineCompileTimeClass(xsdType);
// TODO: which one is better (this one or the above)?
// SchemaDescription desc = findSchemaDescriptionByNamespace(xsdType.getNamespaceURI());
// if (desc == null) {
// return null;
// }
// Map<QName, Class<?>> map = desc.getXsdTypeTocompileTimeClassMap();
// if (map == null) {
// return null;
// }
// return (Class<T>) map.get(xsdType);
}
@Override
public Class<? extends ObjectType> getCompileTimeClassForObjectType(QName objectType) {
PrismObjectDefinition definition = findObjectDefinitionByType(objectType);
if (definition == null) {
return null;
}
return definition.getCompileTimeClass();
}
@Override
public PrismObjectDefinition determineDefinitionFromClass(Class compileTimeClass) {
PrismObjectDefinition def = findObjectDefinitionByCompileTimeClass(compileTimeClass);
if (def != null) {
return def;
}
Class<?> superclass = compileTimeClass.getSuperclass();
if (superclass == null || superclass == Object.class) {
return null;
}
return determineDefinitionFromClass(superclass);
}
@Override
public <T extends Containerable> ItemDefinition locateItemDefinition(@NotNull QName itemName,
@Nullable ComplexTypeDefinition complexTypeDefinition,
@Nullable Function<QName, ItemDefinition> dynamicDefinitionResolver) throws SchemaException {
ItemDefinition def;
if (complexTypeDefinition != null) {
def = complexTypeDefinition.findItemDefinition(itemName);
if (def != null) {
return def;
}
}
if (complexTypeDefinition == null || complexTypeDefinition.isXsdAnyMarker()) {
def = resolveGlobalItemDefinition(itemName, complexTypeDefinition);
if (def != null) {
return def;
}
}
if (dynamicDefinitionResolver != null) {
def = dynamicDefinitionResolver.apply(itemName);
if (def != null) {
return def;
}
}
return null;
}
//endregion
//region Unqualified names resolution
// TODO fix this temporary and inefficient implementation
@Override
public QName resolveUnqualifiedTypeName(QName type) throws SchemaException {
QName typeFound = null;
for (SchemaDescription desc: schemaDescriptions) {
QName typeInSchema = new QName(desc.getNamespace(), type.getLocalPart());
if (desc.getSchema() != null && desc.getSchema().findComplexTypeDefinition(typeInSchema) != null) {
if (typeFound != null) {
throw new SchemaException("Ambiguous type name: " + type);
} else {
typeFound = typeInSchema;
}
}
}
if (typeFound == null) {
throw new SchemaException("Unknown type: " + type);
} else {
return typeFound;
}
}
@Override
public QName qualifyTypeName(QName typeName) throws SchemaException {
if (typeName == null || !QNameUtil.isUnqualified(typeName)) {
return typeName;
}
return resolveUnqualifiedTypeName(typeName);
}
// current implementation tries to find all references to the child CTD and select those that are able to resolve path of 'rest'
// fails on ambiguity
// it's a bit fragile, as adding new references to child CTD in future may break existing code
@Override
public ComplexTypeDefinition determineParentDefinition(@NotNull ComplexTypeDefinition child, @NotNull ItemPath rest) {
ComplexTypeDefinition parent = null;
for (PrismSchema schema : getSchemas()) {
if (schema == null) {
continue;
}
for (ComplexTypeDefinition ctd : schema.getComplexTypeDefinitions()) {
for (ItemDefinition item : ctd.getDefinitions()) {
if (item instanceof PrismContainerDefinition) {
PrismContainerDefinition<?> itemPcd = (PrismContainerDefinition<?>) item;
if (itemPcd.getComplexTypeDefinition() != null) {
if (child.getTypeName().equals(itemPcd.getComplexTypeDefinition().getTypeName())) {
if (!rest.isEmpty() && ctd.findItemDefinition(rest) == null) {
continue;
}
if (parent != null && !parent.getTypeClass().equals(ctd.getTypeName())) {
throw new IllegalStateException("Couldn't find parent definition for " + child.getTypeName() + ": More than one candidate found: "
+ parent.getTypeName() + ", " + itemPcd.getTypeName());
}
parent = ctd;
}
}
}
}
}
}
// ComplexTypeDefinition def = findComplexTypeDefinition(new QName(
// "http://midpoint.evolveum.com/xml/ns/public/common/common-3",
// "ObjectType")); // FIXME BRUTAL HACK
if (parent == null) {
throw new IllegalStateException("Couldn't find definition for parent for " + child.getTypeName() + ", path=" + rest);
}
return parent;
}
@Override
public PrismObjectDefinition determineReferencedObjectDefinition(QName targetTypeName, ItemPath rest) {
// TEMPORARY HACK -- TODO FIXME
PrismObjectDefinition def = findObjectDefinitionByType(targetTypeName);
if (def == null) {
throw new IllegalStateException("Couldn't find definition for referenced object for " + targetTypeName + ", path=" + rest);
}
return def;
}
private ComplexTypeDefinition resolveGlobalTypeDefinitionWithoutNamespace(String typeLocalName) {
ComplexTypeDefinition found = null;
for (SchemaDescription schemaDescription : parsedSchemas.values()) {
PrismSchema schema = schemaDescription.getSchema();
if (schema == null) { // is this possible?
continue;
}
ComplexTypeDefinition def = schema.findComplexTypeDefinition(new QName(schema.getNamespace(), typeLocalName));
if (def != null) {
if (found != null) {
// TODO change to SchemaException
throw new IllegalArgumentException("Multiple possible resolutions for unqualified type name " + typeLocalName + " (e.g. in " +
def.getTypeName() + " and " + found.getTypeName());
}
found = def;
}
}
return found;
}
/**
* Looks for a top-level definition for the specified element name (in all schemas).
*/
@Override
public ItemDefinition resolveGlobalItemDefinition(QName elementQName) throws SchemaException {
return resolveGlobalItemDefinition(elementQName, (ComplexTypeDefinition) null);
}
@Override
public ItemDefinition resolveGlobalItemDefinition(QName elementQName, PrismContainerDefinition<?> containerDefinition) throws SchemaException {
return resolveGlobalItemDefinition(elementQName, containerDefinition != null ? containerDefinition.getComplexTypeDefinition() : null);
}
@Override
public ItemDefinition resolveGlobalItemDefinition(QName itemName, @Nullable ComplexTypeDefinition complexTypeDefinition) throws SchemaException {
if (QNameUtil.noNamespace(itemName)) {
if (complexTypeDefinition != null && complexTypeDefinition.getDefaultNamespace() != null) {
itemName = new QName(complexTypeDefinition.getDefaultNamespace(), itemName.getLocalPart());
}
else {
List<String> ignoredNamespaces = complexTypeDefinition != null ?
complexTypeDefinition.getIgnoredNamespaces() :
null;
return resolveGlobalItemDefinitionWithoutNamespace(itemName.getLocalPart(), ItemDefinition.class, true, ignoredNamespaces);
}
}
PrismSchema schema = findSchemaByNamespace(itemName.getNamespaceURI());
if (schema == null) {
return null;
}
return schema.findItemDefinitionByElementName(itemName, ItemDefinition.class);