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