Bug 1290 - Swagger Documentation is failing to load - java script
[controller.git] / opendaylight / md-sal / sal-rest-docgen / src / main / java / org / opendaylight / controller / sal / rest / doc / impl / ModelGenerator.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.sal.rest.doc.impl;
9
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;
15 import java.util.Map;
16 import java.util.Set;
17
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;
57
58 /**
59  * Generates JSON Schema for data defined in Yang
60  */
61 public class ModelGenerator {
62
63     private static Logger _logger = LoggerFactory.getLogger(ModelGenerator.class);
64
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
90     private static final Map<Class<? extends TypeDefinition<?>>, String> YANG_TYPE_TO_JSON_TYPE_MAPPING;
91
92     static {
93         Map<Class<? extends TypeDefinition<?>>, String> tempMap1 = new HashMap<Class<? extends TypeDefinition<?>>, String>(
94                 10);
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);
107         // TODO: Binary type
108
109         YANG_TYPE_TO_JSON_TYPE_MAPPING = Collections.unmodifiableMap(tempMap1);
110     }
111
112     public ModelGenerator() {
113     }
114
115     public JSONObject convertToJsonSchema(Module module) throws IOException, JSONException {
116         JSONObject models = new JSONObject();
117         processContainers(module, models);
118         processRPCs(module, models);
119         return models;
120     }
121
122     private void processContainers(Module module, JSONObject models) throws IOException,
123             JSONException {
124
125         String moduleName = module.getName();
126         Set<DataSchemaNode> childNodes = module.getChildNodes();
127
128         for (DataSchemaNode childNode : childNodes) {
129             JSONObject configModuleJSON = null;
130             JSONObject operationalModuleJSON = null;
131
132             String childNodeName = childNode.getQName().getLocalName();
133             /*
134              * For every container in the module
135              */
136             if (childNode instanceof ContainerSchemaNode) {
137                 configModuleJSON = processContainer((ContainerSchemaNode) childNode, moduleName,
138                         true, models, true);
139                 operationalModuleJSON = processContainer((ContainerSchemaNode) childNode,
140                         moduleName, true, models, false);
141             }
142
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);
147             }
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);
152             }
153         }
154
155     }
156
157     /**
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
161      *
162      * @param module
163      * @throws JSONException
164      * @throws IOException
165      */
166     private void processRPCs(Module module, JSONObject models) throws JSONException, IOException {
167
168         Set<RpcDefinition> rpcs = module.getRpcs();
169         String moduleName = module.getName();
170         for (RpcDefinition rpc : rpcs) {
171
172             ContainerSchemaNode input = rpc.getInput();
173             if (input != null) {
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);
179             }
180
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);
187             }
188         }
189     }
190
191     /**
192      * Processes the container node and populates the moduleJSON
193      *
194      * @param container
195      * @param moduleName
196      * @param isConfig
197      * @throws JSONException
198      * @throws IOException
199      */
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);
203     }
204
205     private JSONObject processContainer(ContainerSchemaNode container, String moduleName,
206             boolean addSchemaStmt, JSONObject models, Boolean isConfig) throws JSONException,
207             IOException {
208         JSONObject moduleJSON = getSchemaTemplate();
209         if (addSchemaStmt) {
210             moduleJSON = getSchemaTemplate();
211         } else {
212             moduleJSON = new JSONObject();
213         }
214         moduleJSON.put(TYPE_KEY, OBJECT_TYPE);
215
216         String containerDescription = container.getDescription();
217         moduleJSON.put(DESCRIPTION_KEY, containerDescription);
218
219         Set<DataSchemaNode> containerChildren = container.getChildNodes();
220         JSONObject properties = processChildren(containerChildren, moduleName, models, isConfig);
221         moduleJSON.put(PROPERTIES_KEY, properties);
222         return moduleJSON;
223     }
224
225     private JSONObject processChildren(Set<DataSchemaNode> nodes, String moduleName,
226             JSONObject models) throws JSONException, IOException {
227         return processChildren(nodes, moduleName, models, null);
228     }
229
230     /**
231      * Processes the nodes
232      *
233      * @param nodes
234      * @param moduleName
235      * @param isConfig
236      * @return
237      * @throws JSONException
238      * @throws IOException
239      */
240     private JSONObject processChildren(Set<DataSchemaNode> nodes, String moduleName,
241             JSONObject models, Boolean isConfig) throws JSONException, IOException {
242
243         JSONObject properties = new JSONObject();
244
245         for (DataSchemaNode node : nodes) {
246             if (isConfig == null || node.isConfiguration() == isConfig) {
247
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);
254
255                 } else if (node instanceof LeafListSchemaNode) {
256                     property = processLeafListNode((LeafListSchemaNode) node);
257
258                 } else if (node instanceof ChoiceNode) {
259                     property = processChoiceNode((ChoiceNode) node, moduleName, models);
260
261                 } else if (node instanceof AnyXmlSchemaNode) {
262                     property = processAnyXMLNode((AnyXmlSchemaNode) node);
263
264                 } else if (node instanceof ContainerSchemaNode) {
265                     property = processContainer((ContainerSchemaNode) node, moduleName, false,
266                             models, isConfig);
267
268                 } else {
269                     throw new IllegalArgumentException("Unknown DataSchemaNode type: "
270                             + node.getClass());
271                 }
272
273                 property.putOpt(DESCRIPTION_KEY, node.getDescription());
274                 properties.put(name, property);
275             }
276         }
277         return properties;
278     }
279
280     /**
281      *
282      * @param listNode
283      * @throws JSONException
284      */
285     private JSONObject processLeafListNode(LeafListSchemaNode listNode) throws JSONException {
286         JSONObject props = new JSONObject();
287         props.put(TYPE_KEY, ARRAY_TYPE);
288
289         JSONObject itemsVal = new JSONObject();
290         processTypeDef(listNode.getType(), itemsVal);
291         props.put(ITEMS_KEY, itemsVal);
292
293         ConstraintDefinition constraints = listNode.getConstraints();
294         processConstraints(constraints, props);
295
296         return props;
297     }
298
299     /**
300      *
301      * @param choiceNode
302      * @param moduleName
303      * @throws JSONException
304      * @throws IOException
305      */
306     private JSONObject processChoiceNode(ChoiceNode choiceNode, String moduleName, JSONObject models)
307             throws JSONException, IOException {
308
309         Set<ChoiceCaseNode> cases = choiceNode.getCases();
310
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);
319         }
320
321         JSONObject oneOfProps = new JSONObject();
322         oneOfProps.put(ONE_OF_KEY, choiceProps);
323         oneOfProps.put(TYPE_KEY, OBJECT_TYPE);
324
325         return oneOfProps;
326     }
327
328     /**
329      *
330      * @param constraints
331      * @param props
332      * @throws JSONException
333      */
334     private void processConstraints(ConstraintDefinition constraints, JSONObject props)
335             throws JSONException {
336         boolean isMandatory = constraints.isMandatory();
337         props.put(REQUIRED_KEY, isMandatory);
338
339         Integer minElements = constraints.getMinElements();
340         Integer maxElements = constraints.getMaxElements();
341         if (minElements != null) {
342             props.put(MIN_ITEMS, minElements);
343         }
344         if (maxElements != null) {
345             props.put(MAX_ITEMS, maxElements);
346         }
347     }
348
349     /**
350      * Parses a ListSchema node.
351      *
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.
355      *
356      * @param listNode
357      * @param moduleName
358      * @param isConfig
359      * @return
360      * @throws JSONException
361      * @throws IOException
362      */
363     private JSONObject processListSchemaNode(ListSchemaNode listNode, String moduleName,
364             JSONObject models, Boolean isConfig) throws JSONException, IOException {
365
366         Set<DataSchemaNode> listChildren = listNode.getChildNodes();
367         String fileName = (BooleanUtils.isNotFalse(isConfig)?OperationBuilder.CONFIG:OperationBuilder.OPERATIONAL) +
368                                                                 listNode.getQName().getLocalName();
369
370         JSONObject childSchemaProperties = processChildren(listChildren, moduleName, models);
371         JSONObject childSchema = getSchemaTemplate();
372         childSchema.put(TYPE_KEY, OBJECT_TYPE);
373         childSchema.put(PROPERTIES_KEY, childSchemaProperties);
374
375         /*
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.
379          */
380         // writeToFile(fileName, childSchema.toString(2), moduleName);
381         childSchema.put("id", fileName);
382         models.put(fileName, childSchema);
383
384         JSONObject listNodeProperties = new JSONObject();
385         listNodeProperties.put(TYPE_KEY, ARRAY_TYPE);
386
387         JSONObject items = new JSONObject();
388         items.put(REF_KEY, fileName);
389         listNodeProperties.put(ITEMS_KEY, items);
390
391         return listNodeProperties;
392
393     }
394
395     /**
396      *
397      * @param leafNode
398      * @return
399      * @throws JSONException
400      */
401     private JSONObject processLeafNode(LeafSchemaNode leafNode) throws JSONException {
402         JSONObject property = new JSONObject();
403
404         String leafDescription = leafNode.getDescription();
405         property.put(DESCRIPTION_KEY, leafDescription);
406
407         processConstraints(leafNode.getConstraints(), property);
408         processTypeDef(leafNode.getType(), property);
409
410         return property;
411     }
412
413     /**
414      *
415      * @param leafNode
416      * @return
417      * @throws JSONException
418      */
419     private JSONObject processAnyXMLNode(AnyXmlSchemaNode leafNode) throws JSONException {
420         JSONObject property = new JSONObject();
421
422         String leafDescription = leafNode.getDescription();
423         property.put(DESCRIPTION_KEY, leafDescription);
424
425         processConstraints(leafNode.getConstraints(), property);
426
427         return property;
428     }
429
430     /**
431      * @param property
432      * @throws JSONException
433      */
434     private void processTypeDef(TypeDefinition<?> leafTypeDef, JSONObject property)
435             throws JSONException {
436
437         if (leafTypeDef instanceof ExtendedType) {
438             processExtendedType(leafTypeDef, property);
439         } else if (leafTypeDef instanceof EnumerationType) {
440             processEnumType((EnumerationType) leafTypeDef, property);
441
442         } else if (leafTypeDef instanceof BitsTypeDefinition) {
443             processBitsType((BitsTypeDefinition) leafTypeDef, property);
444
445         } else if (leafTypeDef instanceof UnionTypeDefinition) {
446             processUnionType((UnionTypeDefinition) leafTypeDef, property);
447
448         } else if (leafTypeDef instanceof IdentityrefTypeDefinition) {
449             property.putOpt(TYPE_KEY, "object");
450         } else if (leafTypeDef instanceof BinaryTypeDefinition) {
451             processBinaryType((BinaryTypeDefinition) leafTypeDef, property);
452         } else {
453             // System.out.println("In else: " + leafTypeDef.getClass());
454             String jsonType = YANG_TYPE_TO_JSON_TYPE_MAPPING.get(leafTypeDef.getClass());
455             if (jsonType == null) {
456                 jsonType = "object";
457             }
458             property.putOpt(TYPE_KEY, jsonType);
459         }
460     }
461
462     /**
463      *
464      * @param leafTypeDef
465      * @param property
466      * @throws JSONException
467      */
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);
474         } else {
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);
482             }
483             String jsonType = YANG_TYPE_TO_JSON_TYPE_MAPPING.get(leafBaseType.getClass());
484             property.putOpt(TYPE_KEY, jsonType);
485         }
486
487     }
488
489     /*
490    *
491    */
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);
498     }
499
500     /**
501      *
502      * @param enumLeafType
503      * @param property
504      * @throws JSONException
505      */
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());
512         }
513         property.putOpt(ENUM, new JSONArray(enumNames));
514     }
515
516     /**
517      *
518      * @param bitsType
519      * @param property
520      * @throws JSONException
521      */
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();
528
529         List<Bit> bits = bitsType.getBits();
530         for (Bit bit : bits) {
531             enumValues.put(bit.getName());
532         }
533         JSONObject itemsValue = new JSONObject();
534         itemsValue.put(ENUM, enumValues);
535         property.put(ITEMS_KEY, itemsValue);
536     }
537
538     /**
539      *
540      * @param unionType
541      * @param property
542      * @throws JSONException
543      */
544     private void processUnionType(UnionTypeDefinition unionType, JSONObject property)
545             throws JSONException {
546
547         StringBuilder type = new StringBuilder();
548         for (TypeDefinition<?> typeDef : unionType.getTypes() ) {
549             if( type.length() > 0 ){
550                 type.append( " or " );
551             }
552             type.append(YANG_TYPE_TO_JSON_TYPE_MAPPING.get(typeDef.getClass()));
553         }
554
555         property.put(TYPE_KEY, type );
556     }
557
558     /**
559      * Helper method to generate a pre-filled JSON schema object.
560      *
561      * @return
562      * @throws JSONException
563      */
564     private JSONObject getSchemaTemplate() throws JSONException {
565         JSONObject schemaJSON = new JSONObject();
566         schemaJSON.put(SCHEMA_KEY, SCHEMA_URL);
567
568         return schemaJSON;
569     }
570 }