BUG-865: Remove reference to ExtendedType
[netconf.git] / restconf / sal-rest-docgen / src / main / java / org / opendaylight / netconf / 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.netconf.sal.rest.doc.impl;
9
10 import static org.opendaylight.netconf.sal.rest.doc.util.RestDocgenUtil.resolveNodesName;
11 import com.google.common.base.Preconditions;
12 import java.io.IOException;
13 import java.util.ArrayList;
14 import java.util.List;
15 import java.util.Set;
16 import javax.annotation.concurrent.NotThreadSafe;
17 import org.json.JSONArray;
18 import org.json.JSONException;
19 import org.json.JSONObject;
20 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder;
21 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Post;
22 import org.opendaylight.yangtools.yang.common.QName;
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.ChoiceSchemaNode;
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.DataNodeContainer;
29 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.Module;
35 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
36 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
37 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
39 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
40 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
41 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
42 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
43 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
44 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
45 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
46 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
47 import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
48 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
49 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
50 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
51 import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 /**
56  * Generates JSON Schema for data defined in YANG.
57  */
58 @NotThreadSafe
59 public class ModelGenerator {
60
61     private static final Logger LOG = 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     private static final String ID_KEY = "id";
88     private static final String SUB_TYPES_KEY = "subTypes";
89
90     private Module topLevelModule;
91
92     public ModelGenerator() {
93     }
94
95     private static String jsonTypeFor(final TypeDefinition<?> type) {
96         if (type instanceof BooleanTypeDefinition) {
97             return BOOLEAN;
98         } else if (type instanceof DecimalTypeDefinition) {
99             return NUMBER;
100         } else if (type instanceof EnumTypeDefinition) {
101             return ENUM;
102         } else if (type instanceof IntegerTypeDefinition) {
103             return INTEGER;
104         } else if (type instanceof UnsignedIntegerTypeDefinition) {
105             return INTEGER;
106         } else if (type instanceof StringTypeDefinition) {
107             return STRING;
108         }
109
110         // TODO: Binary type
111         return null;
112     }
113
114     public JSONObject convertToJsonSchema(final Module module, final SchemaContext schemaContext) throws IOException, JSONException {
115         JSONObject models = new JSONObject();
116         topLevelModule = module;
117         processModules(module, models);
118         processContainersAndLists(module, models, schemaContext);
119         processRPCs(module, models, schemaContext);
120         processIdentities(module, models);
121         return models;
122     }
123
124     private void processModules(final Module module, final JSONObject models) throws JSONException {
125         createConcreteModelForPost(models, module.getName() + BaseYangSwaggerGenerator.MODULE_NAME_SUFFIX, createPropertiesForPost(module));
126     }
127
128     private void processContainersAndLists(final Module module, final JSONObject models, final SchemaContext schemaContext)
129             throws IOException, JSONException {
130
131         String moduleName = module.getName();
132
133         for (DataSchemaNode childNode : module.getChildNodes()) {
134             // For every container and list in the module
135             if (childNode instanceof ContainerSchemaNode || childNode instanceof ListSchemaNode) {
136                 processDataNodeContainer((DataNodeContainer) childNode, moduleName, models, true, schemaContext);
137                 processDataNodeContainer((DataNodeContainer) childNode, moduleName, models, false, schemaContext);
138             }
139         }
140
141     }
142
143     /**
144      * Process the RPCs for a Module Spits out a file each of the name <rpcName>-input.json and <rpcName>-output.json
145      * for each RPC that contains input & output elements
146      *
147      * @param module
148      * @throws JSONException
149      * @throws IOException
150      */
151     private void processRPCs(final Module module, final JSONObject models, final SchemaContext schemaContext) throws JSONException,
152             IOException {
153
154         Set<RpcDefinition> rpcs = module.getRpcs();
155         String moduleName = module.getName();
156         for (RpcDefinition rpc : rpcs) {
157
158             ContainerSchemaNode input = rpc.getInput();
159             if (input != null) {
160                 JSONObject inputJSON = processDataNodeContainer(input, moduleName, models, schemaContext);
161                 String filename = "(" + rpc.getQName().getLocalName() + ")input";
162                 inputJSON.put("id", filename);
163                 // writeToFile(filename, inputJSON.toString(2), moduleName);
164                 models.put(filename, inputJSON);
165             }
166
167             ContainerSchemaNode output = rpc.getOutput();
168             if (output != null) {
169                 JSONObject outputJSON = processDataNodeContainer(output, moduleName, models, schemaContext);
170                 String filename = "(" + rpc.getQName().getLocalName() + ")output";
171                 outputJSON.put("id", filename);
172                 models.put(filename, outputJSON);
173             }
174         }
175     }
176
177     /**
178      * Processes the 'identity' statement in a yang model and maps it to a 'model' in the Swagger JSON spec.
179      *
180      * @param module
181      *            The module from which the identity stmt will be processed
182      * @param models
183      *            The JSONObject in which the parsed identity will be put as a 'model' obj
184      */
185     private static void processIdentities(final Module module, final JSONObject models) throws JSONException {
186
187         String moduleName = module.getName();
188         Set<IdentitySchemaNode> idNodes = module.getIdentities();
189         LOG.debug("Processing Identities for module {} . Found {} identity statements", moduleName, idNodes.size());
190
191         for (IdentitySchemaNode idNode : idNodes) {
192             JSONObject identityObj = new JSONObject();
193             String identityName = idNode.getQName().getLocalName();
194             LOG.debug("Processing Identity: {}", identityName);
195
196             identityObj.put(ID_KEY, identityName);
197             identityObj.put(DESCRIPTION_KEY, idNode.getDescription());
198
199             JSONObject props = new JSONObject();
200             IdentitySchemaNode baseId = idNode.getBaseIdentity();
201
202             if (baseId == null) {
203                 /**
204                  * This is a base identity. So lets see if it has sub types. If it does, then add them to the model
205                  * definition.
206                  */
207                 Set<IdentitySchemaNode> derivedIds = idNode.getDerivedIdentities();
208
209                 if (derivedIds != null) {
210                     JSONArray subTypes = new JSONArray();
211                     for (IdentitySchemaNode derivedId : derivedIds) {
212                         subTypes.put(derivedId.getQName().getLocalName());
213                     }
214                     identityObj.put(SUB_TYPES_KEY, subTypes);
215                 }
216             } else {
217                 /**
218                  * This is a derived entity. Add it's base type & move on.
219                  */
220                 props.put(TYPE_KEY, baseId.getQName().getLocalName());
221             }
222
223             // Add the properties. For a base type, this will be an empty object as required by the Swagger spec.
224             identityObj.put(PROPERTIES_KEY, props);
225             models.put(identityName, identityObj);
226         }
227     }
228
229     /**
230      * Processes the container and list nodes and populates the moduleJSON.
231      */
232     private JSONObject processDataNodeContainer(final DataNodeContainer dataNode, final String moduleName, final JSONObject models,
233             final SchemaContext schemaContext) throws JSONException, IOException {
234         return processDataNodeContainer(dataNode, moduleName, models, true, schemaContext);
235     }
236
237     private JSONObject processDataNodeContainer(final DataNodeContainer dataNode, final String moduleName, final JSONObject models,
238             final boolean isConfig, final SchemaContext schemaContext) throws JSONException, IOException {
239         if (dataNode instanceof ListSchemaNode || dataNode instanceof ContainerSchemaNode) {
240             Preconditions.checkArgument(dataNode instanceof SchemaNode, "Data node should be also schema node");
241             Iterable<DataSchemaNode> containerChildren = dataNode.getChildNodes();
242             JSONObject properties = processChildren(containerChildren, ((SchemaNode) dataNode).getQName(), moduleName,
243                     models, isConfig, schemaContext);
244
245             String nodeName = (isConfig ? OperationBuilder.CONFIG : OperationBuilder.OPERATIONAL)
246                     + ((SchemaNode) dataNode).getQName().getLocalName();
247
248             JSONObject childSchema = getSchemaTemplate();
249             childSchema.put(TYPE_KEY, OBJECT_TYPE);
250             childSchema.put(PROPERTIES_KEY, properties);
251             childSchema.put("id", nodeName);
252             models.put(nodeName, childSchema);
253
254             if (isConfig) {
255                 createConcreteModelForPost(models, ((SchemaNode) dataNode).getQName().getLocalName(),
256                         createPropertiesForPost(dataNode));
257             }
258
259             JSONObject items = new JSONObject();
260             items.put(REF_KEY, nodeName);
261             JSONObject dataNodeProperties = new JSONObject();
262             dataNodeProperties.put(TYPE_KEY, dataNode instanceof ListSchemaNode ? ARRAY_TYPE : OBJECT_TYPE);
263             dataNodeProperties.put(ITEMS_KEY, items);
264
265             return dataNodeProperties;
266         }
267         return null;
268     }
269
270     private static void createConcreteModelForPost(final JSONObject models, final String localName,
271             final JSONObject properties) throws JSONException {
272         String nodePostName = OperationBuilder.CONFIG + localName + Post.METHOD_NAME;
273         JSONObject postSchema = getSchemaTemplate();
274         postSchema.put(TYPE_KEY, OBJECT_TYPE);
275         postSchema.put("id", nodePostName);
276         postSchema.put(PROPERTIES_KEY, properties);
277         models.put(nodePostName, postSchema);
278     }
279
280     private JSONObject createPropertiesForPost(final DataNodeContainer dataNodeContainer) throws JSONException {
281         JSONObject properties = new JSONObject();
282         for (DataSchemaNode childNode : dataNodeContainer.getChildNodes()) {
283             if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
284                 JSONObject items = new JSONObject();
285                 items.put(REF_KEY, "(config)" + childNode.getQName().getLocalName());
286                 JSONObject property = new JSONObject();
287                 property.put(TYPE_KEY, childNode instanceof ListSchemaNode ? ARRAY_TYPE : OBJECT_TYPE);
288                 property.put(ITEMS_KEY, items);
289                 properties.put(childNode.getQName().getLocalName(), property);
290             } else if (childNode instanceof LeafSchemaNode) {
291                 JSONObject property = processLeafNode((LeafSchemaNode)childNode);
292                 properties.put(childNode.getQName().getLocalName(), property);
293             }
294         }
295         return properties;
296     }
297
298     private JSONObject processChildren(final Iterable<DataSchemaNode> nodes, final QName parentQName, final String moduleName,
299             final JSONObject models, final SchemaContext schemaContext) throws JSONException, IOException {
300         return processChildren(nodes, parentQName, moduleName, models, true, schemaContext);
301     }
302
303     /**
304      * Processes the nodes.
305      */
306     private JSONObject processChildren(final Iterable<DataSchemaNode> nodes, final QName parentQName,
307             final String moduleName, final JSONObject models, final boolean isConfig, final SchemaContext schemaContext)
308             throws JSONException, IOException {
309
310         JSONObject properties = new JSONObject();
311
312         for (DataSchemaNode node : nodes) {
313             if (node.isConfiguration() == isConfig) {
314
315                 String name = resolveNodesName(node, topLevelModule, schemaContext);
316                 JSONObject property = null;
317                 if (node instanceof LeafSchemaNode) {
318                     property = processLeafNode((LeafSchemaNode) node);
319                 } else if (node instanceof ListSchemaNode) {
320                     property = processDataNodeContainer((ListSchemaNode) node, moduleName, models, isConfig,
321                             schemaContext);
322
323                 } else if (node instanceof LeafListSchemaNode) {
324                     property = processLeafListNode((LeafListSchemaNode) node);
325
326                 } else if (node instanceof ChoiceSchemaNode) {
327                     property = processChoiceNode((ChoiceSchemaNode) node, moduleName, models, schemaContext);
328
329                 } else if (node instanceof AnyXmlSchemaNode) {
330                     property = processAnyXMLNode((AnyXmlSchemaNode) node);
331
332                 } else if (node instanceof ContainerSchemaNode) {
333                     property = processDataNodeContainer((ContainerSchemaNode) node, moduleName, models, isConfig,
334                             schemaContext);
335
336                 } else {
337                     throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass());
338                 }
339
340                 property.putOpt(DESCRIPTION_KEY, node.getDescription());
341                 properties.put(name, property);
342             }
343         }
344         return properties;
345     }
346
347     private JSONObject processLeafListNode(final LeafListSchemaNode listNode) throws JSONException {
348         JSONObject props = new JSONObject();
349         props.put(TYPE_KEY, ARRAY_TYPE);
350
351         JSONObject itemsVal = new JSONObject();
352         processTypeDef(listNode.getType(), itemsVal);
353         props.put(ITEMS_KEY, itemsVal);
354
355         ConstraintDefinition constraints = listNode.getConstraints();
356         processConstraints(constraints, props);
357
358         return props;
359     }
360
361     private JSONObject processChoiceNode(final ChoiceSchemaNode choiceNode, final String moduleName, final JSONObject models,
362             final SchemaContext schemaContext) throws JSONException, IOException {
363
364         Set<ChoiceCaseNode> cases = choiceNode.getCases();
365
366         JSONArray choiceProps = new JSONArray();
367         for (ChoiceCaseNode choiceCase : cases) {
368             String choiceName = choiceCase.getQName().getLocalName();
369             JSONObject choiceProp = processChildren(choiceCase.getChildNodes(), choiceCase.getQName(), moduleName,
370                     models, schemaContext);
371             JSONObject choiceObj = new JSONObject();
372             choiceObj.put(choiceName, choiceProp);
373             choiceObj.put(TYPE_KEY, OBJECT_TYPE);
374             choiceProps.put(choiceObj);
375         }
376
377         JSONObject oneOfProps = new JSONObject();
378         oneOfProps.put(ONE_OF_KEY, choiceProps);
379         oneOfProps.put(TYPE_KEY, OBJECT_TYPE);
380
381         return oneOfProps;
382     }
383
384     private static void processConstraints(final ConstraintDefinition constraints, final JSONObject props) throws JSONException {
385         boolean isMandatory = constraints.isMandatory();
386         props.put(REQUIRED_KEY, isMandatory);
387
388         Integer minElements = constraints.getMinElements();
389         Integer maxElements = constraints.getMaxElements();
390         if (minElements != null) {
391             props.put(MIN_ITEMS, minElements);
392         }
393         if (maxElements != null) {
394             props.put(MAX_ITEMS, maxElements);
395         }
396     }
397
398     private JSONObject processLeafNode(final LeafSchemaNode leafNode) throws JSONException {
399         JSONObject property = new JSONObject();
400
401         String leafDescription = leafNode.getDescription();
402         property.put(DESCRIPTION_KEY, leafDescription);
403
404         processConstraints(leafNode.getConstraints(), property);
405         processTypeDef(leafNode.getType(), property);
406
407         return property;
408     }
409
410     private static JSONObject processAnyXMLNode(final AnyXmlSchemaNode leafNode) throws JSONException {
411         JSONObject property = new JSONObject();
412
413         String leafDescription = leafNode.getDescription();
414         property.put(DESCRIPTION_KEY, leafDescription);
415
416         processConstraints(leafNode.getConstraints(), property);
417
418         return property;
419     }
420
421     private void processTypeDef(final TypeDefinition<?> leafTypeDef, final JSONObject property) throws JSONException {
422         if (leafTypeDef instanceof BinaryTypeDefinition) {
423             processBinaryType((BinaryTypeDefinition) leafTypeDef, property);
424         } else if (leafTypeDef instanceof BitsTypeDefinition) {
425             processBitsType((BitsTypeDefinition) leafTypeDef, property);
426         } else if (leafTypeDef instanceof EnumTypeDefinition) {
427             processEnumType((EnumTypeDefinition) leafTypeDef, property);
428         } else if (leafTypeDef instanceof IdentityrefTypeDefinition) {
429             property.putOpt(TYPE_KEY,
430                     ((IdentityrefTypeDefinition) leafTypeDef).getIdentity().getQName().getLocalName());
431         } else if (leafTypeDef instanceof StringTypeDefinition) {
432             processStringType((StringTypeDefinition) leafTypeDef, property);
433         } else if (leafTypeDef instanceof UnionTypeDefinition) {
434             processUnionType((UnionTypeDefinition) leafTypeDef, property);
435         } else {
436             String jsonType = jsonTypeFor(leafTypeDef);
437             if (jsonType == null) {
438                 jsonType = "object";
439             }
440             property.putOpt(TYPE_KEY, jsonType);
441         }
442     }
443
444     private static void processBinaryType(final BinaryTypeDefinition binaryType, final JSONObject property) throws JSONException {
445         property.put(TYPE_KEY, STRING);
446         JSONObject media = new JSONObject();
447         media.put(BINARY_ENCODING_KEY, BASE_64);
448         property.put(MEDIA_KEY, media);
449     }
450
451     private static void processEnumType(final EnumTypeDefinition enumLeafType, final JSONObject property) throws JSONException {
452         List<EnumPair> enumPairs = enumLeafType.getValues();
453         List<String> enumNames = new ArrayList<>();
454         for (EnumPair enumPair : enumPairs) {
455             enumNames.add(enumPair.getName());
456         }
457         property.putOpt(ENUM, new JSONArray(enumNames));
458     }
459
460     private static void processBitsType(final BitsTypeDefinition bitsType, final JSONObject property) throws JSONException {
461         property.put(TYPE_KEY, ARRAY_TYPE);
462         property.put(MIN_ITEMS, 0);
463         property.put(UNIQUE_ITEMS_KEY, true);
464         JSONArray enumValues = new JSONArray();
465
466         List<Bit> bits = bitsType.getBits();
467         for (Bit bit : bits) {
468             enumValues.put(bit.getName());
469         }
470         JSONObject itemsValue = new JSONObject();
471         itemsValue.put(ENUM, enumValues);
472         property.put(ITEMS_KEY, itemsValue);
473     }
474
475     private static void processStringType(final StringTypeDefinition stringType, final JSONObject property) throws JSONException {
476         StringTypeDefinition type = stringType;
477         List<LengthConstraint> lengthConstraints = stringType.getLengthConstraints();
478         while (lengthConstraints.isEmpty() && type.getBaseType() != null) {
479             type = type.getBaseType();
480             lengthConstraints = type.getLengthConstraints();
481         }
482
483         // FIXME: json-schema is not expressive enough to capture min/max laternatives. We should find the true minimum
484         //        and true maximum implied by the constraints and use that.
485         for (LengthConstraint lengthConstraint : lengthConstraints) {
486             Number min = lengthConstraint.getMin();
487             Number max = lengthConstraint.getMax();
488             property.putOpt(MIN_LENGTH_KEY, min);
489             property.putOpt(MAX_LENGTH_KEY, max);
490         }
491
492         property.put(TYPE_KEY, STRING);
493     }
494
495     private static void processUnionType(final UnionTypeDefinition unionType, final JSONObject property) throws JSONException {
496         StringBuilder type = new StringBuilder();
497         for (TypeDefinition<?> typeDef : unionType.getTypes()) {
498             if (type.length() > 0) {
499                 type.append(" or ");
500             }
501             type.append(jsonTypeFor(typeDef));
502         }
503
504         property.put(TYPE_KEY, type);
505     }
506
507     /**
508      * Helper method to generate a pre-filled JSON schema object.
509      */
510     private static JSONObject getSchemaTemplate() throws JSONException {
511         JSONObject schemaJSON = new JSONObject();
512         schemaJSON.put(SCHEMA_KEY, SCHEMA_URL);
513
514         return schemaJSON;
515     }
516
517 }