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" })
88 T schemaWriter = newWriter(out);
89 S generationState = newGenerationState(metaschema, schemaWriter, configuration);
90 generateSchema(generationState);
91 generationState.flushWriter();
92 } catch (SchemaGenerationException ex) {
93 throw ex;
94 } catch (Exception ex) {
95 throw new SchemaGenerationException(ex);
96 }
97 }
98
99
100
101
102
103
104
105
106
107
108 protected List<IAssemblyDefinition> analyzeDefinitions(
109 @NonNull S generationState,
110 @Nullable BiConsumer<ModuleIndex.DefinitionEntry, IDefinition> handler) {
111
112
113
114
115 List<IAssemblyDefinition> rootAssemblyDefinitions = new LinkedList<>();
116 for (ModuleIndex.DefinitionEntry entry : generationState.getMetaschemaIndex().getDefinitions()) {
117
118 IDefinition definition = ObjectUtils.notNull(entry.getDefinition());
119 if (definition instanceof IAssemblyDefinition && ((IAssemblyDefinition) definition).isRoot()) {
120
121 IAssemblyDefinition assemblyDefinition = (IAssemblyDefinition) definition;
122 rootAssemblyDefinitions.add(assemblyDefinition);
123 }
124
125 boolean referenced = entry.isReferenced();
126 if (!referenced) {
127
128 continue;
129 }
130
131 if (handler != null) {
132 handler.accept(entry, definition);
133 }
134 }
135 return rootAssemblyDefinitions;
136 }
137
138 }