View Javadoc
1   /*
2    * Portions of this software was developed by employees of the National Institute
3    * of Standards and Technology (NIST), an agency of the Federal Government and is
4    * being made available as a public service. Pursuant to title 17 United States
5    * Code Section 105, works of NIST employees are not subject to copyright
6    * protection in the United States. This software may be subject to foreign
7    * copyright. Permission in the United States and in foreign countries, to the
8    * extent that NIST may hold copyright, to use, copy, modify, create derivative
9    * works, and distribute this software and its documentation without fee is hereby
10   * granted on a non-exclusive basis, provided that this notice and disclaimer
11   * of warranty appears in all copies.
12   *
13   * THE SOFTWARE IS PROVIDED 'AS IS' WITHOUT ANY WARRANTY OF ANY KIND, EITHER
14   * EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY
15   * THAT THE SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF
16   * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND FREEDOM FROM
17   * INFRINGEMENT, AND ANY WARRANTY THAT THE DOCUMENTATION WILL CONFORM TO THE
18   * SOFTWARE, OR ANY WARRANTY THAT THE SOFTWARE WILL BE ERROR FREE.  IN NO EVENT
19   * SHALL NIST BE LIABLE FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO, DIRECT,
20   * INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES, ARISING OUT OF, RESULTING FROM,
21   * OR IN ANY WAY CONNECTED WITH THIS SOFTWARE, WHETHER OR NOT BASED UPON WARRANTY,
22   * CONTRACT, TORT, OR OTHERWISE, WHETHER OR NOT INJURY WAS SUSTAINED BY PERSONS OR
23   * PROPERTY OR OTHERWISE, AND WHETHER OR NOT LOSS WAS SUSTAINED FROM, OR AROSE OUT
24   * OF THE RESULTS OF, OR USE OF, THE SOFTWARE OR SERVICES PROVIDED HEREUNDER.
25   */
26  
27  package gov.nist.secauto.metaschema.schemagen.json;
28  
29  import com.fasterxml.jackson.core.JsonFactory;
30  import com.fasterxml.jackson.core.JsonGenerator;
31  import com.fasterxml.jackson.core.JsonGenerator.Feature;
32  import com.fasterxml.jackson.databind.ObjectMapper;
33  import com.fasterxml.jackson.databind.node.JsonNodeFactory;
34  import com.fasterxml.jackson.databind.node.ObjectNode;
35  
36  import gov.nist.secauto.metaschema.core.configuration.IConfiguration;
37  import gov.nist.secauto.metaschema.core.model.IAssemblyDefinition;
38  import gov.nist.secauto.metaschema.core.model.IModule;
39  import gov.nist.secauto.metaschema.core.util.ObjectUtils;
40  import gov.nist.secauto.metaschema.schemagen.AbstractSchemaGenerator;
41  import gov.nist.secauto.metaschema.schemagen.SchemaGenerationException;
42  import gov.nist.secauto.metaschema.schemagen.SchemaGenerationFeature;
43  import gov.nist.secauto.metaschema.schemagen.json.datatype.JsonDatatypeManager;
44  import gov.nist.secauto.metaschema.schemagen.json.impl.JsonGenerationState;
45  
46  import java.io.IOException;
47  import java.io.Writer;
48  import java.util.LinkedHashMap;
49  import java.util.List;
50  import java.util.Map;
51  import java.util.stream.Collectors;
52  
53  import edu.umd.cs.findbugs.annotations.NonNull;
54  
55  public class JsonSchemaGenerator
56      extends AbstractSchemaGenerator<JsonGenerator, JsonDatatypeManager, JsonGenerationState> {
57    @NonNull
58    private final JsonFactory jsonFactory;
59  
60    public JsonSchemaGenerator() {
61      this(new JsonFactory());
62    }
63  
64    public JsonSchemaGenerator(@NonNull JsonFactory jsonFactory) {
65      this.jsonFactory = jsonFactory;
66    }
67  
68    @NonNull
69    public JsonFactory getJsonFactory() {
70      return jsonFactory;
71    }
72  
73    @SuppressWarnings("resource")
74    @Override
75    protected JsonGenerator newWriter(Writer out) {
76      try {
77        return ObjectUtils.notNull(getJsonFactory().createGenerator(out)
78            .setCodec(new ObjectMapper())
79            .useDefaultPrettyPrinter()
80            .disable(Feature.AUTO_CLOSE_TARGET));
81      } catch (IOException ex) {
82        throw new SchemaGenerationException(ex);
83      }
84    }
85  
86    @Override
87    protected JsonGenerationState newGenerationState(
88        IModule module,
89        JsonGenerator schemaWriter,
90        IConfiguration<SchemaGenerationFeature<?>> configuration) {
91      return new JsonGenerationState(module, schemaWriter, configuration);
92    }
93  
94    @Override
95    protected void generateSchema(JsonGenerationState state) {
96      // analyze all definitions
97      List<IAssemblyDefinition> rootAssemblyDefinitions = analyzeDefinitions(
98          state,
99          (entry, definition) -> {
100           assert entry != null;
101           assert definition != null;
102 
103           if (entry.isReferenced()) {
104             // ensure schema is generated
105             state.getSchema(definition);
106           }
107         });
108 
109     if (rootAssemblyDefinitions.isEmpty()) {
110       throw new SchemaGenerationException("No root definitions found");
111     }
112 
113     // generate the properties first to ensure all definitions are identified
114     List<RootPropertyEntry> rootEntries = rootAssemblyDefinitions.stream()
115         .map(root -> {
116           assert root != null;
117           return new RootPropertyEntry(root, state);
118         })
119         .collect(Collectors.toUnmodifiableList());
120 
121     IModule module = state.getModule();
122     try {
123       state.writeStartObject();
124 
125       state.writeField("$schema", "http://json-schema.org/draft-07/schema#");
126       state.writeField("$id",
127           String.format("%s/%s-%s-schema.json",
128               module.getXmlNamespace(),
129               module.getShortName(),
130               module.getVersion()));
131       state.writeField("$comment", module.getName().toMarkdown());
132       state.writeField("type", "object");
133 
134       ObjectNode definitionsObject = state.generateDefinitions();
135       if (!definitionsObject.isEmpty()) {
136         state.writeField("definitions", definitionsObject);
137       }
138 
139       @SuppressWarnings("resource") JsonGenerator writer = state.getWriter(); // NOPMD not owned
140 
141       if (rootEntries.size() == 1) {
142         rootEntries.iterator().next().write(writer);
143       } else {
144         writer.writeFieldName("oneOf");
145         writer.writeStartArray();
146 
147         for (RootPropertyEntry root : rootEntries) {
148           assert root != null;
149           writer.writeStartObject();
150           root.write(writer);
151           writer.writeEndObject();
152         }
153 
154         writer.writeEndArray();
155       }
156       state.writeEndObject();
157     } catch (IOException ex) {
158       throw new SchemaGenerationException(ex);
159     }
160   }
161 
162   @NonNull
163   private static Map<String, ObjectNode> generateRootProperties(
164       @NonNull IAssemblyDefinition definition,
165       @NonNull JsonGenerationState state) {
166     Map<String, ObjectNode> properties = new LinkedHashMap<>(); // NOPMD no concurrent access
167 
168     properties.put("$schema", JsonNodeFactory.instance.objectNode()
169         .put("type", "string")
170         .put("format", "uri-reference"));
171 
172     ObjectNode rootObj = ObjectUtils.notNull(JsonNodeFactory.instance.objectNode());
173     state.getSchema(definition).generateSchemaOrRef(state, rootObj);
174 
175     properties.put(definition.getRootJsonName(), rootObj);
176     return properties;
177   }
178 
179   private static class RootPropertyEntry {
180     @NonNull
181     private final IAssemblyDefinition definition;
182     @NonNull
183     private final Map<String, ObjectNode> properties;
184 
185     public RootPropertyEntry(
186         @NonNull IAssemblyDefinition definition,
187         @NonNull JsonGenerationState state) {
188       this.definition = definition;
189       this.properties = generateRootProperties(definition, state);
190     }
191 
192     @NonNull
193     protected IAssemblyDefinition getDefinition() {
194       return definition;
195     }
196 
197     @NonNull
198     protected Map<String, ObjectNode> getProperties() {
199       return properties;
200     }
201 
202     public void write(JsonGenerator writer) throws IOException {
203       writer.writeFieldName("properties");
204       writer.writeStartObject();
205 
206       for (Map.Entry<String, ObjectNode> entry : getProperties().entrySet()) {
207         writer.writeFieldName(entry.getKey());
208         writer.writeTree(entry.getValue());
209       }
210 
211       writer.writeEndObject();
212 
213       writer.writeFieldName("required");
214       writer.writeStartArray();
215       writer.writeString(getDefinition().getRootJsonName());
216       writer.writeEndArray();
217 
218       writer.writeBooleanField("additionalProperties", false);
219     }
220   }
221 }