Adjust window on read
[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.Collection;
22 import java.util.List;
23 import java.util.Optional;
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(schemaContext, 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 SchemaContext schemaContext, final Module module,
248             final ObjectNode models) {
249
250         final String moduleName = module.getName();
251         final Collection<? extends IdentitySchemaNode> idNodes = module.getIdentities();
252         LOG.debug("Processing Identities for module {} . Found {} identity statements", moduleName, idNodes.size());
253
254         for (final IdentitySchemaNode idNode : idNodes) {
255             final ObjectNode identityObj = JsonNodeFactory.instance.objectNode();
256             final String identityName = idNode.getQName().getLocalName();
257             LOG.debug("Processing Identity: {}", identityName);
258
259             identityObj.put(ID_KEY, identityName);
260             putIfNonNull(identityObj, DESCRIPTION_KEY, idNode.getDescription().orElse(null));
261
262             final ObjectNode props = JsonNodeFactory.instance.objectNode();
263
264             if (idNode.getBaseIdentities().isEmpty()) {
265                 /*
266                  * This is a base identity. So lets see if it has sub types. If it does, then add them to the model
267                  * definition.
268                  */
269                 final Collection<? extends IdentitySchemaNode> derivedIds = schemaContext.getDerivedIdentities(idNode);
270                 if (!derivedIds.isEmpty()) {
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             } else {
278                 /*
279                  * This is a derived entity. Add it's base type & move on.
280                  */
281                 props.put(TYPE_KEY, idNode.getBaseIdentities().iterator().next().getQName().getLocalName());
282             }
283
284             // Add the properties. For a base type, this will be an empty object as required by the Swagger spec.
285             identityObj.set(PROPERTIES_KEY, props);
286             models.set(identityName, identityObj);
287         }
288     }
289
290     private ObjectNode processDataNodeContainer(
291             final DataNodeContainer dataNode, final String parentName, final ObjectNode models, final boolean isConfig,
292             final SchemaContext schemaContext) throws IOException {
293         if (dataNode instanceof ListSchemaNode || dataNode instanceof ContainerSchemaNode) {
294             final String localName = ((SchemaNode) dataNode).getQName().getLocalName();
295             final ObjectNode properties = processChildren(dataNode.getChildNodes(), parentName + "/" + localName,
296                 models, isConfig, schemaContext);
297             final String nodeName = parentName + (isConfig ? OperationBuilder.CONFIG : OperationBuilder.OPERATIONAL)
298                     + localName;
299
300             final ObjectNode childSchema = getSchemaTemplate();
301             childSchema.put(TYPE_KEY, OBJECT_TYPE);
302             childSchema.set(PROPERTIES_KEY, properties);
303
304             childSchema.put(ID_KEY, nodeName);
305             models.set(nodeName, childSchema);
306
307             if (isConfig) {
308                 createConcreteModelForPost(models, localName,
309                         createPropertiesForPost(dataNode, schemaContext, parentName + "/" + localName));
310             }
311
312             return processTopData(nodeName, models, (SchemaNode) dataNode);
313         }
314         return null;
315     }
316
317     private static void createConcreteModelForPost(final ObjectNode models, final String localName,
318                                                    final JsonNode properties) {
319         final String nodePostName = OperationBuilder.CONFIG + localName + Post.METHOD_NAME;
320         final ObjectNode postSchema = getSchemaTemplate();
321         postSchema.put(TYPE_KEY, OBJECT_TYPE);
322         postSchema.put(ID_KEY, nodePostName);
323         postSchema.set(PROPERTIES_KEY, properties);
324         models.set(nodePostName, postSchema);
325     }
326
327     private JsonNode createPropertiesForPost(final DataNodeContainer dataNodeContainer,
328                                                final SchemaContext schemaContext, final String parentName) {
329         final ObjectNode properties = JsonNodeFactory.instance.objectNode();
330         for (final DataSchemaNode childNode : dataNodeContainer.getChildNodes()) {
331             if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
332                 final ObjectNode items = JsonNodeFactory.instance.objectNode();
333                 items.put(REF_KEY, parentName + "(config)" + childNode.getQName().getLocalName());
334                 final ObjectNode property = JsonNodeFactory.instance.objectNode();
335                 property.put(TYPE_KEY, childNode instanceof ListSchemaNode ? ARRAY_TYPE : OBJECT_TYPE);
336                 property.set(ITEMS_KEY, items);
337                 properties.set(childNode.getQName().getLocalName(), property);
338             } else if (childNode instanceof LeafSchemaNode) {
339                 final ObjectNode property = processLeafNode((LeafSchemaNode) childNode, schemaContext);
340                 properties.set(childNode.getQName().getLocalName(), property);
341             }
342         }
343         return properties;
344     }
345
346     /**
347      * Processes the nodes.
348      */
349     private ObjectNode processChildren(
350             final Iterable<? extends DataSchemaNode> nodes, final String parentName, final ObjectNode models,
351             final boolean isConfig, final SchemaContext schemaContext) throws IOException {
352         final ObjectNode properties = JsonNodeFactory.instance.objectNode();
353         for (final DataSchemaNode node : nodes) {
354             if (node.isConfiguration() == isConfig) {
355                 final String name = resolveNodesName(node, topLevelModule, schemaContext);
356                 final ObjectNode property;
357                 if (node instanceof LeafSchemaNode) {
358                     property = processLeafNode((LeafSchemaNode) node, schemaContext);
359
360                 } else if (node instanceof ListSchemaNode) {
361                     property = processDataNodeContainer((ListSchemaNode) node, parentName, models, isConfig,
362                             schemaContext);
363
364                 } else if (node instanceof LeafListSchemaNode) {
365                     property = processLeafListNode((LeafListSchemaNode) node, schemaContext);
366
367                 } else if (node instanceof ChoiceSchemaNode) {
368                     if (((ChoiceSchemaNode) node).getCases().iterator().hasNext()) {
369                         processChoiceNode(((ChoiceSchemaNode) node).getCases().iterator().next()
370                             .getChildNodes(), parentName, models, schemaContext, isConfig, properties);
371                     }
372                     continue;
373
374                 } else if (node instanceof AnyxmlSchemaNode) {
375                     property = processAnyXMLNode((AnyxmlSchemaNode) node);
376
377                 } else if (node instanceof AnydataSchemaNode) {
378                     property = processAnydataNode((AnydataSchemaNode) node);
379
380                 } else if (node instanceof ContainerSchemaNode) {
381                     property = processDataNodeContainer((ContainerSchemaNode) node, parentName, models, isConfig,
382                             schemaContext);
383
384                 } else {
385                     throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass());
386                 }
387                 putIfNonNull(property, DESCRIPTION_KEY, node.getDescription().orElse(null));
388                 properties.set(topLevelModule.getName() + ":" + name, property);
389             }
390         }
391         return properties;
392     }
393
394     private ObjectNode processLeafListNode(final LeafListSchemaNode listNode,
395                                            final SchemaContext schemaContext) {
396         final ObjectNode props = JsonNodeFactory.instance.objectNode();
397         props.put(TYPE_KEY, ARRAY_TYPE);
398
399         final ObjectNode itemsVal = JsonNodeFactory.instance.objectNode();
400         final Optional<ElementCountConstraint> optConstraint = listNode.getElementCountConstraint();
401         final int max;
402         if (optConstraint.isPresent()) {
403             final Integer constraintMax = optConstraint.get().getMaxElements();
404             max = constraintMax == null ? 2 : constraintMax;
405             processElementCount(optConstraint.get(), props);
406         } else {
407             max = 2;
408         }
409
410         if (max >= 2) {
411             processTypeDef(listNode.getType(), listNode, itemsVal, schemaContext);
412             processTypeDef(listNode.getType(), listNode, itemsVal, schemaContext);
413         } else {
414             processTypeDef(listNode.getType(), listNode, itemsVal, schemaContext);
415         }
416         props.set(ITEMS_KEY, itemsVal);
417
418         return props;
419     }
420
421     private void processChoiceNode(
422             final Iterable<? extends DataSchemaNode> nodes, final String moduleName, final ObjectNode models,
423             final SchemaContext schemaContext, final boolean isConfig, final ObjectNode properties)
424            throws IOException {
425         for (final DataSchemaNode node : nodes) {
426             final String name = resolveNodesName(node, topLevelModule, schemaContext);
427             final ObjectNode property;
428
429             if (node instanceof LeafSchemaNode) {
430                 property = processLeafNode((LeafSchemaNode) node, schemaContext);
431
432             } else if (node instanceof ListSchemaNode) {
433                 property = processDataNodeContainer((ListSchemaNode) node, moduleName, models, isConfig,
434                         schemaContext);
435
436             } else if (node instanceof LeafListSchemaNode) {
437                 property = processLeafListNode((LeafListSchemaNode) node, schemaContext);
438
439             } else if (node instanceof ChoiceSchemaNode) {
440                 if (((ChoiceSchemaNode) node).getCases().iterator().hasNext()) {
441                     processChoiceNode(((ChoiceSchemaNode) node).getCases().iterator().next().getChildNodes(),
442                             moduleName, models, schemaContext, isConfig, properties);
443                 }
444                 continue;
445
446             } else if (node instanceof AnyxmlSchemaNode) {
447                 property = processAnyXMLNode((AnyxmlSchemaNode) node);
448
449             } else if (node instanceof AnydataSchemaNode) {
450                 property = processAnydataNode((AnydataSchemaNode) node);
451
452             } else if (node instanceof ContainerSchemaNode) {
453                 property = processDataNodeContainer((ContainerSchemaNode) node, moduleName, models, isConfig,
454                         schemaContext);
455
456             } else {
457                 throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass());
458             }
459
460             putIfNonNull(property, DESCRIPTION_KEY, node.getDescription().orElse(null));
461             properties.set(name, property);
462         }
463     }
464
465     private static void processElementCount(final ElementCountConstraint constraint, final ObjectNode props) {
466         final Integer minElements = constraint.getMinElements();
467         if (minElements != null) {
468             props.put(MIN_ITEMS, minElements);
469         }
470         final Integer maxElements = constraint.getMaxElements();
471         if (maxElements != null) {
472             props.put(MAX_ITEMS, maxElements);
473         }
474     }
475
476     private static void processMandatory(final MandatoryAware node, final ObjectNode props) {
477         props.put(REQUIRED_KEY, node.isMandatory());
478     }
479
480     private ObjectNode processLeafNode(final LeafSchemaNode leafNode,
481                                        final SchemaContext schemaContext) {
482         final ObjectNode property = JsonNodeFactory.instance.objectNode();
483
484         final String leafDescription = leafNode.getDescription().orElse(null);
485         putIfNonNull(property, DESCRIPTION_KEY, leafDescription);
486         processMandatory(leafNode, property);
487         processTypeDef(leafNode.getType(), leafNode, property, schemaContext);
488
489         return property;
490     }
491
492     private static ObjectNode processAnydataNode(final AnydataSchemaNode leafNode) {
493         final ObjectNode property = JsonNodeFactory.instance.objectNode();
494
495         final String leafDescription = leafNode.getDescription().orElse(null);
496         putIfNonNull(property, DESCRIPTION_KEY, leafDescription);
497
498         processMandatory(leafNode, property);
499         final String localName = leafNode.getQName().getLocalName();
500         property.put(TYPE_KEY, "example of anydata " + localName);
501
502         return property;
503     }
504
505     private static ObjectNode processAnyXMLNode(final AnyxmlSchemaNode leafNode) {
506         final ObjectNode property = JsonNodeFactory.instance.objectNode();
507
508         final String leafDescription = leafNode.getDescription().orElse(null);
509         putIfNonNull(property, DESCRIPTION_KEY, leafDescription);
510
511         processMandatory(leafNode, property);
512         final String localName = leafNode.getQName().getLocalName();
513         property.put(TYPE_KEY, "example of anyxml " + localName);
514
515         return property;
516     }
517
518     private String processTypeDef(final TypeDefinition<?> leafTypeDef, final DataSchemaNode node,
519                                   final ObjectNode property, final SchemaContext schemaContext) {
520         final String jsonType;
521         final Object defValue = leafTypeDef.getDefaultValue().orElse(null);
522         if (defValue == null) {
523             if (leafTypeDef instanceof BinaryTypeDefinition) {
524                 jsonType = processBinaryType(property);
525
526             } else if (leafTypeDef instanceof BitsTypeDefinition) {
527                 jsonType = processBitsType((BitsTypeDefinition) leafTypeDef, property);
528
529             } else if (leafTypeDef instanceof EnumTypeDefinition) {
530                 jsonType = processEnumType((EnumTypeDefinition) leafTypeDef, property);
531
532             } else if (leafTypeDef instanceof IdentityrefTypeDefinition) {
533                 final String name = topLevelModule.getName();
534                 jsonType = name + ":" + ((IdentityrefTypeDefinition) leafTypeDef).getIdentities().iterator().next()
535                         .getQName().getLocalName();
536
537             } else if (leafTypeDef instanceof StringTypeDefinition) {
538                 jsonType = processStringType(leafTypeDef, property, node.getQName().getLocalName());
539
540             } else if (leafTypeDef instanceof UnionTypeDefinition) {
541                 jsonType = processUnionType((UnionTypeDefinition) leafTypeDef, property, schemaContext, node);
542
543             } else if (leafTypeDef instanceof EmptyTypeDefinition) {
544                 jsonType = UNIQUE_EMPTY_IDENTIFIER;
545
546             } else if (leafTypeDef instanceof LeafrefTypeDefinition) {
547                 return processLeafRef(node, property, schemaContext, leafTypeDef);
548
549             } else if (leafTypeDef instanceof BooleanTypeDefinition) {
550                 jsonType = "true";
551
552             } else if (leafTypeDef instanceof RangeRestrictedTypeDefinition) {
553                 final Number maybeLower = ((RangeRestrictedTypeDefinition<?, ?>) leafTypeDef).getRangeConstraint()
554                         .map(RangeConstraint::getAllowedRanges).map(RangeSet::span).map(Range::lowerEndpoint)
555                         .orElse(null);
556                 jsonType = String.valueOf(maybeLower);
557
558             } else {
559                 jsonType = OBJECT_TYPE;
560
561             }
562         } else {
563             jsonType = String.valueOf(defValue);
564         }
565         putIfNonNull(property, TYPE_KEY, jsonType);
566         return jsonType;
567     }
568
569     private String processLeafRef(final DataSchemaNode node, final ObjectNode property,
570                                   final SchemaContext schemaContext, final TypeDefinition<?> leafTypeDef) {
571         PathExpression xpath = ((LeafrefTypeDefinition) leafTypeDef).getPathStatement();
572         final SchemaNode schemaNode;
573
574         final String xPathString = STRIP_PATTERN.matcher(xpath.getOriginalString()).replaceAll("");
575         xpath = new PathExpressionImpl(xPathString, xpath.isAbsolute());
576
577         final Module module;
578         if (xpath.isAbsolute()) {
579             module = findModule(schemaContext, leafTypeDef.getQName());
580             schemaNode = SchemaContextUtil.findDataSchemaNode(schemaContext, module, xpath);
581         } else {
582             module = findModule(schemaContext, node.getQName());
583             schemaNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, module, node, xpath);
584         }
585
586         return processTypeDef(((TypedDataSchemaNode) schemaNode).getType(), (DataSchemaNode) schemaNode,
587                 property, schemaContext);
588     }
589
590     private static Module findModule(final SchemaContext schemaContext, final QName qualifiedName) {
591         return schemaContext.findModule(qualifiedName.getNamespace(), qualifiedName.getRevision()).orElse(null);
592     }
593
594     private static String processBinaryType(final ObjectNode property) {
595         final ObjectNode media = JsonNodeFactory.instance.objectNode();
596         media.put(BINARY_ENCODING_KEY, BASE_64);
597         property.set(MEDIA_KEY, media);
598         return "bin1 bin2";
599     }
600
601     private static String processEnumType(final EnumTypeDefinition enumLeafType,
602                                           final ObjectNode property) {
603         final List<EnumPair> enumPairs = enumLeafType.getValues();
604         ArrayNode enumNames = new ArrayNode(JsonNodeFactory.instance);
605         for (final EnumPair enumPair : enumPairs) {
606             enumNames.add(new TextNode(enumPair.getName()));
607         }
608
609         property.set(ENUM, enumNames);
610         return enumLeafType.getValues().iterator().next().getName();
611     }
612
613     private static String processBitsType(final BitsTypeDefinition bitsType,
614                                           final ObjectNode property) {
615         property.put(MIN_ITEMS, 0);
616         property.put(UNIQUE_ITEMS_KEY, true);
617         ArrayNode enumNames = new ArrayNode(JsonNodeFactory.instance);
618         for (final Bit bit : bitsType.getBits()) {
619             enumNames.add(new TextNode(bit.getName()));
620         }
621         property.set(ENUM, enumNames);
622
623         return enumNames.iterator().next() + " " + enumNames.get(enumNames.size() - 1);
624     }
625
626     private static String processStringType(final TypeDefinition<?> stringType,
627                                             final ObjectNode property, final String nodeName) {
628         StringTypeDefinition type = (StringTypeDefinition) stringType;
629         Optional<LengthConstraint> lengthConstraints = ((StringTypeDefinition) stringType).getLengthConstraint();
630         while (!lengthConstraints.isPresent() && type.getBaseType() != null) {
631             type = type.getBaseType();
632             lengthConstraints = type.getLengthConstraint();
633         }
634
635         if (lengthConstraints.isPresent()) {
636             final Range<Integer> range = lengthConstraints.get().getAllowedRanges().span();
637             putIfNonNull(property, MIN_LENGTH_KEY, range.lowerEndpoint());
638             putIfNonNull(property, MAX_LENGTH_KEY, range.upperEndpoint());
639         }
640
641         if (type.getPatternConstraints().iterator().hasNext()) {
642             final PatternConstraint pattern = type.getPatternConstraints().iterator().next();
643             String regex = pattern.getJavaPatternString();
644             regex = regex.substring(1, regex.length() - 1);
645             final Generex generex = new Generex(regex);
646             return generex.random();
647         } else {
648             return "Some " + nodeName;
649         }
650     }
651
652     private String processUnionType(final UnionTypeDefinition unionType, final ObjectNode property,
653                                     final SchemaContext schemaContext, final DataSchemaNode node) {
654         final ArrayNode unionNames = new ArrayNode(JsonNodeFactory.instance);
655         for (final TypeDefinition<?> typeDef : unionType.getTypes()) {
656             unionNames.add(processTypeDef(typeDef, node, property, schemaContext));
657         }
658         property.set(ENUM, unionNames);
659         return unionNames.iterator().next().asText();
660     }
661
662     /**
663      * Helper method to generate a pre-filled JSON schema object.
664      */
665     private static ObjectNode getSchemaTemplate() {
666         final ObjectNode schemaJSON = JsonNodeFactory.instance.objectNode();
667         schemaJSON.put(SCHEMA_KEY, SCHEMA_URL);
668
669         return schemaJSON;
670     }
671
672     private static void putIfNonNull(final ObjectNode property, final String key, final Number number) {
673         if (key != null && number != null) {
674             if (number instanceof Double) {
675                 property.put(key, (Double) number);
676             } else if (number instanceof Float) {
677                 property.put(key, (Float) number);
678             } else if (number instanceof Integer) {
679                 property.put(key, (Integer) number);
680             } else if (number instanceof Short) {
681                 property.put(key, (Short) number);
682             } else if (number instanceof Long) {
683                 property.put(key, (Long) number);
684             }
685         }
686     }
687
688     private static void putIfNonNull(final ObjectNode property, final String key, final String value) {
689         if (key != null && value != null) {
690             property.put(key, value);
691         }
692     }
693
694 }