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;
17 import org.apache.commons.lang3.BooleanUtils;
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.IdentitySchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.Module;
33 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
34 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
35 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
36 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
37 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
38 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
39 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
40 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
41 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
42 import org.opendaylight.yangtools.yang.model.util.BooleanType;
43 import org.opendaylight.yangtools.yang.model.util.Decimal64;
44 import org.opendaylight.yangtools.yang.model.util.EnumerationType;
45 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
46 import org.opendaylight.yangtools.yang.model.util.Int16;
47 import org.opendaylight.yangtools.yang.model.util.Int32;
48 import org.opendaylight.yangtools.yang.model.util.Int64;
49 import org.opendaylight.yangtools.yang.model.util.Int8;
50 import org.opendaylight.yangtools.yang.model.util.StringType;
51 import org.opendaylight.yangtools.yang.model.util.Uint16;
52 import org.opendaylight.yangtools.yang.model.util.Uint32;
53 import org.opendaylight.yangtools.yang.model.util.Uint64;
54 import org.opendaylight.yangtools.yang.model.util.Uint8;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
59 * Generates JSON Schema for data defined in Yang
61 public class ModelGenerator {
63 private static Logger _logger = LoggerFactory.getLogger(ModelGenerator.class);
65 private static final String BASE_64 = "base64";
66 private static final String BINARY_ENCODING_KEY = "binaryEncoding";
67 private static final String MEDIA_KEY = "media";
68 private static final String ONE_OF_KEY = "oneOf";
69 private static final String UNIQUE_ITEMS_KEY = "uniqueItems";
70 private static final String MAX_ITEMS = "maxItems";
71 private static final String MIN_ITEMS = "minItems";
72 private static final String SCHEMA_URL = "http://json-schema.org/draft-04/schema";
73 private static final String SCHEMA_KEY = "$schema";
74 private static final String MAX_LENGTH_KEY = "maxLength";
75 private static final String MIN_LENGTH_KEY = "minLength";
76 private static final String REQUIRED_KEY = "required";
77 private static final String REF_KEY = "$ref";
78 private static final String ITEMS_KEY = "items";
79 private static final String TYPE_KEY = "type";
80 private static final String PROPERTIES_KEY = "properties";
81 private static final String DESCRIPTION_KEY = "description";
82 private static final String OBJECT_TYPE = "object";
83 private static final String ARRAY_TYPE = "array";
84 private static final String ENUM = "enum";
85 private static final String INTEGER = "integer";
86 private static final String NUMBER = "number";
87 private static final String BOOLEAN = "boolean";
88 private static final String STRING = "string";
89 private static final String ID_KEY = "id";
90 private static final String SUB_TYPES_KEY = "subTypes";
92 private static final Map<Class<? extends TypeDefinition<?>>, String> YANG_TYPE_TO_JSON_TYPE_MAPPING;
95 Map<Class<? extends TypeDefinition<?>>, String> tempMap1 = new HashMap<Class<? extends TypeDefinition<?>>, String>(
97 tempMap1.put(StringType.class, STRING);
98 tempMap1.put(BooleanType.class, BOOLEAN);
99 tempMap1.put(Int8.class, INTEGER);
100 tempMap1.put(Int16.class, INTEGER);
101 tempMap1.put(Int32.class, INTEGER);
102 tempMap1.put(Int64.class, INTEGER);
103 tempMap1.put(Uint16.class, INTEGER);
104 tempMap1.put(Uint32.class, INTEGER);
105 tempMap1.put(Uint64.class, INTEGER);
106 tempMap1.put(Uint8.class, INTEGER);
107 tempMap1.put(Decimal64.class, NUMBER);
108 tempMap1.put(EnumerationType.class, ENUM);
111 YANG_TYPE_TO_JSON_TYPE_MAPPING = Collections.unmodifiableMap(tempMap1);
114 public ModelGenerator() {
117 public JSONObject convertToJsonSchema(Module module) throws IOException, JSONException {
118 JSONObject models = new JSONObject();
119 processContainers(module, models);
120 processRPCs(module, models);
121 processIdentities(module, models);
125 private void processContainers(Module module, JSONObject models) throws IOException,
128 String moduleName = module.getName();
130 for (DataSchemaNode childNode : module.getChildNodes()) {
131 JSONObject configModuleJSON = null;
132 JSONObject operationalModuleJSON = null;
134 String childNodeName = childNode.getQName().getLocalName();
136 * For every container in the module
138 if (childNode instanceof ContainerSchemaNode) {
139 configModuleJSON = processContainer((ContainerSchemaNode) childNode, moduleName,
141 operationalModuleJSON = processContainer((ContainerSchemaNode) childNode,
142 moduleName, true, models, false);
145 if (configModuleJSON != null) {
146 _logger.debug("Adding model for [{}]", OperationBuilder.CONFIG + childNodeName);
147 configModuleJSON.put("id", OperationBuilder.CONFIG + childNodeName);
148 models.put(OperationBuilder.CONFIG + childNodeName, configModuleJSON);
150 if (operationalModuleJSON != null) {
151 _logger.debug("Adding model for [{}]", OperationBuilder.OPERATIONAL + childNodeName);
152 operationalModuleJSON.put("id", OperationBuilder.OPERATIONAL + childNodeName);
153 models.put(OperationBuilder.OPERATIONAL + childNodeName, operationalModuleJSON);
160 * Process the RPCs for a Module Spits out a file each of the name
161 * <rpcName>-input.json and <rpcName>-output.json for each RPC that contains
162 * input & output elements
165 * @throws JSONException
166 * @throws IOException
168 private void processRPCs(Module module, JSONObject models) throws JSONException, IOException {
170 Set<RpcDefinition> rpcs = module.getRpcs();
171 String moduleName = module.getName();
172 for (RpcDefinition rpc : rpcs) {
174 ContainerSchemaNode input = rpc.getInput();
176 JSONObject inputJSON = processContainer(input, moduleName, true, models);
177 String filename = "(" + rpc.getQName().getLocalName() + ")input";
178 inputJSON.put("id", filename);
179 // writeToFile(filename, inputJSON.toString(2), moduleName);
180 models.put(filename, inputJSON);
183 ContainerSchemaNode output = rpc.getOutput();
184 if (output != null) {
185 JSONObject outputJSON = processContainer(output, moduleName, true, models);
186 String filename = "(" + rpc.getQName().getLocalName() + ")output";
187 outputJSON.put("id", filename);
188 models.put(filename, outputJSON);
194 * Processes the 'identity' statement in a yang model
195 * and maps it to a 'model' in the Swagger JSON spec.
197 * @param module The module from which the identity stmt will be processed
198 * @param models The JSONObject in which the parsed identity will be put as a 'model' obj
199 * @throws JSONException
201 private void processIdentities(Module module, JSONObject models) throws JSONException {
203 String moduleName = module.getName();
204 Set<IdentitySchemaNode> idNodes = module.getIdentities();
205 _logger.debug("Processing Identities for module {} . Found {} identity statements", moduleName, idNodes.size());
207 for(IdentitySchemaNode idNode : idNodes){
208 JSONObject identityObj=new JSONObject();
209 String identityName = idNode.getQName().getLocalName();
210 _logger.debug("Processing Identity: {}", identityName);
212 identityObj.put(ID_KEY, identityName);
213 identityObj.put(DESCRIPTION_KEY, idNode.getDescription());
215 JSONObject props = new JSONObject();
216 IdentitySchemaNode baseId = idNode.getBaseIdentity();
221 * This is a base identity. So lets see if
222 * it has sub types. If it does, then add them to the model definition.
224 Set<IdentitySchemaNode> derivedIds = idNode.getDerivedIdentities();
226 if(derivedIds != null) {
227 JSONArray subTypes = new JSONArray();
228 for(IdentitySchemaNode derivedId : derivedIds){
229 subTypes.put(derivedId.getQName().getLocalName());
231 identityObj.put(SUB_TYPES_KEY, subTypes);
235 * This is a derived entity. Add it's base type & move on.
237 props.put(TYPE_KEY, baseId.getQName().getLocalName());
240 //Add the properties. For a base type, this will be an empty object as required by the Swagger spec.
241 identityObj.put(PROPERTIES_KEY, props);
242 models.put(identityName, identityObj);
246 * Processes the container node and populates the moduleJSON
251 * @throws JSONException
252 * @throws IOException
254 private JSONObject processContainer(ContainerSchemaNode container, String moduleName,
255 boolean addSchemaStmt, JSONObject models) throws JSONException, IOException {
256 return processContainer(container, moduleName, addSchemaStmt, models, (Boolean) null);
259 private JSONObject processContainer(ContainerSchemaNode container, String moduleName,
260 boolean addSchemaStmt, JSONObject models, Boolean isConfig) throws JSONException,
262 JSONObject moduleJSON = getSchemaTemplate();
264 moduleJSON = getSchemaTemplate();
266 moduleJSON = new JSONObject();
268 moduleJSON.put(TYPE_KEY, OBJECT_TYPE);
270 String containerDescription = container.getDescription();
271 moduleJSON.put(DESCRIPTION_KEY, containerDescription);
273 JSONObject properties = processChildren(container.getChildNodes(), moduleName, models, isConfig);
274 moduleJSON.put(PROPERTIES_KEY, properties);
278 private JSONObject processChildren(Iterable<DataSchemaNode> nodes, String moduleName,
279 JSONObject models) throws JSONException, IOException {
280 return processChildren(nodes, moduleName, models, null);
284 * Processes the nodes
290 * @throws JSONException
291 * @throws IOException
293 private JSONObject processChildren(Iterable<DataSchemaNode> nodes, String moduleName,
294 JSONObject models, Boolean isConfig) throws JSONException, IOException {
296 JSONObject properties = new JSONObject();
298 for (DataSchemaNode node : nodes) {
299 if (isConfig == null || node.isConfiguration() == isConfig) {
301 String name = node.getQName().getLocalName();
302 JSONObject property = null;
303 if (node instanceof LeafSchemaNode) {
304 property = processLeafNode((LeafSchemaNode) node);
305 } else if (node instanceof ListSchemaNode) {
306 property = processListSchemaNode((ListSchemaNode) node, moduleName, models, isConfig);
308 } else if (node instanceof LeafListSchemaNode) {
309 property = processLeafListNode((LeafListSchemaNode) node);
311 } else if (node instanceof ChoiceNode) {
312 property = processChoiceNode((ChoiceNode) node, moduleName, models);
314 } else if (node instanceof AnyXmlSchemaNode) {
315 property = processAnyXMLNode((AnyXmlSchemaNode) node);
317 } else if (node instanceof ContainerSchemaNode) {
318 property = processContainer((ContainerSchemaNode) node, moduleName, false,
322 throw new IllegalArgumentException("Unknown DataSchemaNode type: "
326 property.putOpt(DESCRIPTION_KEY, node.getDescription());
327 properties.put(name, property);
336 * @throws JSONException
338 private JSONObject processLeafListNode(LeafListSchemaNode listNode) throws JSONException {
339 JSONObject props = new JSONObject();
340 props.put(TYPE_KEY, ARRAY_TYPE);
342 JSONObject itemsVal = new JSONObject();
343 processTypeDef(listNode.getType(), itemsVal);
344 props.put(ITEMS_KEY, itemsVal);
346 ConstraintDefinition constraints = listNode.getConstraints();
347 processConstraints(constraints, props);
356 * @throws JSONException
357 * @throws IOException
359 private JSONObject processChoiceNode(ChoiceNode choiceNode, String moduleName, JSONObject models)
360 throws JSONException, IOException {
362 Set<ChoiceCaseNode> cases = choiceNode.getCases();
364 JSONArray choiceProps = new JSONArray();
365 for (ChoiceCaseNode choiceCase : cases) {
366 String choiceName = choiceCase.getQName().getLocalName();
367 JSONObject choiceProp = processChildren(choiceCase.getChildNodes(), moduleName, models);
368 JSONObject choiceObj = new JSONObject();
369 choiceObj.put(choiceName, choiceProp);
370 choiceObj.put(TYPE_KEY, OBJECT_TYPE);
371 choiceProps.put(choiceObj);
374 JSONObject oneOfProps = new JSONObject();
375 oneOfProps.put(ONE_OF_KEY, choiceProps);
376 oneOfProps.put(TYPE_KEY, OBJECT_TYPE);
385 * @throws JSONException
387 private void processConstraints(ConstraintDefinition constraints, JSONObject props)
388 throws JSONException {
389 boolean isMandatory = constraints.isMandatory();
390 props.put(REQUIRED_KEY, isMandatory);
392 Integer minElements = constraints.getMinElements();
393 Integer maxElements = constraints.getMaxElements();
394 if (minElements != null) {
395 props.put(MIN_ITEMS, minElements);
397 if (maxElements != null) {
398 props.put(MAX_ITEMS, maxElements);
403 * Parses a ListSchema node.
405 * Due to a limitation of the RAML--->JAX-RS tool, sub-properties must be in
406 * a separate JSON schema file. Hence, we have to write some properties to a
407 * new file, while continuing to process the rest.
413 * @throws JSONException
414 * @throws IOException
416 private JSONObject processListSchemaNode(ListSchemaNode listNode, String moduleName,
417 JSONObject models, Boolean isConfig) throws JSONException, IOException {
419 String fileName = (BooleanUtils.isNotFalse(isConfig)?OperationBuilder.CONFIG:OperationBuilder.OPERATIONAL) +
420 listNode.getQName().getLocalName();
422 JSONObject childSchemaProperties = processChildren(listNode.getChildNodes(), moduleName, models);
423 JSONObject childSchema = getSchemaTemplate();
424 childSchema.put(TYPE_KEY, OBJECT_TYPE);
425 childSchema.put(PROPERTIES_KEY, childSchemaProperties);
428 * Due to a limitation of the RAML--->JAX-RS tool, sub-properties must
429 * be in a separate JSON schema file. Hence, we have to write some
430 * properties to a new file, while continuing to process the rest.
432 // writeToFile(fileName, childSchema.toString(2), moduleName);
433 childSchema.put("id", fileName);
434 models.put(fileName, childSchema);
436 JSONObject listNodeProperties = new JSONObject();
437 listNodeProperties.put(TYPE_KEY, ARRAY_TYPE);
439 JSONObject items = new JSONObject();
440 items.put(REF_KEY, fileName);
441 listNodeProperties.put(ITEMS_KEY, items);
443 return listNodeProperties;
451 * @throws JSONException
453 private JSONObject processLeafNode(LeafSchemaNode leafNode) throws JSONException {
454 JSONObject property = new JSONObject();
456 String leafDescription = leafNode.getDescription();
457 property.put(DESCRIPTION_KEY, leafDescription);
459 processConstraints(leafNode.getConstraints(), property);
460 processTypeDef(leafNode.getType(), property);
469 * @throws JSONException
471 private JSONObject processAnyXMLNode(AnyXmlSchemaNode leafNode) throws JSONException {
472 JSONObject property = new JSONObject();
474 String leafDescription = leafNode.getDescription();
475 property.put(DESCRIPTION_KEY, leafDescription);
477 processConstraints(leafNode.getConstraints(), property);
484 * @throws JSONException
486 private void processTypeDef(TypeDefinition<?> leafTypeDef, JSONObject property)
487 throws JSONException {
489 if (leafTypeDef instanceof ExtendedType) {
490 processExtendedType(leafTypeDef, property);
491 } else if (leafTypeDef instanceof EnumerationType) {
492 processEnumType((EnumerationType) leafTypeDef, property);
494 } else if (leafTypeDef instanceof BitsTypeDefinition) {
495 processBitsType((BitsTypeDefinition) leafTypeDef, property);
497 } else if (leafTypeDef instanceof UnionTypeDefinition) {
498 processUnionType((UnionTypeDefinition) leafTypeDef, property);
500 } else if (leafTypeDef instanceof IdentityrefTypeDefinition) {
501 property.putOpt(TYPE_KEY, ((IdentityrefTypeDefinition) leafTypeDef).getIdentity().getQName().getLocalName());
502 } else if (leafTypeDef instanceof BinaryTypeDefinition) {
503 processBinaryType((BinaryTypeDefinition) leafTypeDef, property);
505 // System.out.println("In else: " + leafTypeDef.getClass());
506 String jsonType = YANG_TYPE_TO_JSON_TYPE_MAPPING.get(leafTypeDef.getClass());
507 if (jsonType == null) {
510 property.putOpt(TYPE_KEY, jsonType);
518 * @throws JSONException
520 private void processExtendedType(TypeDefinition<?> leafTypeDef, JSONObject property)
521 throws JSONException {
522 Object leafBaseType = leafTypeDef.getBaseType();
523 if (leafBaseType instanceof ExtendedType) {
524 // recursively process an extended type until we hit a base type
525 processExtendedType((TypeDefinition<?>) leafBaseType, property);
527 List<LengthConstraint> lengthConstraints = ((ExtendedType) leafTypeDef)
528 .getLengthConstraints();
529 for (LengthConstraint lengthConstraint : lengthConstraints) {
530 Number min = lengthConstraint.getMin();
531 Number max = lengthConstraint.getMax();
532 property.putOpt(MIN_LENGTH_KEY, min);
533 property.putOpt(MAX_LENGTH_KEY, max);
535 String jsonType = YANG_TYPE_TO_JSON_TYPE_MAPPING.get(leafBaseType.getClass());
536 property.putOpt(TYPE_KEY, jsonType);
544 private void processBinaryType(BinaryTypeDefinition binaryType, JSONObject property)
545 throws JSONException {
546 property.put(TYPE_KEY, STRING);
547 JSONObject media = new JSONObject();
548 media.put(BINARY_ENCODING_KEY, BASE_64);
549 property.put(MEDIA_KEY, media);
554 * @param enumLeafType
556 * @throws JSONException
558 private void processEnumType(EnumerationType enumLeafType, JSONObject property)
559 throws JSONException {
560 List<EnumPair> enumPairs = enumLeafType.getValues();
561 List<String> enumNames = new ArrayList<String>();
562 for (EnumPair enumPair : enumPairs) {
563 enumNames.add(enumPair.getName());
565 property.putOpt(ENUM, new JSONArray(enumNames));
572 * @throws JSONException
574 private void processBitsType(BitsTypeDefinition bitsType, JSONObject property)
575 throws JSONException {
576 property.put(TYPE_KEY, ARRAY_TYPE);
577 property.put(MIN_ITEMS, 0);
578 property.put(UNIQUE_ITEMS_KEY, true);
579 JSONArray enumValues = new JSONArray();
581 List<Bit> bits = bitsType.getBits();
582 for (Bit bit : bits) {
583 enumValues.put(bit.getName());
585 JSONObject itemsValue = new JSONObject();
586 itemsValue.put(ENUM, enumValues);
587 property.put(ITEMS_KEY, itemsValue);
594 * @throws JSONException
596 private void processUnionType(UnionTypeDefinition unionType, JSONObject property)
597 throws JSONException {
599 StringBuilder type = new StringBuilder();
600 for (TypeDefinition<?> typeDef : unionType.getTypes() ) {
601 if( type.length() > 0 ){
602 type.append( " or " );
604 type.append(YANG_TYPE_TO_JSON_TYPE_MAPPING.get(typeDef.getClass()));
607 property.put(TYPE_KEY, type );
611 * Helper method to generate a pre-filled JSON schema object.
614 * @throws JSONException
616 private JSONObject getSchemaTemplate() throws JSONException {
617 JSONObject schemaJSON = new JSONObject();
618 schemaJSON.put(SCHEMA_KEY, SCHEMA_URL);