1
2
3
4
5
6 package gov.nist.secauto.metaschema.schemagen;
7
8 import gov.nist.secauto.metaschema.core.configuration.IConfiguration;
9 import gov.nist.secauto.metaschema.core.model.IAssemblyDefinition;
10 import gov.nist.secauto.metaschema.core.model.IDefinition;
11 import gov.nist.secauto.metaschema.core.model.IModule;
12 import gov.nist.secauto.metaschema.core.util.ObjectUtils;
13 import gov.nist.secauto.metaschema.schemagen.datatype.IDatatypeManager;
14
15 import java.io.Writer;
16 import java.util.LinkedList;
17 import java.util.List;
18 import java.util.function.BiConsumer;
19
20 import edu.umd.cs.findbugs.annotations.NonNull;
21 import edu.umd.cs.findbugs.annotations.Nullable;
22
23
24
25
26
27
28
29
30
31
32
33
34 public abstract class AbstractSchemaGenerator<
35 T extends AutoCloseable,
36 D extends IDatatypeManager,
37 S extends AbstractGenerationState<
38 T, D>>
39 implements ISchemaGenerator {
40
41
42
43
44
45
46
47
48
49
50 @NonNull
51 protected abstract T newWriter(@NonNull Writer out);
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66 @NonNull
67 protected abstract S newGenerationState(
68 @NonNull IModule module,
69 @NonNull T schemaWriter,
70 @NonNull IConfiguration<SchemaGenerationFeature<?>> configuration);
71
72
73
74
75
76
77
78 protected abstract void generateSchema(@NonNull S generationState);
79
80 @Override
81 public void generateFromModule(
82 IModule metaschema,
83 Writer out,
84 IConfiguration<SchemaGenerationFeature<?>> configuration) {
85 try {
86
87 @SuppressWarnings({ "PMD.CloseResource", "resource" }) T schemaWriter = newWriter(out);
88 S generationState = newGenerationState(metaschema, schemaWriter, configuration);
89 generateSchema(generationState);
90 generationState.flushWriter();
91 } catch (SchemaGenerationException ex) {
92 throw ex;
93 } catch (Exception ex) {
94 throw new SchemaGenerationException(ex);
95 }
96 }
97
98
99
100
101
102
103
104
105
106
107 protected List<IAssemblyDefinition> analyzeDefinitions(
108 @NonNull S generationState,
109 @Nullable BiConsumer<ModuleIndex.DefinitionEntry, IDefinition> handler) {
110
111
112
113
114 List<IAssemblyDefinition> rootAssemblyDefinitions = new LinkedList<>();
115 for (ModuleIndex.DefinitionEntry entry : generationState.getMetaschemaIndex().getDefinitions()) {
116
117 IDefinition definition = ObjectUtils.notNull(entry.getDefinition());
118 if (definition instanceof IAssemblyDefinition && ((IAssemblyDefinition) definition).isRoot()) {
119
120 IAssemblyDefinition assemblyDefinition = (IAssemblyDefinition) definition;
121 rootAssemblyDefinitions.add(assemblyDefinition);
122 }
123
124 boolean referenced = entry.isReferenced();
125 if (!referenced) {
126
127 continue;
128 }
129
130 if (handler != null) {
131 handler.accept(entry, definition);
132 }
133 }
134 return rootAssemblyDefinitions;
135 }
136
137 }