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