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.controller.sal.rest.doc.impl;
10 import java.io.IOException;
11 import java.util.ArrayList;
12 import java.util.Collections;
13 import java.util.HashMap;
14 import java.util.List;
18 import org.json.JSONArray;
19 import org.json.JSONException;
20 import org.json.JSONObject;
21 import org.opendaylight.controller.sal.rest.doc.model.builder.OperationBuilder;
22 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
23 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
24 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
25 import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
26 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
27 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.Module;
32 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
33 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
34 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
35 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
36 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
37 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
38 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
39 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
40 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
41 import org.opendaylight.yangtools.yang.model.util.BooleanType;
42 import org.opendaylight.yangtools.yang.model.util.Decimal64;
43 import org.opendaylight.yangtools.yang.model.util.EnumerationType;
44 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
45 import org.opendaylight.yangtools.yang.model.util.Int16;
46 import org.opendaylight.yangtools.yang.model.util.Int32;
47 import org.opendaylight.yangtools.yang.model.util.Int64;
48 import org.opendaylight.yangtools.yang.model.util.Int8;
49 import org.opendaylight.yangtools.yang.model.util.StringType;
50 import org.opendaylight.yangtools.yang.model.util.Uint16;
51 import org.opendaylight.yangtools.yang.model.util.Uint32;
52 import org.opendaylight.yangtools.yang.model.util.Uint64;
53 import org.opendaylight.yangtools.yang.model.util.Uint8;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
58 * Generates JSON Schema for data defined in Yang
60 public class ModelGenerator {
62 private static Logger _logger = LoggerFactory.getLogger(ModelGenerator.class);
64 private static final String BASE_64 = "base64";
65 private static final String BINARY_ENCODING_KEY = "binaryEncoding";
66 private static final String MEDIA_KEY = "media";
67 private static final String ONE_OF_KEY = "oneOf";
68 private static final String UNIQUE_ITEMS_KEY = "uniqueItems";
69 private static final String MAX_ITEMS = "maxItems";
70 private static final String MIN_ITEMS = "minItems";
71 private static final String SCHEMA_URL = "http://json-schema.org/draft-04/schema";
72 private static final String SCHEMA_KEY = "$schema";
73 private static final String MAX_LENGTH_KEY = "maxLength";
74 private static final String MIN_LENGTH_KEY = "minLength";
75 private static final String REQUIRED_KEY = "required";
76 private static final String REF_KEY = "$ref";
77 private static final String ITEMS_KEY = "items";
78 private static final String TYPE_KEY = "type";
79 private static final String PROPERTIES_KEY = "properties";
80 private static final String DESCRIPTION_KEY = "description";
81 private static final String OBJECT_TYPE = "object";
82 private static final String ARRAY_TYPE = "array";
83 private static final String ENUM = "enum";
84 private static final String INTEGER = "integer";
85 private static final String NUMBER = "number";
86 private static final String BOOLEAN = "boolean";
87 private static final String STRING = "string";
89 private static final Map<Class<? extends TypeDefinition<?>>, String> YANG_TYPE_TO_JSON_TYPE_MAPPING;
92 Map<Class<? extends TypeDefinition<?>>, String> tempMap1 = new HashMap<Class<? extends TypeDefinition<?>>, String>(
94 tempMap1.put(StringType.class, STRING);
95 tempMap1.put(BooleanType.class, BOOLEAN);
96 tempMap1.put(Int8.class, INTEGER);
97 tempMap1.put(Int16.class, INTEGER);
98 tempMap1.put(Int32.class, INTEGER);
99 tempMap1.put(Int64.class, INTEGER);
100 tempMap1.put(Uint16.class, INTEGER);
101 tempMap1.put(Uint32.class, INTEGER);
102 tempMap1.put(Uint64.class, INTEGER);
103 tempMap1.put(Uint8.class, INTEGER);
104 tempMap1.put(Decimal64.class, NUMBER);
105 tempMap1.put(EnumerationType.class, ENUM);
108 YANG_TYPE_TO_JSON_TYPE_MAPPING = Collections.unmodifiableMap(tempMap1);
111 public ModelGenerator() {
114 public JSONObject convertToJsonSchema(Module module) throws IOException, JSONException {
115 JSONObject models = new JSONObject();
116 processContainers(module, models);
117 processRPCs(module, models);
121 private void processContainers(Module module, JSONObject models) throws IOException,
124 String moduleName = module.getName();
125 Set<DataSchemaNode> childNodes = module.getChildNodes();
127 for (DataSchemaNode childNode : childNodes) {
128 JSONObject configModuleJSON = null;
129 JSONObject operationalModuleJSON = null;
131 String childNodeName = childNode.getQName().getLocalName();
133 * For every container in the module
135 if (childNode instanceof ContainerSchemaNode) {
136 configModuleJSON = processContainer((ContainerSchemaNode) childNode, moduleName,
138 operationalModuleJSON = processContainer((ContainerSchemaNode) childNode,
139 moduleName, true, models, false);
142 if (configModuleJSON != null) {
143 _logger.debug("Adding model for [{}]", OperationBuilder.CONFIG + childNodeName);
144 configModuleJSON.put("id", OperationBuilder.CONFIG + childNodeName);
145 models.put(OperationBuilder.CONFIG + childNodeName, configModuleJSON);
147 if (operationalModuleJSON != null) {
148 _logger.debug("Adding model for [{}]", OperationBuilder.OPERATIONAL + childNodeName);
149 operationalModuleJSON.put("id", OperationBuilder.OPERATIONAL + childNodeName);
150 models.put(OperationBuilder.OPERATIONAL + childNodeName, operationalModuleJSON);
157 * Process the RPCs for a Module Spits out a file each of the name
158 * <rpcName>-input.json and <rpcName>-output.json for each RPC that contains
159 * input & output elements
162 * @throws JSONException
163 * @throws IOException
165 private void processRPCs(Module module, JSONObject models) throws JSONException, IOException {
167 Set<RpcDefinition> rpcs = module.getRpcs();
168 String moduleName = module.getName();
169 for (RpcDefinition rpc : rpcs) {
171 ContainerSchemaNode input = rpc.getInput();
173 JSONObject inputJSON = processContainer(input, moduleName, true, models);
174 String filename = "(" + rpc.getQName().getLocalName() + ")input";
175 inputJSON.put("id", filename);
176 // writeToFile(filename, inputJSON.toString(2), moduleName);
177 models.put(filename, inputJSON);
180 ContainerSchemaNode output = rpc.getOutput();
181 if (output != null) {
182 JSONObject outputJSON = processContainer(output, moduleName, true, models);
183 String filename = "(" + rpc.getQName().getLocalName() + ")output";
184 outputJSON.put("id", filename);
185 models.put(filename, outputJSON);
191 * Processes the container node and populates the moduleJSON
196 * @throws JSONException
197 * @throws IOException
199 private JSONObject processContainer(ContainerSchemaNode container, String moduleName,
200 boolean addSchemaStmt, JSONObject models) throws JSONException, IOException {
201 return processContainer(container, moduleName, addSchemaStmt, models, (Boolean) null);
204 private JSONObject processContainer(ContainerSchemaNode container, String moduleName,
205 boolean addSchemaStmt, JSONObject models, Boolean isConfig) throws JSONException,
207 JSONObject moduleJSON = getSchemaTemplate();
209 moduleJSON = getSchemaTemplate();
211 moduleJSON = new JSONObject();
213 moduleJSON.put(TYPE_KEY, OBJECT_TYPE);
215 String containerDescription = container.getDescription();
216 moduleJSON.put(DESCRIPTION_KEY, containerDescription);
218 Set<DataSchemaNode> containerChildren = container.getChildNodes();
219 JSONObject properties = processChildren(containerChildren, moduleName, models, isConfig);
220 moduleJSON.put(PROPERTIES_KEY, properties);
224 private JSONObject processChildren(Set<DataSchemaNode> nodes, String moduleName,
225 JSONObject models) throws JSONException, IOException {
226 return processChildren(nodes, moduleName, models, null);
230 * Processes the nodes
236 * @throws JSONException
237 * @throws IOException
239 private JSONObject processChildren(Set<DataSchemaNode> nodes, String moduleName,
240 JSONObject models, Boolean isConfig) throws JSONException, IOException {
242 JSONObject properties = new JSONObject();
244 for (DataSchemaNode node : nodes) {
245 if (isConfig == null || node.isConfiguration() == isConfig) {
247 String name = node.getQName().getLocalName();
248 JSONObject property = null;
249 if (node instanceof LeafSchemaNode) {
250 property = processLeafNode((LeafSchemaNode) node);
251 } else if (node instanceof ListSchemaNode) {
252 property = processListSchemaNode((ListSchemaNode) node, moduleName, models);
254 } else if (node instanceof LeafListSchemaNode) {
255 property = processLeafListNode((LeafListSchemaNode) node);
257 } else if (node instanceof ChoiceNode) {
258 property = processChoiceNode((ChoiceNode) node, moduleName, models);
260 } else if (node instanceof AnyXmlSchemaNode) {
261 property = processAnyXMLNode((AnyXmlSchemaNode) node);
263 } else if (node instanceof ContainerSchemaNode) {
264 property = processContainer((ContainerSchemaNode) node, moduleName, false,
268 throw new IllegalArgumentException("Unknown DataSchemaNode type: "
272 property.putOpt(DESCRIPTION_KEY, node.getDescription());
273 properties.put(name, property);
282 * @throws JSONException
284 private JSONObject processLeafListNode(LeafListSchemaNode listNode) throws JSONException {
285 JSONObject props = new JSONObject();
286 props.put(TYPE_KEY, ARRAY_TYPE);
288 JSONObject itemsVal = new JSONObject();
289 processTypeDef(listNode.getType(), itemsVal);
290 props.put(ITEMS_KEY, itemsVal);
292 ConstraintDefinition constraints = listNode.getConstraints();
293 processConstraints(constraints, props);
302 * @throws JSONException
303 * @throws IOException
305 private JSONObject processChoiceNode(ChoiceNode choiceNode, String moduleName, JSONObject models)
306 throws JSONException, IOException {
308 Set<ChoiceCaseNode> cases = choiceNode.getCases();
310 JSONArray choiceProps = new JSONArray();
311 for (ChoiceCaseNode choiceCase : cases) {
312 String choiceName = choiceCase.getQName().getLocalName();
313 JSONObject choiceProp = processChildren(choiceCase.getChildNodes(), moduleName, models);
314 JSONObject choiceObj = new JSONObject();
315 choiceObj.put(choiceName, choiceProp);
316 choiceObj.put(TYPE_KEY, OBJECT_TYPE);
317 choiceProps.put(choiceObj);
320 JSONObject oneOfProps = new JSONObject();
321 oneOfProps.put(ONE_OF_KEY, choiceProps);
322 oneOfProps.put(TYPE_KEY, OBJECT_TYPE);
331 * @throws JSONException
333 private void processConstraints(ConstraintDefinition constraints, JSONObject props)
334 throws JSONException {
335 boolean isMandatory = constraints.isMandatory();
336 props.put(REQUIRED_KEY, isMandatory);
338 Integer minElements = constraints.getMinElements();
339 Integer maxElements = constraints.getMaxElements();
340 if (minElements != null) {
341 props.put(MIN_ITEMS, minElements);
343 if (maxElements != null) {
344 props.put(MAX_ITEMS, maxElements);
349 * Parses a ListSchema node.
351 * Due to a limitation of the RAML--->JAX-RS tool, sub-properties must be in
352 * a separate JSON schema file. Hence, we have to write some properties to a
353 * new file, while continuing to process the rest.
358 * @throws JSONException
359 * @throws IOException
361 private JSONObject processListSchemaNode(ListSchemaNode listNode, String moduleName,
362 JSONObject models) throws JSONException, IOException {
364 Set<DataSchemaNode> listChildren = listNode.getChildNodes();
365 String fileName = listNode.getQName().getLocalName();
367 JSONObject childSchemaProperties = processChildren(listChildren, moduleName, models);
368 JSONObject childSchema = getSchemaTemplate();
369 childSchema.put(TYPE_KEY, OBJECT_TYPE);
370 childSchema.put(PROPERTIES_KEY, childSchemaProperties);
373 * Due to a limitation of the RAML--->JAX-RS tool, sub-properties must
374 * be in a separate JSON schema file. Hence, we have to write some
375 * properties to a new file, while continuing to process the rest.
377 // writeToFile(fileName, childSchema.toString(2), moduleName);
378 childSchema.put("id", fileName);
379 models.put(fileName, childSchema);
381 JSONObject listNodeProperties = new JSONObject();
382 listNodeProperties.put(TYPE_KEY, ARRAY_TYPE);
384 JSONObject items = new JSONObject();
385 items.put(REF_KEY, fileName);
386 listNodeProperties.put(ITEMS_KEY, items);
388 return listNodeProperties;
396 * @throws JSONException
398 private JSONObject processLeafNode(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);
414 * @throws JSONException
416 private JSONObject processAnyXMLNode(AnyXmlSchemaNode leafNode) throws JSONException {
417 JSONObject property = new JSONObject();
419 String leafDescription = leafNode.getDescription();
420 property.put(DESCRIPTION_KEY, leafDescription);
422 processConstraints(leafNode.getConstraints(), property);
429 * @throws JSONException
431 private void processTypeDef(TypeDefinition<?> leafTypeDef, JSONObject property)
432 throws JSONException {
434 if (leafTypeDef instanceof ExtendedType) {
435 processExtendedType(leafTypeDef, property);
436 } else if (leafTypeDef instanceof EnumerationType) {
437 processEnumType((EnumerationType) leafTypeDef, property);
439 } else if (leafTypeDef instanceof BitsTypeDefinition) {
440 processBitsType((BitsTypeDefinition) leafTypeDef, property);
442 } else if (leafTypeDef instanceof UnionTypeDefinition) {
443 processUnionType((UnionTypeDefinition) leafTypeDef, property);
445 } else if (leafTypeDef instanceof IdentityrefTypeDefinition) {
446 property.putOpt(TYPE_KEY, "object");
447 } else if (leafTypeDef instanceof BinaryTypeDefinition) {
448 processBinaryType((BinaryTypeDefinition) leafTypeDef, property);
450 // System.out.println("In else: " + leafTypeDef.getClass());
451 String jsonType = YANG_TYPE_TO_JSON_TYPE_MAPPING.get(leafTypeDef.getClass());
452 if (jsonType == null) {
455 property.putOpt(TYPE_KEY, jsonType);
463 * @throws JSONException
465 private void processExtendedType(TypeDefinition<?> leafTypeDef, JSONObject property)
466 throws JSONException {
467 Object leafBaseType = leafTypeDef.getBaseType();
468 if (leafBaseType instanceof ExtendedType) {
469 // recursively process an extended type until we hit a base type
470 processExtendedType((TypeDefinition<?>) leafBaseType, property);
472 List<LengthConstraint> lengthConstraints = ((ExtendedType) leafTypeDef)
473 .getLengthConstraints();
474 for (LengthConstraint lengthConstraint : lengthConstraints) {
475 Number min = lengthConstraint.getMin();
476 Number max = lengthConstraint.getMax();
477 property.putOpt(MIN_LENGTH_KEY, min);
478 property.putOpt(MAX_LENGTH_KEY, max);
480 String jsonType = YANG_TYPE_TO_JSON_TYPE_MAPPING.get(leafBaseType.getClass());
481 property.putOpt(TYPE_KEY, jsonType);
489 private void processBinaryType(BinaryTypeDefinition binaryType, JSONObject property)
490 throws JSONException {
491 property.put(TYPE_KEY, STRING);
492 JSONObject media = new JSONObject();
493 media.put(BINARY_ENCODING_KEY, BASE_64);
494 property.put(MEDIA_KEY, media);
499 * @param enumLeafType
501 * @throws JSONException
503 private void processEnumType(EnumerationType enumLeafType, JSONObject property)
504 throws JSONException {
505 List<EnumPair> enumPairs = enumLeafType.getValues();
506 List<String> enumNames = new ArrayList<String>();
507 for (EnumPair enumPair : enumPairs) {
508 enumNames.add(enumPair.getName());
510 property.putOpt(ENUM, new JSONArray(enumNames));
517 * @throws JSONException
519 private void processBitsType(BitsTypeDefinition bitsType, JSONObject property)
520 throws JSONException {
521 property.put(TYPE_KEY, ARRAY_TYPE);
522 property.put(MIN_ITEMS, 0);
523 property.put(UNIQUE_ITEMS_KEY, true);
524 JSONArray enumValues = new JSONArray();
526 List<Bit> bits = bitsType.getBits();
527 for (Bit bit : bits) {
528 enumValues.put(bit.getName());
530 JSONObject itemsValue = new JSONObject();
531 itemsValue.put(ENUM, enumValues);
532 property.put(ITEMS_KEY, itemsValue);
539 * @throws JSONException
541 private void processUnionType(UnionTypeDefinition unionType, JSONObject property)
542 throws JSONException {
544 List<TypeDefinition<?>> unionTypes = unionType.getTypes();
545 JSONArray unionArray = new JSONArray();
546 for (TypeDefinition<?> typeDef : unionTypes) {
547 unionArray.put(YANG_TYPE_TO_JSON_TYPE_MAPPING.get(typeDef.getClass()));
549 property.put(TYPE_KEY, unionArray);
553 * Helper method to generate a pre-filled JSON schema object.
556 * @throws JSONException
558 private JSONObject getSchemaTemplate() throws JSONException {
559 JSONObject schemaJSON = new JSONObject();
560 schemaJSON.put(SCHEMA_KEY, SCHEMA_URL);