Add message to update the schema context of the InMemoryDOMDataStore
[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.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;
55
56 /**
57  * Generates JSON Schema for data defined in Yang
58  */
59 public class ModelGenerator {
60
61     private static final Logger _logger = LoggerFactory.getLogger(ModelGenerator.class);
62
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";
87
88     private static final Map<Class<? extends TypeDefinition<?>>, String> YANG_TYPE_TO_JSON_TYPE_MAPPING;
89
90     static {
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);
104         //TODO: Binary type
105
106         YANG_TYPE_TO_JSON_TYPE_MAPPING = Collections.unmodifiableMap(tempMap1);
107     }
108
109     public ModelGenerator(){
110     }
111
112     public JSONObject convertToJsonSchema(final Module module) throws IOException, JSONException {
113         JSONObject models = new JSONObject();
114         processContainers(module, models);
115         processRPCs(module, models);
116
117         return models;
118     }
119
120
121
122     private void processContainers(final Module module, final JSONObject models) throws IOException, JSONException {
123
124         String moduleName = module.getName();
125         Set<DataSchemaNode> childNodes =  module.getChildNodes();
126
127         for(DataSchemaNode childNode : childNodes){
128             JSONObject moduleJSON=null;
129             String filename = childNode.getQName().getLocalName();
130             /*
131              * For every container in the module
132              */
133             if(childNode instanceof ContainerSchemaNode) {
134                 moduleJSON = processContainer((ContainerSchemaNode)childNode, moduleName, true, models);
135             }
136
137             if(moduleJSON!=null) {
138                 _logger.debug("Adding model for [{}]", filename);
139                 moduleJSON.put("id", filename);
140                 models.put(filename, moduleJSON);
141             }
142         }
143
144     }
145
146
147     /**
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
152      *
153      * @param module
154      * @throws JSONException
155      * @throws IOException
156      */
157     private void processRPCs(final Module module, final JSONObject models) throws JSONException, IOException {
158
159         Set<RpcDefinition> rpcs =  module.getRpcs();
160         String moduleName = module.getName();
161         for(RpcDefinition rpc: rpcs) {
162
163             ContainerSchemaNode input = rpc.getInput();
164             if(input!=null) {
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);
170             }
171
172             ContainerSchemaNode output = rpc.getOutput();
173             if(output!=null) {
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);
178             }
179         }
180     }
181
182
183     /**
184      * Processes the container node and populates the moduleJSON
185      *
186      * @param container
187      * @param moduleName
188      * @throws JSONException
189      * @throws IOException
190      */
191     private JSONObject processContainer(final ContainerSchemaNode container, final String moduleName, final boolean addSchemaStmt, final JSONObject models) throws JSONException, IOException{
192         JSONObject moduleJSON = getSchemaTemplate();
193         if(addSchemaStmt) {
194             moduleJSON = getSchemaTemplate();
195         } else {
196             moduleJSON = new JSONObject();
197         }
198         moduleJSON.put(TYPE_KEY, OBJECT_TYPE);
199
200         String containerDescription = container.getDescription();
201         moduleJSON.put(DESCRIPTION_KEY, containerDescription);
202
203         Set<DataSchemaNode> containerChildren = container.getChildNodes();
204         JSONObject properties = processChildren(containerChildren, moduleName, models);
205         moduleJSON.put(PROPERTIES_KEY, properties);
206         return moduleJSON;
207     }
208
209     /**
210      * Processes the nodes
211      * @param nodes
212      * @param moduleName
213      * @return
214      * @throws JSONException
215      * @throws IOException
216      */
217     private JSONObject processChildren(final Set<DataSchemaNode> nodes, final String moduleName, final JSONObject models) throws JSONException, IOException {
218
219         JSONObject properties = new JSONObject();
220
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);
228
229             } else if (node instanceof LeafListSchemaNode) {
230                 property = processLeafListNode((LeafListSchemaNode)node);
231
232             } else if (node instanceof ChoiceNode) {
233                 property = processChoiceNode((ChoiceNode)node, moduleName, models);
234
235             } else if (node instanceof AnyXmlSchemaNode) {
236                 property = processAnyXMLNode((AnyXmlSchemaNode)node);
237
238             } else if (node instanceof ContainerSchemaNode) {
239                 property = processContainer((ContainerSchemaNode)node, moduleName, false, models);
240
241             } else {
242                 throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass());
243             }
244
245             property.putOpt(DESCRIPTION_KEY, node.getDescription());
246             properties.put(name, property);
247         }
248         return properties;
249     }
250
251     /**
252      *
253      * @param listNode
254      * @throws JSONException
255      */
256     private JSONObject processLeafListNode(final LeafListSchemaNode listNode) throws JSONException {
257         JSONObject props = new JSONObject();
258         props.put(TYPE_KEY, ARRAY_TYPE);
259
260         JSONObject itemsVal = new JSONObject();
261         processTypeDef(listNode.getType(), itemsVal);
262         props.put(ITEMS_KEY, itemsVal);
263
264         ConstraintDefinition constraints = listNode.getConstraints();
265         processConstraints(constraints, props);
266
267         return props;
268     }
269
270     /**
271      *
272      * @param choiceNode
273      * @param moduleName
274      * @throws JSONException
275      * @throws IOException
276      */
277     private JSONObject processChoiceNode(final ChoiceNode choiceNode, final String moduleName, final JSONObject models) throws JSONException, IOException {
278
279         Set<ChoiceCaseNode> cases = choiceNode.getCases();
280
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);
289         }
290
291         JSONObject oneOfProps = new JSONObject();
292         oneOfProps.put(ONE_OF_KEY, choiceProps);
293         oneOfProps.put(TYPE_KEY, OBJECT_TYPE);
294
295         return oneOfProps;
296     }
297
298
299     /**
300      *
301      * @param constraints
302      * @param props
303      * @throws JSONException
304      */
305     private void processConstraints(final ConstraintDefinition constraints, final JSONObject props) throws JSONException {
306         boolean isMandatory = constraints.isMandatory();
307         props.put(REQUIRED_KEY, isMandatory);
308
309         Integer minElements = constraints.getMinElements();
310         Integer maxElements = constraints.getMaxElements();
311         if(minElements !=null) {
312             props.put(MIN_ITEMS, minElements);
313         }
314         if(maxElements !=null) {
315             props.put(MAX_ITEMS, maxElements);
316         }
317     }
318
319     /**
320      * Parses a ListSchema node.
321      *
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.
325      *
326      * @param listNode
327      * @param moduleName
328      * @return
329      * @throws JSONException
330      * @throws IOException
331      */
332     private JSONObject processListSchemaNode(final ListSchemaNode listNode, final String moduleName, final JSONObject models) throws JSONException, IOException {
333
334         Set<DataSchemaNode> listChildren = listNode.getChildNodes();
335         String fileName = listNode.getQName().getLocalName();
336
337         JSONObject childSchemaProperties = processChildren(listChildren, moduleName, models);
338         JSONObject childSchema = getSchemaTemplate();
339         childSchema.put(TYPE_KEY, OBJECT_TYPE);
340         childSchema.put(PROPERTIES_KEY, childSchemaProperties);
341
342         /*
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.
346          */
347         //writeToFile(fileName, childSchema.toString(2), moduleName);
348         childSchema.put("id", fileName);
349         models.put(fileName, childSchema);
350
351
352         JSONObject listNodeProperties = new JSONObject();
353         listNodeProperties.put(TYPE_KEY, ARRAY_TYPE);
354
355         JSONObject items = new JSONObject();
356         items.put(REF_KEY,fileName );
357         listNodeProperties.put(ITEMS_KEY, items);
358
359         return listNodeProperties;
360
361     }
362
363     /**
364      *
365      * @param leafNode
366      * @return
367      * @throws JSONException
368      */
369     private JSONObject processLeafNode(final LeafSchemaNode leafNode) throws JSONException {
370         JSONObject property = new JSONObject();
371
372         String leafDescription = leafNode.getDescription();
373         property.put(DESCRIPTION_KEY, leafDescription);
374
375         processConstraints(leafNode.getConstraints(), property);
376         processTypeDef(leafNode.getType(), property);
377
378         return property;
379     }
380
381     /**
382      *
383      * @param leafNode
384      * @return
385      * @throws JSONException
386      */
387     private JSONObject processAnyXMLNode(final AnyXmlSchemaNode leafNode) throws JSONException {
388         JSONObject property = new JSONObject();
389
390         String leafDescription = leafNode.getDescription();
391         property.put(DESCRIPTION_KEY, leafDescription);
392
393         processConstraints(leafNode.getConstraints(), property);
394
395         return property;
396     }
397
398     /**
399      * @param property
400      * @throws JSONException
401      */
402     private void processTypeDef(final TypeDefinition<?> leafTypeDef, final JSONObject property) throws JSONException {
403
404         if(leafTypeDef instanceof ExtendedType){
405             processExtendedType(leafTypeDef, property);
406         } else if (leafTypeDef instanceof EnumerationType) {
407             processEnumType((EnumerationType)leafTypeDef, property);
408
409         } else if (leafTypeDef instanceof BitsTypeDefinition) {
410             processBitsType((BitsTypeDefinition)leafTypeDef, property);
411
412         } else if (leafTypeDef instanceof UnionTypeDefinition) {
413             processUnionType((UnionTypeDefinition)leafTypeDef, property);
414
415         } else if (leafTypeDef instanceof IdentityrefTypeDefinition) {
416             property.putOpt(TYPE_KEY, "object");
417         } else if (leafTypeDef instanceof BinaryTypeDefinition) {
418             processBinaryType((BinaryTypeDefinition)leafTypeDef, property);
419         } else {
420             //System.out.println("In else: " + leafTypeDef.getClass());
421             String jsonType = YANG_TYPE_TO_JSON_TYPE_MAPPING.get(leafTypeDef.getClass());
422             if(jsonType==null) {
423                 jsonType = "object";
424             }
425             property.putOpt(TYPE_KEY, jsonType);
426         }
427     }
428
429     /**
430      *
431      * @param leafTypeDef
432      * @param property
433      * @throws JSONException
434      */
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);
440         } else {
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);
447             }
448             String jsonType = YANG_TYPE_TO_JSON_TYPE_MAPPING.get(leafBaseType.getClass());
449             property.putOpt(TYPE_KEY,jsonType );
450         }
451
452     }
453
454     /*
455      *
456      */
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);
462     }
463
464     /**
465      *
466      * @param enumLeafType
467      * @param property
468      * @throws JSONException
469      */
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());
475         }
476         property.putOpt(ENUM, new JSONArray(enumNames));
477     }
478
479     /**
480      *
481      * @param bitsType
482      * @param property
483      * @throws JSONException
484      */
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();
490
491         List<Bit> bits = bitsType.getBits();
492         for(Bit bit: bits) {
493             enumValues.put(bit.getName());
494         }
495         JSONObject itemsValue = new JSONObject();
496         itemsValue.put(ENUM, enumValues);
497         property.put(ITEMS_KEY, itemsValue);
498     }
499
500
501     /**
502      *
503      * @param unionType
504      * @param property
505      * @throws JSONException
506      */
507     private void processUnionType(final UnionTypeDefinition unionType, final JSONObject property) throws JSONException{
508
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()));
513         }
514         property.put(TYPE_KEY, unionArray);
515     }
516
517
518     /**
519      * Helper method to generate a pre-filled
520      * JSON schema object.
521      * @return
522      * @throws JSONException
523      */
524     private JSONObject getSchemaTemplate() throws JSONException {
525         JSONObject schemaJSON = new JSONObject();
526         schemaJSON.put(SCHEMA_KEY, SCHEMA_URL);
527
528         return schemaJSON;
529     }
530 }