2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.netconf.sal.rest.doc.impl;
10 import static org.opendaylight.netconf.sal.rest.doc.util.RestDocgenUtil.resolveNodesName;
11 import com.google.common.base.Preconditions;
12 import java.io.IOException;
13 import java.util.ArrayList;
14 import java.util.List;
16 import javax.annotation.concurrent.NotThreadSafe;
17 import org.json.JSONArray;
18 import org.json.JSONException;
19 import org.json.JSONObject;
20 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder;
21 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Post;
22 import org.opendaylight.yangtools.yang.common.QName;
23 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
24 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
25 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
27 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
29 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.Module;
35 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
36 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
37 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
39 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
40 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
41 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
42 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
43 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
44 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
45 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
46 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
47 import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
48 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
49 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
50 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
51 import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
56 * Generates JSON Schema for data defined in YANG.
59 public class ModelGenerator {
61 private static final Logger LOG = LoggerFactory.getLogger(ModelGenerator.class);
63 private static final String BASE_64 = "base64";
64 private static final String BINARY_ENCODING_KEY = "binaryEncoding";
65 private static final String MEDIA_KEY = "media";
66 private static final String ONE_OF_KEY = "oneOf";
67 private static final String UNIQUE_ITEMS_KEY = "uniqueItems";
68 private static final String MAX_ITEMS = "maxItems";
69 private static final String MIN_ITEMS = "minItems";
70 private static final String SCHEMA_URL = "http://json-schema.org/draft-04/schema";
71 private static final String SCHEMA_KEY = "$schema";
72 private static final String MAX_LENGTH_KEY = "maxLength";
73 private static final String MIN_LENGTH_KEY = "minLength";
74 private static final String REQUIRED_KEY = "required";
75 private static final String REF_KEY = "$ref";
76 private static final String ITEMS_KEY = "items";
77 private static final String TYPE_KEY = "type";
78 private static final String PROPERTIES_KEY = "properties";
79 private static final String DESCRIPTION_KEY = "description";
80 private static final String OBJECT_TYPE = "object";
81 private static final String ARRAY_TYPE = "array";
82 private static final String ENUM = "enum";
83 private static final String INTEGER = "integer";
84 private static final String NUMBER = "number";
85 private static final String BOOLEAN = "boolean";
86 private static final String STRING = "string";
87 private static final String ID_KEY = "id";
88 private static final String SUB_TYPES_KEY = "subTypes";
90 private Module topLevelModule;
92 public ModelGenerator() {
95 private static String jsonTypeFor(final TypeDefinition<?> type) {
96 if (type instanceof BooleanTypeDefinition) {
98 } else if (type instanceof DecimalTypeDefinition) {
100 } else if (type instanceof EnumTypeDefinition) {
102 } else if (type instanceof IntegerTypeDefinition) {
104 } else if (type instanceof UnsignedIntegerTypeDefinition) {
106 } else if (type instanceof StringTypeDefinition) {
114 public JSONObject convertToJsonSchema(final Module module, final SchemaContext schemaContext) throws IOException, JSONException {
115 JSONObject models = new JSONObject();
116 topLevelModule = module;
117 processModules(module, models);
118 processContainersAndLists(module, models, schemaContext);
119 processRPCs(module, models, schemaContext);
120 processIdentities(module, models);
124 private void processModules(final Module module, final JSONObject models) throws JSONException {
125 createConcreteModelForPost(models, module.getName() + BaseYangSwaggerGenerator.MODULE_NAME_SUFFIX, createPropertiesForPost(module));
128 private void processContainersAndLists(final Module module, final JSONObject models, final SchemaContext schemaContext)
129 throws IOException, JSONException {
131 String moduleName = module.getName();
133 for (DataSchemaNode childNode : module.getChildNodes()) {
134 // For every container and list in the module
135 if (childNode instanceof ContainerSchemaNode || childNode instanceof ListSchemaNode) {
136 processDataNodeContainer((DataNodeContainer) childNode, moduleName, models, true, schemaContext);
137 processDataNodeContainer((DataNodeContainer) childNode, moduleName, models, false, schemaContext);
144 * Process the RPCs for a Module Spits out a file each of the name <rpcName>-input.json and <rpcName>-output.json
145 * for each RPC that contains input & output elements
148 * @throws JSONException
149 * @throws IOException
151 private void processRPCs(final Module module, final JSONObject models, final SchemaContext schemaContext) throws JSONException,
154 Set<RpcDefinition> rpcs = module.getRpcs();
155 String moduleName = module.getName();
156 for (RpcDefinition rpc : rpcs) {
158 ContainerSchemaNode input = rpc.getInput();
160 JSONObject inputJSON = processDataNodeContainer(input, moduleName, models, schemaContext);
161 String filename = "(" + rpc.getQName().getLocalName() + ")input";
162 inputJSON.put("id", filename);
163 // writeToFile(filename, inputJSON.toString(2), moduleName);
164 models.put(filename, inputJSON);
167 ContainerSchemaNode output = rpc.getOutput();
168 if (output != null) {
169 JSONObject outputJSON = processDataNodeContainer(output, moduleName, models, schemaContext);
170 String filename = "(" + rpc.getQName().getLocalName() + ")output";
171 outputJSON.put("id", filename);
172 models.put(filename, outputJSON);
178 * Processes the 'identity' statement in a yang model and maps it to a 'model' in the Swagger JSON spec.
181 * The module from which the identity stmt will be processed
183 * The JSONObject in which the parsed identity will be put as a 'model' obj
185 private static void processIdentities(final Module module, final JSONObject models) throws JSONException {
187 String moduleName = module.getName();
188 Set<IdentitySchemaNode> idNodes = module.getIdentities();
189 LOG.debug("Processing Identities for module {} . Found {} identity statements", moduleName, idNodes.size());
191 for (IdentitySchemaNode idNode : idNodes) {
192 JSONObject identityObj = new JSONObject();
193 String identityName = idNode.getQName().getLocalName();
194 LOG.debug("Processing Identity: {}", identityName);
196 identityObj.put(ID_KEY, identityName);
197 identityObj.put(DESCRIPTION_KEY, idNode.getDescription());
199 JSONObject props = new JSONObject();
200 IdentitySchemaNode baseId = idNode.getBaseIdentity();
202 if (baseId == null) {
204 * This is a base identity. So lets see if it has sub types. If it does, then add them to the model
207 Set<IdentitySchemaNode> derivedIds = idNode.getDerivedIdentities();
209 if (derivedIds != null) {
210 JSONArray subTypes = new JSONArray();
211 for (IdentitySchemaNode derivedId : derivedIds) {
212 subTypes.put(derivedId.getQName().getLocalName());
214 identityObj.put(SUB_TYPES_KEY, subTypes);
218 * This is a derived entity. Add it's base type & move on.
220 props.put(TYPE_KEY, baseId.getQName().getLocalName());
223 // Add the properties. For a base type, this will be an empty object as required by the Swagger spec.
224 identityObj.put(PROPERTIES_KEY, props);
225 models.put(identityName, identityObj);
230 * Processes the container and list nodes and populates the moduleJSON.
232 private JSONObject processDataNodeContainer(final DataNodeContainer dataNode, final String moduleName, final JSONObject models,
233 final SchemaContext schemaContext) throws JSONException, IOException {
234 return processDataNodeContainer(dataNode, moduleName, models, true, schemaContext);
237 private JSONObject processDataNodeContainer(final DataNodeContainer dataNode, final String moduleName, final JSONObject models,
238 final boolean isConfig, final SchemaContext schemaContext) throws JSONException, IOException {
239 if (dataNode instanceof ListSchemaNode || dataNode instanceof ContainerSchemaNode) {
240 Preconditions.checkArgument(dataNode instanceof SchemaNode, "Data node should be also schema node");
241 Iterable<DataSchemaNode> containerChildren = dataNode.getChildNodes();
242 JSONObject properties = processChildren(containerChildren, ((SchemaNode) dataNode).getQName(), moduleName,
243 models, isConfig, schemaContext);
245 String nodeName = (isConfig ? OperationBuilder.CONFIG : OperationBuilder.OPERATIONAL)
246 + ((SchemaNode) dataNode).getQName().getLocalName();
248 JSONObject childSchema = getSchemaTemplate();
249 childSchema.put(TYPE_KEY, OBJECT_TYPE);
250 childSchema.put(PROPERTIES_KEY, properties);
251 childSchema.put("id", nodeName);
252 models.put(nodeName, childSchema);
255 createConcreteModelForPost(models, ((SchemaNode) dataNode).getQName().getLocalName(),
256 createPropertiesForPost(dataNode));
259 JSONObject items = new JSONObject();
260 items.put(REF_KEY, nodeName);
261 JSONObject dataNodeProperties = new JSONObject();
262 dataNodeProperties.put(TYPE_KEY, dataNode instanceof ListSchemaNode ? ARRAY_TYPE : OBJECT_TYPE);
263 dataNodeProperties.put(ITEMS_KEY, items);
265 return dataNodeProperties;
270 private static void createConcreteModelForPost(final JSONObject models, final String localName,
271 final JSONObject properties) throws JSONException {
272 String nodePostName = OperationBuilder.CONFIG + localName + Post.METHOD_NAME;
273 JSONObject postSchema = getSchemaTemplate();
274 postSchema.put(TYPE_KEY, OBJECT_TYPE);
275 postSchema.put("id", nodePostName);
276 postSchema.put(PROPERTIES_KEY, properties);
277 models.put(nodePostName, postSchema);
280 private JSONObject createPropertiesForPost(final DataNodeContainer dataNodeContainer) throws JSONException {
281 JSONObject properties = new JSONObject();
282 for (DataSchemaNode childNode : dataNodeContainer.getChildNodes()) {
283 if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
284 JSONObject items = new JSONObject();
285 items.put(REF_KEY, "(config)" + childNode.getQName().getLocalName());
286 JSONObject property = new JSONObject();
287 property.put(TYPE_KEY, childNode instanceof ListSchemaNode ? ARRAY_TYPE : OBJECT_TYPE);
288 property.put(ITEMS_KEY, items);
289 properties.put(childNode.getQName().getLocalName(), property);
290 } else if (childNode instanceof LeafSchemaNode) {
291 JSONObject property = processLeafNode((LeafSchemaNode)childNode);
292 properties.put(childNode.getQName().getLocalName(), property);
298 private JSONObject processChildren(final Iterable<DataSchemaNode> nodes, final QName parentQName, final String moduleName,
299 final JSONObject models, final SchemaContext schemaContext) throws JSONException, IOException {
300 return processChildren(nodes, parentQName, moduleName, models, true, schemaContext);
304 * Processes the nodes.
306 private JSONObject processChildren(final Iterable<DataSchemaNode> nodes, final QName parentQName,
307 final String moduleName, final JSONObject models, final boolean isConfig, final SchemaContext schemaContext)
308 throws JSONException, IOException {
310 JSONObject properties = new JSONObject();
312 for (DataSchemaNode node : nodes) {
313 if (node.isConfiguration() == isConfig) {
315 String name = resolveNodesName(node, topLevelModule, schemaContext);
316 JSONObject property = null;
317 if (node instanceof LeafSchemaNode) {
318 property = processLeafNode((LeafSchemaNode) node);
319 } else if (node instanceof ListSchemaNode) {
320 property = processDataNodeContainer((ListSchemaNode) node, moduleName, models, isConfig,
323 } else if (node instanceof LeafListSchemaNode) {
324 property = processLeafListNode((LeafListSchemaNode) node);
326 } else if (node instanceof ChoiceSchemaNode) {
327 property = processChoiceNode((ChoiceSchemaNode) node, moduleName, models, schemaContext);
329 } else if (node instanceof AnyXmlSchemaNode) {
330 property = processAnyXMLNode((AnyXmlSchemaNode) node);
332 } else if (node instanceof ContainerSchemaNode) {
333 property = processDataNodeContainer((ContainerSchemaNode) node, moduleName, models, isConfig,
337 throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass());
340 property.putOpt(DESCRIPTION_KEY, node.getDescription());
341 properties.put(name, property);
347 private JSONObject processLeafListNode(final LeafListSchemaNode listNode) throws JSONException {
348 JSONObject props = new JSONObject();
349 props.put(TYPE_KEY, ARRAY_TYPE);
351 JSONObject itemsVal = new JSONObject();
352 processTypeDef(listNode.getType(), itemsVal);
353 props.put(ITEMS_KEY, itemsVal);
355 ConstraintDefinition constraints = listNode.getConstraints();
356 processConstraints(constraints, props);
361 private JSONObject processChoiceNode(final ChoiceSchemaNode choiceNode, final String moduleName, final JSONObject models,
362 final SchemaContext schemaContext) throws JSONException, IOException {
364 Set<ChoiceCaseNode> cases = choiceNode.getCases();
366 JSONArray choiceProps = new JSONArray();
367 for (ChoiceCaseNode choiceCase : cases) {
368 String choiceName = choiceCase.getQName().getLocalName();
369 JSONObject choiceProp = processChildren(choiceCase.getChildNodes(), choiceCase.getQName(), moduleName,
370 models, schemaContext);
371 JSONObject choiceObj = new JSONObject();
372 choiceObj.put(choiceName, choiceProp);
373 choiceObj.put(TYPE_KEY, OBJECT_TYPE);
374 choiceProps.put(choiceObj);
377 JSONObject oneOfProps = new JSONObject();
378 oneOfProps.put(ONE_OF_KEY, choiceProps);
379 oneOfProps.put(TYPE_KEY, OBJECT_TYPE);
384 private static void processConstraints(final ConstraintDefinition constraints, final JSONObject props) throws JSONException {
385 boolean isMandatory = constraints.isMandatory();
386 props.put(REQUIRED_KEY, isMandatory);
388 Integer minElements = constraints.getMinElements();
389 Integer maxElements = constraints.getMaxElements();
390 if (minElements != null) {
391 props.put(MIN_ITEMS, minElements);
393 if (maxElements != null) {
394 props.put(MAX_ITEMS, maxElements);
398 private JSONObject processLeafNode(final LeafSchemaNode leafNode) throws JSONException {
399 JSONObject property = new JSONObject();
401 String leafDescription = leafNode.getDescription();
402 property.put(DESCRIPTION_KEY, leafDescription);
404 processConstraints(leafNode.getConstraints(), property);
405 processTypeDef(leafNode.getType(), property);
410 private static JSONObject processAnyXMLNode(final AnyXmlSchemaNode leafNode) throws JSONException {
411 JSONObject property = new JSONObject();
413 String leafDescription = leafNode.getDescription();
414 property.put(DESCRIPTION_KEY, leafDescription);
416 processConstraints(leafNode.getConstraints(), property);
421 private void processTypeDef(final TypeDefinition<?> leafTypeDef, final JSONObject property) throws JSONException {
422 if (leafTypeDef instanceof BinaryTypeDefinition) {
423 processBinaryType((BinaryTypeDefinition) leafTypeDef, property);
424 } else if (leafTypeDef instanceof BitsTypeDefinition) {
425 processBitsType((BitsTypeDefinition) leafTypeDef, property);
426 } else if (leafTypeDef instanceof EnumTypeDefinition) {
427 processEnumType((EnumTypeDefinition) leafTypeDef, property);
428 } else if (leafTypeDef instanceof IdentityrefTypeDefinition) {
429 property.putOpt(TYPE_KEY,
430 ((IdentityrefTypeDefinition) leafTypeDef).getIdentity().getQName().getLocalName());
431 } else if (leafTypeDef instanceof StringTypeDefinition) {
432 processStringType((StringTypeDefinition) leafTypeDef, property);
433 } else if (leafTypeDef instanceof UnionTypeDefinition) {
434 processUnionType((UnionTypeDefinition) leafTypeDef, property);
436 String jsonType = jsonTypeFor(leafTypeDef);
437 if (jsonType == null) {
440 property.putOpt(TYPE_KEY, jsonType);
444 private static void processBinaryType(final BinaryTypeDefinition binaryType, final JSONObject property) throws JSONException {
445 property.put(TYPE_KEY, STRING);
446 JSONObject media = new JSONObject();
447 media.put(BINARY_ENCODING_KEY, BASE_64);
448 property.put(MEDIA_KEY, media);
451 private static void processEnumType(final EnumTypeDefinition enumLeafType, final JSONObject property) throws JSONException {
452 List<EnumPair> enumPairs = enumLeafType.getValues();
453 List<String> enumNames = new ArrayList<>();
454 for (EnumPair enumPair : enumPairs) {
455 enumNames.add(enumPair.getName());
457 property.putOpt(ENUM, new JSONArray(enumNames));
460 private static void processBitsType(final BitsTypeDefinition bitsType, final JSONObject property) throws JSONException {
461 property.put(TYPE_KEY, ARRAY_TYPE);
462 property.put(MIN_ITEMS, 0);
463 property.put(UNIQUE_ITEMS_KEY, true);
464 JSONArray enumValues = new JSONArray();
466 List<Bit> bits = bitsType.getBits();
467 for (Bit bit : bits) {
468 enumValues.put(bit.getName());
470 JSONObject itemsValue = new JSONObject();
471 itemsValue.put(ENUM, enumValues);
472 property.put(ITEMS_KEY, itemsValue);
475 private static void processStringType(final StringTypeDefinition stringType, final JSONObject property) throws JSONException {
476 StringTypeDefinition type = stringType;
477 List<LengthConstraint> lengthConstraints = stringType.getLengthConstraints();
478 while (lengthConstraints.isEmpty() && type.getBaseType() != null) {
479 type = type.getBaseType();
480 lengthConstraints = type.getLengthConstraints();
483 // FIXME: json-schema is not expressive enough to capture min/max laternatives. We should find the true minimum
484 // and true maximum implied by the constraints and use that.
485 for (LengthConstraint lengthConstraint : lengthConstraints) {
486 Number min = lengthConstraint.getMin();
487 Number max = lengthConstraint.getMax();
488 property.putOpt(MIN_LENGTH_KEY, min);
489 property.putOpt(MAX_LENGTH_KEY, max);
492 property.put(TYPE_KEY, STRING);
495 private static void processUnionType(final UnionTypeDefinition unionType, final JSONObject property) throws JSONException {
496 StringBuilder type = new StringBuilder();
497 for (TypeDefinition<?> typeDef : unionType.getTypes()) {
498 if (type.length() > 0) {
501 type.append(jsonTypeFor(typeDef));
504 property.put(TYPE_KEY, type);
508 * Helper method to generate a pre-filled JSON schema object.
510 private static JSONObject getSchemaTemplate() throws JSONException {
511 JSONObject schemaJSON = new JSONObject();
512 schemaJSON.put(SCHEMA_KEY, SCHEMA_URL);