97937936beb47c9ceceacab9325c8c978ac7f196
[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.fasterxml.jackson.databind.JsonNode;
13 import com.fasterxml.jackson.databind.node.ArrayNode;
14 import com.fasterxml.jackson.databind.node.JsonNodeFactory;
15 import com.fasterxml.jackson.databind.node.ObjectNode;
16 import com.fasterxml.jackson.databind.node.TextNode;
17 import com.google.common.collect.Range;
18 import com.google.common.collect.RangeSet;
19 import com.mifmif.common.regex.Generex;
20 import java.io.IOException;
21 import java.util.List;
22 import java.util.Optional;
23 import java.util.Set;
24 import java.util.regex.Pattern;
25 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder;
26 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Post;
27 import org.opendaylight.yangtools.yang.common.QName;
28 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
29 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
30 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
35 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.ElementCountConstraint;
37 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.MandatoryAware;
42 import org.opendaylight.yangtools.yang.model.api.Module;
43 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
44 import org.opendaylight.yangtools.yang.model.api.PathExpression;
45 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
46 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
47 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
49 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
51 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
52 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
53 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
54 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
55 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
56 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
57 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
59 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
60 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
61 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
62 import org.opendaylight.yangtools.yang.model.api.type.RangeRestrictedTypeDefinition;
63 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
64 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
65 import org.opendaylight.yangtools.yang.model.util.PathExpressionImpl;
66 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
69
70 /**
71  * Generates JSON Schema for data defined in YANG. This class is not thread-safe.
72  */
73 public class ModelGenerator {
74
75     private static final Logger LOG = LoggerFactory.getLogger(ModelGenerator.class);
76
77     private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
78     private static final String BASE_64 = "base64";
79     private static final String BINARY_ENCODING_KEY = "binaryEncoding";
80     private static final String MEDIA_KEY = "media";
81     private static final String UNIQUE_ITEMS_KEY = "uniqueItems";
82     private static final String MAX_ITEMS = "maxItems";
83     private static final String MIN_ITEMS = "minItems";
84     private static final String SCHEMA_URL = "http://json-schema.org/draft-04/schema";
85     private static final String SCHEMA_KEY = "$schema";
86     private static final String MAX_LENGTH_KEY = "maxLength";
87     private static final String MIN_LENGTH_KEY = "minLength";
88     private static final String REQUIRED_KEY = "required";
89     private static final String REF_KEY = "$ref";
90     private static final String ITEMS_KEY = "items";
91     private static final String TYPE_KEY = "type";
92     private static final String PROPERTIES_KEY = "properties";
93     private static final String DESCRIPTION_KEY = "description";
94     private static final String OBJECT_TYPE = "object";
95     private static final String ARRAY_TYPE = "array";
96     private static final String ENUM = "enum";
97     private static final String ID_KEY = "id";
98     private static final String SUB_TYPES_KEY = "subTypes";
99     private static final String UNIQUE_EMPTY_IDENTIFIER = "unique_empty_identifier";
100
101     private Module topLevelModule;
102
103     public ModelGenerator() {
104     }
105
106     /**
107      * Creates Json models from provided module according to swagger spec.
108      *
109      * @param module        - Yang module to be converted
110      * @param schemaContext - SchemaContext of all Yang files used by Api Doc
111      * @return ObjectNode containing data used for creating examples and models in Api Doc
112      * @throws IOException if I/O operation fails
113      */
114     public ObjectNode convertToJsonSchema(final Module module,
115                                           final SchemaContext schemaContext) throws IOException {
116         final ObjectNode models = JsonNodeFactory.instance.objectNode();
117         final ObjectNode emptyIdentifier = JsonNodeFactory.instance.objectNode();
118         models.set(UNIQUE_EMPTY_IDENTIFIER, emptyIdentifier);
119         topLevelModule = module;
120         processModules(module, models, schemaContext);
121         processContainersAndLists(module, models, schemaContext);
122         processRPCs(module, models, schemaContext);
123         processIdentities(module, models);
124         return models;
125     }
126
127     private void processModules(final Module module, final ObjectNode models,
128                                 final SchemaContext schemaContext) {
129         createConcreteModelForPost(models, module.getName() + BaseYangSwaggerGenerator.MODULE_NAME_SUFFIX,
130                 createPropertiesForPost(module, schemaContext, module.getName()));
131     }
132
133     private void processContainersAndLists(final Module module, final ObjectNode models,
134                                            final SchemaContext schemaContext) throws IOException {
135         final String moduleName = module.getName();
136
137         for (final DataSchemaNode childNode : module.getChildNodes()) {
138             // For every container and list in the module
139             if (childNode instanceof ContainerSchemaNode || childNode instanceof ListSchemaNode) {
140                 processDataNodeContainer((DataNodeContainer) childNode, moduleName, models, true, schemaContext);
141                 processDataNodeContainer((DataNodeContainer) childNode, moduleName, models, false, schemaContext);
142                 processActionNodeContainer(childNode, moduleName, models, schemaContext);
143             }
144         }
145     }
146
147     /**
148      * Process the Actions Swagger UI.
149      *
150      * @param DataSchemaNode childNode
151      * @param String         moduleName
152      * @param ObjectNode     models
153      * @param SchemaContext  schemaContext
154      * @throws IOException if I/O operation fails
155      */
156     private void processActionNodeContainer(final DataSchemaNode childNode, final String moduleName,
157         final ObjectNode models, final SchemaContext schemaContext) throws IOException {
158         for (ActionDefinition actionDef : ((ActionNodeContainer) childNode).getActions()) {
159             processOperations(actionDef, moduleName, models, schemaContext);
160         }
161     }
162
163     /**
164      * Process the RPCs for Swagger UI.
165      *
166      * @param Module        module
167      * @param ObjectNode    models
168      * @param SchemaContext schemaContext
169      * @throws IOException if I/O operation fails
170      */
171     private void processRPCs(final Module module, final ObjectNode models, final SchemaContext schemaContext)
172         throws IOException {
173         final String moduleName = module.getName();
174         for (final RpcDefinition rpcDefinition : module.getRpcs()) {
175             processOperations(rpcDefinition, moduleName, models, schemaContext);
176         }
177     }
178
179     /**
180      * Process the Operations for a Module Spits out a file each of the name {@code <operationName>-input.json and
181      * <oprationName>-output.json} for each Operation that contains input & output elements.
182      *
183      * @param OperationDefinition operationDef
184      * @param String              moduleName
185      * @param ObjectNode          models
186      * @param SchemaContext       schemaContext
187      * @throws IOException if I/O operation fails
188      */
189     private void processOperations(final OperationDefinition operationDef, final String moduleName,
190         final ObjectNode models, final SchemaContext schemaContext) throws IOException {
191         final ContainerSchemaNode input = operationDef.getInput();
192         if (!input.getChildNodes().isEmpty()) {
193             final ObjectNode properties =
194                 processChildren(input.getChildNodes(), moduleName, models, true, schemaContext);
195
196             final String filename = "(" + operationDef.getQName().getLocalName() + ")input";
197             final ObjectNode childSchema = getSchemaTemplate();
198             childSchema.put(TYPE_KEY, OBJECT_TYPE);
199             childSchema.set(PROPERTIES_KEY, properties);
200             childSchema.put(ID_KEY, filename);
201             models.set(filename, childSchema);
202
203             processTopData(filename, models, input);
204         }
205
206         final ContainerSchemaNode output = operationDef.getOutput();
207         if (!output.getChildNodes().isEmpty()) {
208             final ObjectNode properties =
209                 processChildren(output.getChildNodes(), moduleName, models, true, schemaContext);
210             final String filename = "(" + operationDef.getQName().getLocalName() + ")output";
211             final ObjectNode childSchema = getSchemaTemplate();
212             childSchema.put(TYPE_KEY, OBJECT_TYPE);
213             childSchema.set(PROPERTIES_KEY, properties);
214             childSchema.put(ID_KEY, filename);
215             models.set(filename, childSchema);
216
217             processTopData(filename, models, output);
218         }
219     }
220
221     private ObjectNode processTopData(final String filename, final ObjectNode models, final SchemaNode schemaNode) {
222         final ObjectNode items = JsonNodeFactory.instance.objectNode();
223
224         items.put(REF_KEY, filename);
225         final ObjectNode dataNodeProperties = JsonNodeFactory.instance.objectNode();
226         dataNodeProperties.put(TYPE_KEY, schemaNode instanceof ListSchemaNode ? ARRAY_TYPE : OBJECT_TYPE);
227         dataNodeProperties.set(ITEMS_KEY, items);
228
229         putIfNonNull(dataNodeProperties, DESCRIPTION_KEY, schemaNode.getDescription().orElse(null));
230         final ObjectNode properties = JsonNodeFactory.instance.objectNode();
231         properties.set(topLevelModule.getName() + ":" + schemaNode.getQName().getLocalName(), dataNodeProperties);
232         final ObjectNode finalChildSchema = getSchemaTemplate();
233         finalChildSchema.put(TYPE_KEY, OBJECT_TYPE);
234         finalChildSchema.set(PROPERTIES_KEY, properties);
235         finalChildSchema.put(ID_KEY, filename + OperationBuilder.TOP);
236         models.set(filename + OperationBuilder.TOP, finalChildSchema);
237
238         return dataNodeProperties;
239     }
240
241     /**
242      * Processes the 'identity' statement in a yang model and maps it to a 'model' in the Swagger JSON spec.
243      *
244      * @param module The module from which the identity stmt will be processed
245      * @param models The ObjectNode in which the parsed identity will be put as a 'model' obj
246      */
247     private static void processIdentities(final Module module, final ObjectNode models) {
248
249         final String moduleName = module.getName();
250         final Set<IdentitySchemaNode> idNodes = module.getIdentities();
251         LOG.debug("Processing Identities for module {} . Found {} identity statements", moduleName, idNodes.size());
252
253         for (final IdentitySchemaNode idNode : idNodes) {
254             final ObjectNode identityObj = JsonNodeFactory.instance.objectNode();
255             final String identityName = idNode.getQName().getLocalName();
256             LOG.debug("Processing Identity: {}", identityName);
257
258             identityObj.put(ID_KEY, identityName);
259             putIfNonNull(identityObj, DESCRIPTION_KEY, idNode.getDescription().orElse(null));
260
261             final ObjectNode props = JsonNodeFactory.instance.objectNode();
262
263             if (idNode.getBaseIdentities().isEmpty()) {
264                 /*
265                  * This is a base identity. So lets see if it has sub types. If it does, then add them to the model
266                  * definition.
267                  */
268                 final Set<IdentitySchemaNode> derivedIds = idNode.getDerivedIdentities();
269
270                 if (derivedIds != null) {
271                     final ArrayNode subTypes = new ArrayNode(JsonNodeFactory.instance);
272                     for (final IdentitySchemaNode derivedId : derivedIds) {
273                         subTypes.add(derivedId.getQName().getLocalName());
274                     }
275                     identityObj.set(SUB_TYPES_KEY, subTypes);
276
277                 }
278             } else {
279                 /*
280                  * This is a derived entity. Add it's base type & move on.
281                  */
282                 props.put(TYPE_KEY, idNode.getBaseIdentities().iterator().next().getQName().getLocalName());
283             }
284
285             // Add the properties. For a base type, this will be an empty object as required by the Swagger spec.
286             identityObj.set(PROPERTIES_KEY, props);
287             models.set(identityName, identityObj);
288         }
289     }
290
291     private ObjectNode processDataNodeContainer(
292             final DataNodeContainer dataNode, final String parentName, final ObjectNode models, final boolean isConfig,
293             final SchemaContext schemaContext) throws IOException {
294         if (dataNode instanceof ListSchemaNode || dataNode instanceof ContainerSchemaNode) {
295             final Iterable<DataSchemaNode> containerChildren = dataNode.getChildNodes();
296             final String localName = ((SchemaNode) dataNode).getQName().getLocalName();
297             final ObjectNode properties =
298                     processChildren(containerChildren, parentName + "/" + localName, models, isConfig, schemaContext);
299             final String nodeName = parentName + (isConfig ? OperationBuilder.CONFIG : OperationBuilder.OPERATIONAL)
300                     + localName;
301
302             final ObjectNode childSchema = getSchemaTemplate();
303             childSchema.put(TYPE_KEY, OBJECT_TYPE);
304             childSchema.set(PROPERTIES_KEY, properties);
305
306             childSchema.put(ID_KEY, nodeName);
307             models.set(nodeName, childSchema);
308
309             if (isConfig) {
310                 createConcreteModelForPost(models, localName,
311                         createPropertiesForPost(dataNode, schemaContext, parentName + "/" + localName));
312             }
313
314             return processTopData(nodeName, models, (SchemaNode) dataNode);
315         }
316         return null;
317     }
318
319     private static void createConcreteModelForPost(final ObjectNode models, final String localName,
320                                                    final JsonNode properties) {
321         final String nodePostName = OperationBuilder.CONFIG + localName + Post.METHOD_NAME;
322         final ObjectNode postSchema = getSchemaTemplate();
323         postSchema.put(TYPE_KEY, OBJECT_TYPE);
324         postSchema.put(ID_KEY, nodePostName);
325         postSchema.set(PROPERTIES_KEY, properties);
326         models.set(nodePostName, postSchema);
327     }
328
329     private JsonNode createPropertiesForPost(final DataNodeContainer dataNodeContainer,
330                                                final SchemaContext schemaContext, final String parentName) {
331         final ObjectNode properties = JsonNodeFactory.instance.objectNode();
332         for (final DataSchemaNode childNode : dataNodeContainer.getChildNodes()) {
333             if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
334                 final ObjectNode items = JsonNodeFactory.instance.objectNode();
335                 items.put(REF_KEY, parentName + "(config)" + childNode.getQName().getLocalName());
336                 final ObjectNode property = JsonNodeFactory.instance.objectNode();
337                 property.put(TYPE_KEY, childNode instanceof ListSchemaNode ? ARRAY_TYPE : OBJECT_TYPE);
338                 property.set(ITEMS_KEY, items);
339                 properties.set(childNode.getQName().getLocalName(), property);
340             } else if (childNode instanceof LeafSchemaNode) {
341                 final ObjectNode property = processLeafNode((LeafSchemaNode) childNode, schemaContext);
342                 properties.set(childNode.getQName().getLocalName(), property);
343             }
344         }
345         return properties;
346     }
347
348     /**
349      * Processes the nodes.
350      */
351     private ObjectNode processChildren(
352             final Iterable<DataSchemaNode> nodes, final String parentName, final ObjectNode models,
353             final boolean isConfig, final SchemaContext schemaContext) throws IOException {
354         final ObjectNode properties = JsonNodeFactory.instance.objectNode();
355         for (final DataSchemaNode node : nodes) {
356             if (node.isConfiguration() == isConfig) {
357                 final String name = resolveNodesName(node, topLevelModule, schemaContext);
358                 final ObjectNode property;
359                 if (node instanceof LeafSchemaNode) {
360                     property = processLeafNode((LeafSchemaNode) node, schemaContext);
361
362                 } else if (node instanceof ListSchemaNode) {
363                     property = processDataNodeContainer((ListSchemaNode) node, parentName, models, isConfig,
364                             schemaContext);
365
366                 } else if (node instanceof LeafListSchemaNode) {
367                     property = processLeafListNode((LeafListSchemaNode) node, schemaContext);
368
369                 } else if (node instanceof ChoiceSchemaNode) {
370                     if (((ChoiceSchemaNode) node).getCases().values().iterator().hasNext()) {
371                         processChoiceNode(((ChoiceSchemaNode) node).getCases().values().iterator().next()
372                             .getChildNodes(), parentName, models, schemaContext, isConfig, properties);
373                     }
374                     continue;
375
376                 } else if (node instanceof AnyxmlSchemaNode) {
377                     property = processAnyXMLNode((AnyxmlSchemaNode) node);
378
379                 } else if (node instanceof AnydataSchemaNode) {
380                     property = processAnydataNode((AnydataSchemaNode) node);
381
382                 } else if (node instanceof ContainerSchemaNode) {
383                     property = processDataNodeContainer((ContainerSchemaNode) node, parentName, models, isConfig,
384                             schemaContext);
385
386                 } else {
387                     throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass());
388                 }
389                 putIfNonNull(property, DESCRIPTION_KEY, node.getDescription().orElse(null));
390                 properties.set(topLevelModule.getName() + ":" + name, property);
391             }
392         }
393         return properties;
394     }
395
396     private ObjectNode processLeafListNode(final LeafListSchemaNode listNode,
397                                            final SchemaContext schemaContext) {
398         final ObjectNode props = JsonNodeFactory.instance.objectNode();
399         props.put(TYPE_KEY, ARRAY_TYPE);
400
401         final ObjectNode itemsVal = JsonNodeFactory.instance.objectNode();
402         final Optional<ElementCountConstraint> optConstraint = listNode.getElementCountConstraint();
403         final int max;
404         if (optConstraint.isPresent()) {
405             final Integer constraintMax = optConstraint.get().getMaxElements();
406             max = constraintMax == null ? 2 : constraintMax;
407             processElementCount(optConstraint.get(), props);
408         } else {
409             max = 2;
410         }
411
412         if (max >= 2) {
413             processTypeDef(listNode.getType(), listNode, itemsVal, schemaContext);
414             processTypeDef(listNode.getType(), listNode, itemsVal, schemaContext);
415         } else {
416             processTypeDef(listNode.getType(), listNode, itemsVal, schemaContext);
417         }
418         props.set(ITEMS_KEY, itemsVal);
419
420         return props;
421     }
422
423     private void processChoiceNode(
424             final Iterable<DataSchemaNode> nodes, final String moduleName, final ObjectNode models,
425             final SchemaContext schemaContext, final boolean isConfig, final ObjectNode properties)
426            throws IOException {
427         for (final DataSchemaNode node : nodes) {
428             final String name = resolveNodesName(node, topLevelModule, schemaContext);
429             final ObjectNode property;
430
431             if (node instanceof LeafSchemaNode) {
432                 property = processLeafNode((LeafSchemaNode) node, schemaContext);
433
434             } else if (node instanceof ListSchemaNode) {
435                 property = processDataNodeContainer((ListSchemaNode) node, moduleName, models, isConfig,
436                         schemaContext);
437
438             } else if (node instanceof LeafListSchemaNode) {
439                 property = processLeafListNode((LeafListSchemaNode) node, schemaContext);
440
441             } else if (node instanceof ChoiceSchemaNode) {
442                 if (((ChoiceSchemaNode) node).getCases().values().iterator().hasNext()) {
443                     processChoiceNode(((ChoiceSchemaNode) node).getCases().values().iterator().next().getChildNodes(),
444                             moduleName, models, schemaContext, isConfig, properties);
445                 }
446                 continue;
447
448             } else if (node instanceof AnyxmlSchemaNode) {
449                 property = processAnyXMLNode((AnyxmlSchemaNode) node);
450
451             } else if (node instanceof AnydataSchemaNode) {
452                 property = processAnydataNode((AnydataSchemaNode) node);
453
454             } else if (node instanceof ContainerSchemaNode) {
455                 property = processDataNodeContainer((ContainerSchemaNode) node, moduleName, models, isConfig,
456                         schemaContext);
457
458             } else {
459                 throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass());
460             }
461
462             putIfNonNull(property, DESCRIPTION_KEY, node.getDescription().orElse(null));
463             properties.set(name, property);
464         }
465     }
466
467     private static void processElementCount(final ElementCountConstraint constraint, final ObjectNode props) {
468         final Integer minElements = constraint.getMinElements();
469         if (minElements != null) {
470             props.put(MIN_ITEMS, minElements);
471         }
472         final Integer maxElements = constraint.getMaxElements();
473         if (maxElements != null) {
474             props.put(MAX_ITEMS, maxElements);
475         }
476     }
477
478     private static void processMandatory(final MandatoryAware node, final ObjectNode props) {
479         props.put(REQUIRED_KEY, node.isMandatory());
480     }
481
482     private ObjectNode processLeafNode(final LeafSchemaNode leafNode,
483                                        final SchemaContext schemaContext) {
484         final ObjectNode property = JsonNodeFactory.instance.objectNode();
485
486         final String leafDescription = leafNode.getDescription().orElse(null);
487         putIfNonNull(property, DESCRIPTION_KEY, leafDescription);
488         processMandatory(leafNode, property);
489         processTypeDef(leafNode.getType(), leafNode, property, schemaContext);
490
491         return property;
492     }
493
494     private static ObjectNode processAnydataNode(final AnydataSchemaNode leafNode) {
495         final ObjectNode property = JsonNodeFactory.instance.objectNode();
496
497         final String leafDescription = leafNode.getDescription().orElse(null);
498         putIfNonNull(property, DESCRIPTION_KEY, leafDescription);
499
500         processMandatory(leafNode, property);
501         final String localName = leafNode.getQName().getLocalName();
502         property.put(TYPE_KEY, "example of anydata " + localName);
503
504         return property;
505     }
506
507     private static ObjectNode processAnyXMLNode(final AnyxmlSchemaNode leafNode) {
508         final ObjectNode property = JsonNodeFactory.instance.objectNode();
509
510         final String leafDescription = leafNode.getDescription().orElse(null);
511         putIfNonNull(property, DESCRIPTION_KEY, leafDescription);
512
513         processMandatory(leafNode, property);
514         final String localName = leafNode.getQName().getLocalName();
515         property.put(TYPE_KEY, "example of anyxml " + localName);
516
517         return property;
518     }
519
520     private String processTypeDef(final TypeDefinition<?> leafTypeDef, final DataSchemaNode node,
521                                   final ObjectNode property, final SchemaContext schemaContext) {
522         final String jsonType;
523         final Object defValue = leafTypeDef.getDefaultValue().orElse(null);
524         if (defValue == null) {
525             if (leafTypeDef instanceof BinaryTypeDefinition) {
526                 jsonType = processBinaryType(property);
527
528             } else if (leafTypeDef instanceof BitsTypeDefinition) {
529                 jsonType = processBitsType((BitsTypeDefinition) leafTypeDef, property);
530
531             } else if (leafTypeDef instanceof EnumTypeDefinition) {
532                 jsonType = processEnumType((EnumTypeDefinition) leafTypeDef, property);
533
534             } else if (leafTypeDef instanceof IdentityrefTypeDefinition) {
535                 final String name = topLevelModule.getName();
536                 jsonType = name + ":" + ((IdentityrefTypeDefinition) leafTypeDef).getIdentities().iterator().next()
537                         .getQName().getLocalName();
538
539             } else if (leafTypeDef instanceof StringTypeDefinition) {
540                 jsonType = processStringType(leafTypeDef, property, node.getQName().getLocalName());
541
542             } else if (leafTypeDef instanceof UnionTypeDefinition) {
543                 jsonType = processUnionType((UnionTypeDefinition) leafTypeDef, property, schemaContext, node);
544
545             } else if (leafTypeDef instanceof EmptyTypeDefinition) {
546                 jsonType = UNIQUE_EMPTY_IDENTIFIER;
547
548             } else if (leafTypeDef instanceof LeafrefTypeDefinition) {
549                 return processLeafRef(node, property, schemaContext, leafTypeDef);
550
551             } else if (leafTypeDef instanceof BooleanTypeDefinition) {
552                 jsonType = "true";
553
554             } else if (leafTypeDef instanceof RangeRestrictedTypeDefinition) {
555                 final Number maybeLower = ((RangeRestrictedTypeDefinition<?, ?>) leafTypeDef).getRangeConstraint()
556                         .map(RangeConstraint::getAllowedRanges).map(RangeSet::span).map(Range::lowerEndpoint)
557                         .orElse(null);
558                 jsonType = String.valueOf(maybeLower);
559
560             } else {
561                 jsonType = OBJECT_TYPE;
562
563             }
564         } else {
565             jsonType = String.valueOf(defValue);
566         }
567         putIfNonNull(property, TYPE_KEY, jsonType);
568         return jsonType;
569     }
570
571     private String processLeafRef(final DataSchemaNode node, final ObjectNode property,
572                                   final SchemaContext schemaContext, final TypeDefinition<?> leafTypeDef) {
573         PathExpression xpath = ((LeafrefTypeDefinition) leafTypeDef).getPathStatement();
574         final SchemaNode schemaNode;
575
576         final String xPathString = STRIP_PATTERN.matcher(xpath.getOriginalString()).replaceAll("");
577         xpath = new PathExpressionImpl(xPathString, xpath.isAbsolute());
578
579         final Module module;
580         if (xpath.isAbsolute()) {
581             module = findModule(schemaContext, leafTypeDef.getQName());
582             schemaNode = SchemaContextUtil.findDataSchemaNode(schemaContext, module, xpath);
583         } else {
584             module = findModule(schemaContext, node.getQName());
585             schemaNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, module, node, xpath);
586         }
587
588         return processTypeDef(((TypedDataSchemaNode) schemaNode).getType(), (DataSchemaNode) schemaNode,
589                 property, schemaContext);
590     }
591
592     private static Module findModule(final SchemaContext schemaContext, final QName qualifiedName) {
593         return schemaContext.findModule(qualifiedName.getNamespace(), qualifiedName.getRevision()).orElse(null);
594     }
595
596     private static String processBinaryType(final ObjectNode property) {
597         final ObjectNode media = JsonNodeFactory.instance.objectNode();
598         media.put(BINARY_ENCODING_KEY, BASE_64);
599         property.set(MEDIA_KEY, media);
600         return "bin1 bin2";
601     }
602
603     private static String processEnumType(final EnumTypeDefinition enumLeafType,
604                                           final ObjectNode property) {
605         final List<EnumPair> enumPairs = enumLeafType.getValues();
606         ArrayNode enumNames = new ArrayNode(JsonNodeFactory.instance);
607         for (final EnumPair enumPair : enumPairs) {
608             enumNames.add(new TextNode(enumPair.getName()));
609         }
610
611         property.set(ENUM, enumNames);
612         return enumLeafType.getValues().iterator().next().getName();
613     }
614
615     private static String processBitsType(final BitsTypeDefinition bitsType,
616                                           final ObjectNode property) {
617         property.put(MIN_ITEMS, 0);
618         property.put(UNIQUE_ITEMS_KEY, true);
619         ArrayNode enumNames = new ArrayNode(JsonNodeFactory.instance);
620         final List<Bit> bits = bitsType.getBits();
621         for (final Bit bit : bits) {
622             enumNames.add(new TextNode(bit.getName()));
623         }
624         property.set(ENUM, enumNames);
625
626         return enumNames.iterator().next() + " " + enumNames.get(enumNames.size() - 1);
627     }
628
629     private static String processStringType(final TypeDefinition<?> stringType,
630                                             final ObjectNode property, final String nodeName) {
631         StringTypeDefinition type = (StringTypeDefinition) stringType;
632         Optional<LengthConstraint> lengthConstraints = ((StringTypeDefinition) stringType).getLengthConstraint();
633         while (!lengthConstraints.isPresent() && type.getBaseType() != null) {
634             type = type.getBaseType();
635             lengthConstraints = type.getLengthConstraint();
636         }
637
638         if (lengthConstraints.isPresent()) {
639             final Range<Integer> range = lengthConstraints.get().getAllowedRanges().span();
640             putIfNonNull(property, MIN_LENGTH_KEY, range.lowerEndpoint());
641             putIfNonNull(property, MAX_LENGTH_KEY, range.upperEndpoint());
642         }
643
644         if (type.getPatternConstraints().iterator().hasNext()) {
645             final PatternConstraint pattern = type.getPatternConstraints().iterator().next();
646             String regex = pattern.getJavaPatternString();
647             regex = regex.substring(1, regex.length() - 1);
648             final Generex generex = new Generex(regex);
649             return generex.random();
650         } else {
651             return "Some " + nodeName;
652         }
653     }
654
655     private String processUnionType(final UnionTypeDefinition unionType, final ObjectNode property,
656                                     final SchemaContext schemaContext, final DataSchemaNode node) {
657         final ArrayNode unionNames = new ArrayNode(JsonNodeFactory.instance);
658         for (final TypeDefinition<?> typeDef : unionType.getTypes()) {
659             unionNames.add(processTypeDef(typeDef, node, property, schemaContext));
660         }
661         property.set(ENUM, unionNames);
662         return unionNames.iterator().next().asText();
663     }
664
665     /**
666      * Helper method to generate a pre-filled JSON schema object.
667      */
668     private static ObjectNode getSchemaTemplate() {
669         final ObjectNode schemaJSON = JsonNodeFactory.instance.objectNode();
670         schemaJSON.put(SCHEMA_KEY, SCHEMA_URL);
671
672         return schemaJSON;
673     }
674
675     private static void putIfNonNull(final ObjectNode property, final String key, final Number number) {
676         if (key != null && number != null) {
677             if (number instanceof Double) {
678                 property.put(key, (Double) number);
679             } else if (number instanceof Float) {
680                 property.put(key, (Float) number);
681             } else if (number instanceof Integer) {
682                 property.put(key, (Integer) number);
683             } else if (number instanceof Short) {
684                 property.put(key, (Short) number);
685             } else if (number instanceof Long) {
686                 property.put(key, (Long) number);
687             }
688         }
689     }
690
691     private static void putIfNonNull(final ObjectNode property, final String key, final String value) {
692         if (key != null && value != null) {
693             property.put(key, value);
694         }
695     }
696
697 }