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