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.apache.commons.lang3.BooleanUtils;
19 import org.json.JSONArray;
20 import org.json.JSONException;
21 import org.json.JSONObject;
22 import org.opendaylight.controller.sal.rest.doc.model.builder.OperationBuilder;
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.ChoiceNode;
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.DataSchemaNode;
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";
90 private static final Map<Class<? extends TypeDefinition<?>>, String> YANG_TYPE_TO_JSON_TYPE_MAPPING;
93 Map<Class<? extends TypeDefinition<?>>, String> tempMap1 = new HashMap<Class<? extends TypeDefinition<?>>, String>(
95 tempMap1.put(StringType.class, STRING);
96 tempMap1.put(BooleanType.class, BOOLEAN);
97 tempMap1.put(Int8.class, INTEGER);
98 tempMap1.put(Int16.class, INTEGER);
99 tempMap1.put(Int32.class, INTEGER);
100 tempMap1.put(Int64.class, INTEGER);
101 tempMap1.put(Uint16.class, INTEGER);
102 tempMap1.put(Uint32.class, INTEGER);
103 tempMap1.put(Uint64.class, INTEGER);
104 tempMap1.put(Uint8.class, INTEGER);
105 tempMap1.put(Decimal64.class, NUMBER);
106 tempMap1.put(EnumerationType.class, ENUM);
109 YANG_TYPE_TO_JSON_TYPE_MAPPING = Collections.unmodifiableMap(tempMap1);
112 public ModelGenerator() {
115 public JSONObject convertToJsonSchema(Module module) throws IOException, JSONException {
116 JSONObject models = new JSONObject();
117 processContainers(module, models);
118 processRPCs(module, models);
122 private void processContainers(Module module, JSONObject models) throws IOException,
125 String moduleName = module.getName();
126 Set<DataSchemaNode> childNodes = module.getChildNodes();
128 for (DataSchemaNode childNode : childNodes) {
129 JSONObject configModuleJSON = null;
130 JSONObject operationalModuleJSON = null;
132 String childNodeName = childNode.getQName().getLocalName();
134 * For every container in the module
136 if (childNode instanceof ContainerSchemaNode) {
137 configModuleJSON = processContainer((ContainerSchemaNode) childNode, moduleName,
139 operationalModuleJSON = processContainer((ContainerSchemaNode) childNode,
140 moduleName, true, models, false);
143 if (configModuleJSON != null) {
144 _logger.debug("Adding model for [{}]", OperationBuilder.CONFIG + childNodeName);
145 configModuleJSON.put("id", OperationBuilder.CONFIG + childNodeName);
146 models.put(OperationBuilder.CONFIG + childNodeName, configModuleJSON);
148 if (operationalModuleJSON != null) {
149 _logger.debug("Adding model for [{}]", OperationBuilder.OPERATIONAL + childNodeName);
150 operationalModuleJSON.put("id", OperationBuilder.OPERATIONAL + childNodeName);
151 models.put(OperationBuilder.OPERATIONAL + childNodeName, operationalModuleJSON);
158 * Process the RPCs for a Module Spits out a file each of the name
159 * <rpcName>-input.json and <rpcName>-output.json for each RPC that contains
160 * input & output elements
163 * @throws JSONException
164 * @throws IOException
166 private void processRPCs(Module module, JSONObject models) throws JSONException, IOException {
168 Set<RpcDefinition> rpcs = module.getRpcs();
169 String moduleName = module.getName();
170 for (RpcDefinition rpc : rpcs) {
172 ContainerSchemaNode input = rpc.getInput();
174 JSONObject inputJSON = processContainer(input, moduleName, true, models);
175 String filename = "(" + rpc.getQName().getLocalName() + ")input";
176 inputJSON.put("id", filename);
177 // writeToFile(filename, inputJSON.toString(2), moduleName);
178 models.put(filename, inputJSON);
181 ContainerSchemaNode output = rpc.getOutput();
182 if (output != null) {
183 JSONObject outputJSON = processContainer(output, moduleName, true, models);
184 String filename = "(" + rpc.getQName().getLocalName() + ")output";
185 outputJSON.put("id", filename);
186 models.put(filename, outputJSON);
192 * Processes the container node and populates the moduleJSON
197 * @throws JSONException
198 * @throws IOException
200 private JSONObject processContainer(ContainerSchemaNode container, String moduleName,
201 boolean addSchemaStmt, JSONObject models) throws JSONException, IOException {
202 return processContainer(container, moduleName, addSchemaStmt, models, (Boolean) null);
205 private JSONObject processContainer(ContainerSchemaNode container, String moduleName,
206 boolean addSchemaStmt, JSONObject models, Boolean isConfig) throws JSONException,
208 JSONObject moduleJSON = getSchemaTemplate();
210 moduleJSON = getSchemaTemplate();
212 moduleJSON = new JSONObject();
214 moduleJSON.put(TYPE_KEY, OBJECT_TYPE);
216 String containerDescription = container.getDescription();
217 moduleJSON.put(DESCRIPTION_KEY, containerDescription);
219 Set<DataSchemaNode> containerChildren = container.getChildNodes();
220 JSONObject properties = processChildren(containerChildren, moduleName, models, isConfig);
221 moduleJSON.put(PROPERTIES_KEY, properties);
225 private JSONObject processChildren(Set<DataSchemaNode> nodes, String moduleName,
226 JSONObject models) throws JSONException, IOException {
227 return processChildren(nodes, moduleName, models, null);
231 * Processes the nodes
237 * @throws JSONException
238 * @throws IOException
240 private JSONObject processChildren(Set<DataSchemaNode> nodes, String moduleName,
241 JSONObject models, Boolean isConfig) throws JSONException, IOException {
243 JSONObject properties = new JSONObject();
245 for (DataSchemaNode node : nodes) {
246 if (isConfig == null || node.isConfiguration() == isConfig) {
248 String name = node.getQName().getLocalName();
249 JSONObject property = null;
250 if (node instanceof LeafSchemaNode) {
251 property = processLeafNode((LeafSchemaNode) node);
252 } else if (node instanceof ListSchemaNode) {
253 property = processListSchemaNode((ListSchemaNode) node, moduleName, models, isConfig);
255 } else if (node instanceof LeafListSchemaNode) {
256 property = processLeafListNode((LeafListSchemaNode) node);
258 } else if (node instanceof ChoiceNode) {
259 property = processChoiceNode((ChoiceNode) node, moduleName, models);
261 } else if (node instanceof AnyXmlSchemaNode) {
262 property = processAnyXMLNode((AnyXmlSchemaNode) node);
264 } else if (node instanceof ContainerSchemaNode) {
265 property = processContainer((ContainerSchemaNode) node, moduleName, false,
269 throw new IllegalArgumentException("Unknown DataSchemaNode type: "
273 property.putOpt(DESCRIPTION_KEY, node.getDescription());
274 properties.put(name, property);
283 * @throws JSONException
285 private JSONObject processLeafListNode(LeafListSchemaNode listNode) throws JSONException {
286 JSONObject props = new JSONObject();
287 props.put(TYPE_KEY, ARRAY_TYPE);
289 JSONObject itemsVal = new JSONObject();
290 processTypeDef(listNode.getType(), itemsVal);
291 props.put(ITEMS_KEY, itemsVal);
293 ConstraintDefinition constraints = listNode.getConstraints();
294 processConstraints(constraints, props);
303 * @throws JSONException
304 * @throws IOException
306 private JSONObject processChoiceNode(ChoiceNode choiceNode, String moduleName, JSONObject models)
307 throws JSONException, IOException {
309 Set<ChoiceCaseNode> cases = choiceNode.getCases();
311 JSONArray choiceProps = new JSONArray();
312 for (ChoiceCaseNode choiceCase : cases) {
313 String choiceName = choiceCase.getQName().getLocalName();
314 JSONObject choiceProp = processChildren(choiceCase.getChildNodes(), moduleName, models);
315 JSONObject choiceObj = new JSONObject();
316 choiceObj.put(choiceName, choiceProp);
317 choiceObj.put(TYPE_KEY, OBJECT_TYPE);
318 choiceProps.put(choiceObj);
321 JSONObject oneOfProps = new JSONObject();
322 oneOfProps.put(ONE_OF_KEY, choiceProps);
323 oneOfProps.put(TYPE_KEY, OBJECT_TYPE);
332 * @throws JSONException
334 private void processConstraints(ConstraintDefinition constraints, JSONObject props)
335 throws JSONException {
336 boolean isMandatory = constraints.isMandatory();
337 props.put(REQUIRED_KEY, isMandatory);
339 Integer minElements = constraints.getMinElements();
340 Integer maxElements = constraints.getMaxElements();
341 if (minElements != null) {
342 props.put(MIN_ITEMS, minElements);
344 if (maxElements != null) {
345 props.put(MAX_ITEMS, maxElements);
350 * Parses a ListSchema node.
352 * Due to a limitation of the RAML--->JAX-RS tool, sub-properties must be in
353 * a separate JSON schema file. Hence, we have to write some properties to a
354 * new file, while continuing to process the rest.
360 * @throws JSONException
361 * @throws IOException
363 private JSONObject processListSchemaNode(ListSchemaNode listNode, String moduleName,
364 JSONObject models, Boolean isConfig) throws JSONException, IOException {
366 Set<DataSchemaNode> listChildren = listNode.getChildNodes();
367 String fileName = (BooleanUtils.isNotFalse(isConfig)?OperationBuilder.CONFIG:OperationBuilder.OPERATIONAL) +
368 listNode.getQName().getLocalName();
370 JSONObject childSchemaProperties = processChildren(listChildren, moduleName, models);
371 JSONObject childSchema = getSchemaTemplate();
372 childSchema.put(TYPE_KEY, OBJECT_TYPE);
373 childSchema.put(PROPERTIES_KEY, childSchemaProperties);
376 * Due to a limitation of the RAML--->JAX-RS tool, sub-properties must
377 * be in a separate JSON schema file. Hence, we have to write some
378 * properties to a new file, while continuing to process the rest.
380 // writeToFile(fileName, childSchema.toString(2), moduleName);
381 childSchema.put("id", fileName);
382 models.put(fileName, childSchema);
384 JSONObject listNodeProperties = new JSONObject();
385 listNodeProperties.put(TYPE_KEY, ARRAY_TYPE);
387 JSONObject items = new JSONObject();
388 items.put(REF_KEY, fileName);
389 listNodeProperties.put(ITEMS_KEY, items);
391 return listNodeProperties;
399 * @throws JSONException
401 private JSONObject processLeafNode(LeafSchemaNode leafNode) throws JSONException {
402 JSONObject property = new JSONObject();
404 String leafDescription = leafNode.getDescription();
405 property.put(DESCRIPTION_KEY, leafDescription);
407 processConstraints(leafNode.getConstraints(), property);
408 processTypeDef(leafNode.getType(), property);
417 * @throws JSONException
419 private JSONObject processAnyXMLNode(AnyXmlSchemaNode leafNode) throws JSONException {
420 JSONObject property = new JSONObject();
422 String leafDescription = leafNode.getDescription();
423 property.put(DESCRIPTION_KEY, leafDescription);
425 processConstraints(leafNode.getConstraints(), property);
432 * @throws JSONException
434 private void processTypeDef(TypeDefinition<?> leafTypeDef, JSONObject property)
435 throws JSONException {
437 if (leafTypeDef instanceof ExtendedType) {
438 processExtendedType(leafTypeDef, property);
439 } else if (leafTypeDef instanceof EnumerationType) {
440 processEnumType((EnumerationType) leafTypeDef, property);
442 } else if (leafTypeDef instanceof BitsTypeDefinition) {
443 processBitsType((BitsTypeDefinition) leafTypeDef, property);
445 } else if (leafTypeDef instanceof UnionTypeDefinition) {
446 processUnionType((UnionTypeDefinition) leafTypeDef, property);
448 } else if (leafTypeDef instanceof IdentityrefTypeDefinition) {
449 property.putOpt(TYPE_KEY, "object");
450 } else if (leafTypeDef instanceof BinaryTypeDefinition) {
451 processBinaryType((BinaryTypeDefinition) leafTypeDef, property);
453 // System.out.println("In else: " + leafTypeDef.getClass());
454 String jsonType = YANG_TYPE_TO_JSON_TYPE_MAPPING.get(leafTypeDef.getClass());
455 if (jsonType == null) {
458 property.putOpt(TYPE_KEY, jsonType);
466 * @throws JSONException
468 private void processExtendedType(TypeDefinition<?> leafTypeDef, JSONObject property)
469 throws JSONException {
470 Object leafBaseType = leafTypeDef.getBaseType();
471 if (leafBaseType instanceof ExtendedType) {
472 // recursively process an extended type until we hit a base type
473 processExtendedType((TypeDefinition<?>) leafBaseType, property);
475 List<LengthConstraint> lengthConstraints = ((ExtendedType) leafTypeDef)
476 .getLengthConstraints();
477 for (LengthConstraint lengthConstraint : lengthConstraints) {
478 Number min = lengthConstraint.getMin();
479 Number max = lengthConstraint.getMax();
480 property.putOpt(MIN_LENGTH_KEY, min);
481 property.putOpt(MAX_LENGTH_KEY, max);
483 String jsonType = YANG_TYPE_TO_JSON_TYPE_MAPPING.get(leafBaseType.getClass());
484 property.putOpt(TYPE_KEY, jsonType);
492 private void processBinaryType(BinaryTypeDefinition binaryType, JSONObject property)
493 throws JSONException {
494 property.put(TYPE_KEY, STRING);
495 JSONObject media = new JSONObject();
496 media.put(BINARY_ENCODING_KEY, BASE_64);
497 property.put(MEDIA_KEY, media);
502 * @param enumLeafType
504 * @throws JSONException
506 private void processEnumType(EnumerationType enumLeafType, JSONObject property)
507 throws JSONException {
508 List<EnumPair> enumPairs = enumLeafType.getValues();
509 List<String> enumNames = new ArrayList<String>();
510 for (EnumPair enumPair : enumPairs) {
511 enumNames.add(enumPair.getName());
513 property.putOpt(ENUM, new JSONArray(enumNames));
520 * @throws JSONException
522 private void processBitsType(BitsTypeDefinition bitsType, JSONObject property)
523 throws JSONException {
524 property.put(TYPE_KEY, ARRAY_TYPE);
525 property.put(MIN_ITEMS, 0);
526 property.put(UNIQUE_ITEMS_KEY, true);
527 JSONArray enumValues = new JSONArray();
529 List<Bit> bits = bitsType.getBits();
530 for (Bit bit : bits) {
531 enumValues.put(bit.getName());
533 JSONObject itemsValue = new JSONObject();
534 itemsValue.put(ENUM, enumValues);
535 property.put(ITEMS_KEY, itemsValue);
542 * @throws JSONException
544 private void processUnionType(UnionTypeDefinition unionType, JSONObject property)
545 throws JSONException {
547 StringBuilder type = new StringBuilder();
548 for (TypeDefinition<?> typeDef : unionType.getTypes() ) {
549 if( type.length() > 0 ){
550 type.append( " or " );
552 type.append(YANG_TYPE_TO_JSON_TYPE_MAPPING.get(typeDef.getClass()));
555 property.put(TYPE_KEY, type );
559 * Helper method to generate a pre-filled JSON schema object.
562 * @throws JSONException
564 private JSONObject getSchemaTemplate() throws JSONException {
565 JSONObject schemaJSON = new JSONObject();
566 schemaJSON.put(SCHEMA_KEY, SCHEMA_URL);