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.yangtools.yang.model.api.AnyXmlSchemaNode;
22 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
23 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
24 import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
25 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
27 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.Module;
31 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
32 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
33 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
34 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
35 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
36 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
37 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
38 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
39 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
40 import org.opendaylight.yangtools.yang.model.util.BooleanType;
41 import org.opendaylight.yangtools.yang.model.util.Decimal64;
42 import org.opendaylight.yangtools.yang.model.util.EnumerationType;
43 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
44 import org.opendaylight.yangtools.yang.model.util.Int16;
45 import org.opendaylight.yangtools.yang.model.util.Int32;
46 import org.opendaylight.yangtools.yang.model.util.Int64;
47 import org.opendaylight.yangtools.yang.model.util.Int8;
48 import org.opendaylight.yangtools.yang.model.util.StringType;
49 import org.opendaylight.yangtools.yang.model.util.Uint16;
50 import org.opendaylight.yangtools.yang.model.util.Uint32;
51 import org.opendaylight.yangtools.yang.model.util.Uint64;
52 import org.opendaylight.yangtools.yang.model.util.Uint8;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
57 * Generates JSON Schema for data defined in Yang
59 public class ModelGenerator {
61 private static final Logger _logger = 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";
88 private static final Map<Class<? extends TypeDefinition<?>>, String> YANG_TYPE_TO_JSON_TYPE_MAPPING;
91 Map<Class<? extends TypeDefinition<?>>, String> tempMap1 = new HashMap<Class<? extends TypeDefinition<?>>, String>(10);
92 tempMap1.put(StringType.class , STRING);
93 tempMap1.put(BooleanType.class , BOOLEAN);
94 tempMap1.put(Int8.class , INTEGER);
95 tempMap1.put(Int16.class , INTEGER);
96 tempMap1.put(Int32.class , INTEGER);
97 tempMap1.put(Int64.class , INTEGER);
98 tempMap1.put(Uint16.class , INTEGER);
99 tempMap1.put(Uint32.class , INTEGER);
100 tempMap1.put(Uint64.class , INTEGER);
101 tempMap1.put(Uint8.class , INTEGER);
102 tempMap1.put(Decimal64.class , NUMBER);
103 tempMap1.put(EnumerationType.class , ENUM);
106 YANG_TYPE_TO_JSON_TYPE_MAPPING = Collections.unmodifiableMap(tempMap1);
109 public ModelGenerator(){
112 public JSONObject convertToJsonSchema(final Module module) throws IOException, JSONException {
113 JSONObject models = new JSONObject();
114 processContainers(module, models);
115 processRPCs(module, models);
122 private void processContainers(final Module module, final JSONObject models) throws IOException, JSONException {
124 String moduleName = module.getName();
125 Set<DataSchemaNode> childNodes = module.getChildNodes();
127 for(DataSchemaNode childNode : childNodes){
128 JSONObject moduleJSON=null;
129 String filename = childNode.getQName().getLocalName();
131 * For every container in the module
133 if(childNode instanceof ContainerSchemaNode) {
134 moduleJSON = processContainer((ContainerSchemaNode)childNode, moduleName, true, models);
137 if(moduleJSON!=null) {
138 _logger.debug("Adding model for [{}]", filename);
139 moduleJSON.put("id", filename);
140 models.put(filename, moduleJSON);
148 * Process the RPCs for a Module
149 * Spits out a file each of the name <rpcName>-input.json
150 * and <rpcName>-output.json for each RPC that contains
151 * input & output elements
154 * @throws JSONException
155 * @throws IOException
157 private void processRPCs(final Module module, final JSONObject models) throws JSONException, IOException {
159 Set<RpcDefinition> rpcs = module.getRpcs();
160 String moduleName = module.getName();
161 for(RpcDefinition rpc: rpcs) {
163 ContainerSchemaNode input = rpc.getInput();
165 JSONObject inputJSON = processContainer(input, moduleName, true, models);
166 String filename = rpc.getQName().getLocalName() + "-input";
167 inputJSON.put("id", filename);
168 //writeToFile(filename, inputJSON.toString(2), moduleName);
169 models.put(filename, inputJSON);
172 ContainerSchemaNode output = rpc.getOutput();
174 JSONObject outputJSON = processContainer(output, moduleName, true, models);
175 String filename = rpc.getQName().getLocalName() + "-output";
176 outputJSON.put("id", filename);
177 models.put(filename, outputJSON);
184 * Processes the container node and populates the moduleJSON
188 * @throws JSONException
189 * @throws IOException
191 private JSONObject processContainer(final ContainerSchemaNode container, final String moduleName, final boolean addSchemaStmt, final JSONObject models) throws JSONException, IOException{
192 JSONObject moduleJSON = getSchemaTemplate();
194 moduleJSON = getSchemaTemplate();
196 moduleJSON = new JSONObject();
198 moduleJSON.put(TYPE_KEY, OBJECT_TYPE);
200 String containerDescription = container.getDescription();
201 moduleJSON.put(DESCRIPTION_KEY, containerDescription);
203 Set<DataSchemaNode> containerChildren = container.getChildNodes();
204 JSONObject properties = processChildren(containerChildren, moduleName, models);
205 moduleJSON.put(PROPERTIES_KEY, properties);
210 * Processes the nodes
214 * @throws JSONException
215 * @throws IOException
217 private JSONObject processChildren(final Set<DataSchemaNode> nodes, final String moduleName, final JSONObject models) throws JSONException, IOException {
219 JSONObject properties = new JSONObject();
221 for(DataSchemaNode node : nodes){
222 String name = node.getQName().getLocalName();
223 JSONObject property = null;
224 if(node instanceof LeafSchemaNode) {
225 property = processLeafNode((LeafSchemaNode)node);
226 } else if (node instanceof ListSchemaNode) {
227 property = processListSchemaNode((ListSchemaNode)node, moduleName, models);
229 } else if (node instanceof LeafListSchemaNode) {
230 property = processLeafListNode((LeafListSchemaNode)node);
232 } else if (node instanceof ChoiceNode) {
233 property = processChoiceNode((ChoiceNode)node, moduleName, models);
235 } else if (node instanceof AnyXmlSchemaNode) {
236 property = processAnyXMLNode((AnyXmlSchemaNode)node);
238 } else if (node instanceof ContainerSchemaNode) {
239 property = processContainer((ContainerSchemaNode)node, moduleName, false, models);
242 throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass());
245 property.putOpt(DESCRIPTION_KEY, node.getDescription());
246 properties.put(name, property);
254 * @throws JSONException
256 private JSONObject processLeafListNode(final LeafListSchemaNode listNode) throws JSONException {
257 JSONObject props = new JSONObject();
258 props.put(TYPE_KEY, ARRAY_TYPE);
260 JSONObject itemsVal = new JSONObject();
261 processTypeDef(listNode.getType(), itemsVal);
262 props.put(ITEMS_KEY, itemsVal);
264 ConstraintDefinition constraints = listNode.getConstraints();
265 processConstraints(constraints, props);
274 * @throws JSONException
275 * @throws IOException
277 private JSONObject processChoiceNode(final ChoiceNode choiceNode, final String moduleName, final JSONObject models) throws JSONException, IOException {
279 Set<ChoiceCaseNode> cases = choiceNode.getCases();
281 JSONArray choiceProps = new JSONArray();
282 for(ChoiceCaseNode choiceCase: cases) {
283 String choiceName = choiceCase.getQName().getLocalName();
284 JSONObject choiceProp = processChildren(choiceCase.getChildNodes(), moduleName, models);
285 JSONObject choiceObj = new JSONObject();
286 choiceObj.put(choiceName, choiceProp);
287 choiceObj.put(TYPE_KEY, OBJECT_TYPE);
288 choiceProps.put(choiceObj);
291 JSONObject oneOfProps = new JSONObject();
292 oneOfProps.put(ONE_OF_KEY, choiceProps);
293 oneOfProps.put(TYPE_KEY, OBJECT_TYPE);
303 * @throws JSONException
305 private void processConstraints(final ConstraintDefinition constraints, final JSONObject props) throws JSONException {
306 boolean isMandatory = constraints.isMandatory();
307 props.put(REQUIRED_KEY, isMandatory);
309 Integer minElements = constraints.getMinElements();
310 Integer maxElements = constraints.getMaxElements();
311 if(minElements !=null) {
312 props.put(MIN_ITEMS, minElements);
314 if(maxElements !=null) {
315 props.put(MAX_ITEMS, maxElements);
320 * Parses a ListSchema node.
322 * Due to a limitation of the RAML--->JAX-RS tool, sub-properties
323 * must be in a separate JSON schema file. Hence, we have to write
324 * some properties to a new file, while continuing to process the rest.
329 * @throws JSONException
330 * @throws IOException
332 private JSONObject processListSchemaNode(final ListSchemaNode listNode, final String moduleName, final JSONObject models) throws JSONException, IOException {
334 Set<DataSchemaNode> listChildren = listNode.getChildNodes();
335 String fileName = listNode.getQName().getLocalName();
337 JSONObject childSchemaProperties = processChildren(listChildren, moduleName, models);
338 JSONObject childSchema = getSchemaTemplate();
339 childSchema.put(TYPE_KEY, OBJECT_TYPE);
340 childSchema.put(PROPERTIES_KEY, childSchemaProperties);
343 * Due to a limitation of the RAML--->JAX-RS tool, sub-properties
344 * must be in a separate JSON schema file. Hence, we have to write
345 * some properties to a new file, while continuing to process the rest.
347 //writeToFile(fileName, childSchema.toString(2), moduleName);
348 childSchema.put("id", fileName);
349 models.put(fileName, childSchema);
352 JSONObject listNodeProperties = new JSONObject();
353 listNodeProperties.put(TYPE_KEY, ARRAY_TYPE);
355 JSONObject items = new JSONObject();
356 items.put(REF_KEY,fileName );
357 listNodeProperties.put(ITEMS_KEY, items);
359 return listNodeProperties;
367 * @throws JSONException
369 private JSONObject processLeafNode(final LeafSchemaNode leafNode) throws JSONException {
370 JSONObject property = new JSONObject();
372 String leafDescription = leafNode.getDescription();
373 property.put(DESCRIPTION_KEY, leafDescription);
375 processConstraints(leafNode.getConstraints(), property);
376 processTypeDef(leafNode.getType(), property);
385 * @throws JSONException
387 private JSONObject processAnyXMLNode(final AnyXmlSchemaNode leafNode) throws JSONException {
388 JSONObject property = new JSONObject();
390 String leafDescription = leafNode.getDescription();
391 property.put(DESCRIPTION_KEY, leafDescription);
393 processConstraints(leafNode.getConstraints(), property);
400 * @throws JSONException
402 private void processTypeDef(final TypeDefinition<?> leafTypeDef, final JSONObject property) throws JSONException {
404 if(leafTypeDef instanceof ExtendedType){
405 processExtendedType(leafTypeDef, property);
406 } else if (leafTypeDef instanceof EnumerationType) {
407 processEnumType((EnumerationType)leafTypeDef, property);
409 } else if (leafTypeDef instanceof BitsTypeDefinition) {
410 processBitsType((BitsTypeDefinition)leafTypeDef, property);
412 } else if (leafTypeDef instanceof UnionTypeDefinition) {
413 processUnionType((UnionTypeDefinition)leafTypeDef, property);
415 } else if (leafTypeDef instanceof IdentityrefTypeDefinition) {
416 property.putOpt(TYPE_KEY, "object");
417 } else if (leafTypeDef instanceof BinaryTypeDefinition) {
418 processBinaryType((BinaryTypeDefinition)leafTypeDef, property);
420 //System.out.println("In else: " + leafTypeDef.getClass());
421 String jsonType = YANG_TYPE_TO_JSON_TYPE_MAPPING.get(leafTypeDef.getClass());
425 property.putOpt(TYPE_KEY, jsonType);
433 * @throws JSONException
435 private void processExtendedType(final TypeDefinition<?> leafTypeDef, final JSONObject property) throws JSONException {
436 Object leafBaseType = leafTypeDef.getBaseType();
437 if(leafBaseType instanceof ExtendedType){
438 //recursively process an extended type until we hit a base type
439 processExtendedType((TypeDefinition<?>)leafBaseType, property);
441 List<LengthConstraint> lengthConstraints = ((ExtendedType) leafTypeDef).getLengthConstraints();
442 for(LengthConstraint lengthConstraint: lengthConstraints) {
443 Number min = lengthConstraint.getMin();
444 Number max = lengthConstraint.getMax();
445 property.putOpt(MIN_LENGTH_KEY, min);
446 property.putOpt(MAX_LENGTH_KEY, max);
448 String jsonType = YANG_TYPE_TO_JSON_TYPE_MAPPING.get(leafBaseType.getClass());
449 property.putOpt(TYPE_KEY,jsonType );
457 private void processBinaryType(final BinaryTypeDefinition binaryType, final JSONObject property) throws JSONException {
458 property.put(TYPE_KEY, STRING);
459 JSONObject media = new JSONObject();
460 media.put(BINARY_ENCODING_KEY, BASE_64);
461 property.put(MEDIA_KEY, media);
466 * @param enumLeafType
468 * @throws JSONException
470 private void processEnumType(final EnumerationType enumLeafType, final JSONObject property) throws JSONException {
471 List<EnumPair> enumPairs = enumLeafType.getValues();
472 List<String> enumNames = new ArrayList<String>();
473 for(EnumPair enumPair: enumPairs) {
474 enumNames.add(enumPair.getName());
476 property.putOpt(ENUM, new JSONArray(enumNames));
483 * @throws JSONException
485 private void processBitsType(final BitsTypeDefinition bitsType, final JSONObject property) throws JSONException{
486 property.put(TYPE_KEY, ARRAY_TYPE);
487 property.put(MIN_ITEMS, 0);
488 property.put(UNIQUE_ITEMS_KEY, true);
489 JSONArray enumValues = new JSONArray();
491 List<Bit> bits = bitsType.getBits();
493 enumValues.put(bit.getName());
495 JSONObject itemsValue = new JSONObject();
496 itemsValue.put(ENUM, enumValues);
497 property.put(ITEMS_KEY, itemsValue);
505 * @throws JSONException
507 private void processUnionType(final UnionTypeDefinition unionType, final JSONObject property) throws JSONException{
509 List<TypeDefinition<?>> unionTypes = unionType.getTypes();
510 JSONArray unionArray = new JSONArray();
511 for(TypeDefinition<?> typeDef: unionTypes) {
512 unionArray.put(YANG_TYPE_TO_JSON_TYPE_MAPPING.get(typeDef.getClass()));
514 property.put(TYPE_KEY, unionArray);
519 * Helper method to generate a pre-filled
520 * JSON schema object.
522 * @throws JSONException
524 private JSONObject getSchemaTemplate() throws JSONException {
525 JSONObject schemaJSON = new JSONObject();
526 schemaJSON.put(SCHEMA_KEY, SCHEMA_URL);