75bfe75d0cd3d5ca00c586851690dd91f031633b
[netconf.git] / restconf / sal-rest-docgen / src / main / java / org / opendaylight / netconf / sal / rest / doc / impl / ModelGenerator.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.netconf.sal.rest.doc.impl;
9
10 import static org.opendaylight.netconf.sal.rest.doc.util.RestDocgenUtil.resolveNodesName;
11
12 import com.google.common.base.Optional;
13 import com.mifmif.common.regex.Generex;
14 import java.io.IOException;
15 import java.util.ArrayList;
16 import java.util.List;
17 import java.util.Set;
18 import java.util.regex.Pattern;
19 import javax.annotation.concurrent.NotThreadSafe;
20 import org.json.JSONArray;
21 import org.json.JSONException;
22 import org.json.JSONObject;
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 JSONObject containing data used for creating examples and models in Api Doc
107      * @throws IOException
108      * @throws JSONException
109      */
110     public JSONObject convertToJsonSchema(final Module module, final SchemaContext schemaContext) throws IOException, JSONException {
111         final JSONObject models = new JSONObject();
112         models.put(UNIQUE_EMPTY_IDENTIFIER, new JSONObject());
113         topLevelModule = module;
114         processModules(module, models, schemaContext);
115         processContainersAndLists(module, models, schemaContext);
116         processRPCs(module, models, schemaContext);
117         processIdentities(module, models);
118         return models;
119     }
120
121     private void processModules(final Module module, final JSONObject models, final SchemaContext schemaContext) throws JSONException {
122         createConcreteModelForPost(models, module.getName() + BaseYangSwaggerGenerator.MODULE_NAME_SUFFIX,
123                 createPropertiesForPost(module, schemaContext, module.getName()));
124     }
125
126     private void processContainersAndLists(final Module module, final JSONObject models, final SchemaContext schemaContext)
127             throws IOException, JSONException {
128         final String moduleName = module.getName();
129
130         for (final DataSchemaNode childNode : module.getChildNodes()) {
131             // For every container and list in the module
132             if (childNode instanceof ContainerSchemaNode || childNode instanceof ListSchemaNode) {
133                 processDataNodeContainer((DataNodeContainer) childNode, moduleName, models, true, schemaContext);
134                 processDataNodeContainer((DataNodeContainer) childNode, moduleName, models, false, schemaContext);
135             }
136         }
137     }
138
139     /**
140      * Process the RPCs for a Module Spits out a file each of the name <rpcName>-input.json and <rpcName>-output.json
141      * for each RPC that contains input & output elements
142      *
143      * @param module
144      * @throws JSONException
145      * @throws IOException
146      */
147     private void processRPCs(final Module module, final JSONObject models, final SchemaContext schemaContext) throws JSONException,
148             IOException {
149         final Set<RpcDefinition> rpcs = module.getRpcs();
150         final String moduleName = module.getName();
151         for (final RpcDefinition rpc : rpcs) {
152             final ContainerSchemaNode input = rpc.getInput();
153             if (!input.getChildNodes().isEmpty()) {
154                 final JSONObject properties = processChildren(input.getChildNodes(), moduleName, models, true, schemaContext);
155
156                 final String filename = "(" + rpc.getQName().getLocalName() + ")input";
157                 final JSONObject childSchema = getSchemaTemplate();
158                 childSchema.put(TYPE_KEY, OBJECT_TYPE);
159                 childSchema.put(PROPERTIES_KEY, properties);
160                 childSchema.put(ID_KEY, filename);
161                 models.put(filename, childSchema);
162
163                 processTopData(filename, models, input);
164             }
165
166             final ContainerSchemaNode output = rpc.getOutput();
167             if (!output.getChildNodes().isEmpty()) {
168                 final JSONObject properties = processChildren(output.getChildNodes(), moduleName, models, true, schemaContext);
169                 final String filename = "(" + rpc.getQName().getLocalName() + ")output";
170                 final JSONObject childSchema = getSchemaTemplate();
171                 childSchema.put(TYPE_KEY, OBJECT_TYPE);
172                 childSchema.put(PROPERTIES_KEY, properties);
173                 childSchema.put(ID_KEY, filename);
174                 models.put(filename, childSchema);
175
176                 processTopData(filename, models, output);
177             }
178         }
179     }
180
181     private JSONObject processTopData(final String filename, final JSONObject models, final SchemaNode schemaNode) {
182         final JSONObject items = new JSONObject();
183
184         items.put(REF_KEY, filename);
185         final JSONObject dataNodeProperties = new JSONObject();
186         dataNodeProperties.put(TYPE_KEY, schemaNode instanceof ListSchemaNode ? ARRAY_TYPE : OBJECT_TYPE);
187         dataNodeProperties.put(ITEMS_KEY, items);
188
189         dataNodeProperties.putOpt(DESCRIPTION_KEY, schemaNode.getDescription());
190         final JSONObject properties = new JSONObject();
191         properties.put(topLevelModule.getName() + ":" + schemaNode.getQName().getLocalName(), dataNodeProperties);
192         final JSONObject finalChildSchema = getSchemaTemplate();
193         finalChildSchema.put(TYPE_KEY, OBJECT_TYPE);
194         finalChildSchema.put(PROPERTIES_KEY, properties);
195         finalChildSchema.put(ID_KEY, filename + OperationBuilder.TOP);
196         models.put(filename + OperationBuilder.TOP, finalChildSchema);
197
198         return dataNodeProperties;
199     }
200
201     /**
202      * Processes the 'identity' statement in a yang model and maps it to a 'model' in the Swagger JSON spec.
203      *
204      * @param module The module from which the identity stmt will be processed
205      * @param models The JSONObject in which the parsed identity will be put as a 'model' obj
206      */
207     private static void processIdentities(final Module module, final JSONObject models) throws JSONException {
208
209         final String moduleName = module.getName();
210         final Set<IdentitySchemaNode> idNodes = module.getIdentities();
211         LOG.debug("Processing Identities for module {} . Found {} identity statements", moduleName, idNodes.size());
212
213         for (final IdentitySchemaNode idNode : idNodes) {
214             final JSONObject identityObj = new JSONObject();
215             final String identityName = idNode.getQName().getLocalName();
216             LOG.debug("Processing Identity: {}", identityName);
217
218             identityObj.put(ID_KEY, identityName);
219             identityObj.put(DESCRIPTION_KEY, idNode.getDescription());
220
221             final JSONObject props = new JSONObject();
222             final IdentitySchemaNode baseId = idNode.getBaseIdentity();
223
224             if (baseId == null) {
225                 /**
226                  * This is a base identity. So lets see if it has sub types. If it does, then add them to the model
227                  * definition.
228                  */
229                 final Set<IdentitySchemaNode> derivedIds = idNode.getDerivedIdentities();
230
231                 if (derivedIds != null) {
232                     final JSONArray subTypes = new JSONArray();
233                     for (final IdentitySchemaNode derivedId : derivedIds) {
234                         subTypes.put(derivedId.getQName().getLocalName());
235                     }
236                     identityObj.put(SUB_TYPES_KEY, subTypes);
237
238                 }
239             } else {
240                 /**
241                  * This is a derived entity. Add it's base type & move on.
242                  */
243                 props.put(TYPE_KEY, baseId.getQName().getLocalName());
244             }
245
246             // Add the properties. For a base type, this will be an empty object as required by the Swagger spec.
247             identityObj.put(PROPERTIES_KEY, props);
248             models.put(identityName, identityObj);
249         }
250     }
251
252     private JSONObject processDataNodeContainer(final DataNodeContainer dataNode, final String parentName, final JSONObject models,
253                                                 final boolean isConfig, final SchemaContext schemaContext) throws JSONException, IOException {
254         if (dataNode instanceof ListSchemaNode || dataNode instanceof ContainerSchemaNode) {
255             final Iterable<DataSchemaNode> containerChildren = dataNode.getChildNodes();
256             final String localName = ((SchemaNode) dataNode).getQName().getLocalName();
257             final JSONObject properties = processChildren(containerChildren, parentName + "/" + localName, models, isConfig, schemaContext);
258             final String nodeName = parentName + (isConfig ? OperationBuilder.CONFIG : OperationBuilder.OPERATIONAL)
259                     + localName;
260
261             final JSONObject childSchema = getSchemaTemplate();
262             childSchema.put(TYPE_KEY, OBJECT_TYPE);
263             childSchema.put(PROPERTIES_KEY, properties);
264
265             childSchema.put(ID_KEY, nodeName);
266             models.put(nodeName, childSchema);
267
268             if (isConfig) {
269                 createConcreteModelForPost(models, localName,
270                         createPropertiesForPost(dataNode, schemaContext, parentName + "/" + localName));
271             }
272
273             return processTopData(nodeName, models, (SchemaNode) dataNode);
274         }
275         return null;
276     }
277
278     private static void createConcreteModelForPost(final JSONObject models, final String localName,
279                                                    final JSONObject properties) throws JSONException {
280         final String nodePostName = OperationBuilder.CONFIG + localName + Post.METHOD_NAME;
281         final JSONObject postSchema = getSchemaTemplate();
282         postSchema.put(TYPE_KEY, OBJECT_TYPE);
283         postSchema.put(ID_KEY, nodePostName);
284         postSchema.put(PROPERTIES_KEY, properties);
285         models.put(nodePostName, postSchema);
286     }
287
288     private JSONObject createPropertiesForPost(final DataNodeContainer dataNodeContainer, final SchemaContext schemaContext, final String parentName)
289             throws JSONException {
290         final JSONObject properties = new JSONObject();
291         for (final DataSchemaNode childNode : dataNodeContainer.getChildNodes()) {
292             if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
293                 final JSONObject items = new JSONObject();
294                 items.put(REF_KEY, parentName + "(config)" + childNode.getQName().getLocalName());
295                 final JSONObject property = new JSONObject();
296                 property.put(TYPE_KEY, childNode instanceof ListSchemaNode ? ARRAY_TYPE : OBJECT_TYPE);
297                 property.put(ITEMS_KEY, items);
298                 properties.put(childNode.getQName().getLocalName(), property);
299             } else if (childNode instanceof LeafSchemaNode) {
300                 final JSONObject property = processLeafNode((LeafSchemaNode) childNode, schemaContext);
301                 properties.put(childNode.getQName().getLocalName(), property);
302             }
303         }
304         return properties;
305     }
306
307     /**
308      * Processes the nodes.
309      */
310     private JSONObject processChildren(final Iterable<DataSchemaNode> nodes, final String parentName, final JSONObject models,
311                                        final boolean isConfig, final SchemaContext schemaContext)
312             throws JSONException, IOException {
313         final JSONObject properties = new JSONObject();
314         for (final DataSchemaNode node : nodes) {
315             if (node.isConfiguration() == isConfig) {
316                 final String name = resolveNodesName(node, topLevelModule, schemaContext);
317                 final JSONObject property;
318                 if (node instanceof LeafSchemaNode) {
319                     property = processLeafNode((LeafSchemaNode) node, schemaContext);
320
321                 } else if (node instanceof ListSchemaNode) {
322                     property = processDataNodeContainer((ListSchemaNode) node, parentName, models, isConfig,
323                             schemaContext);
324
325                 } else if (node instanceof LeafListSchemaNode) {
326                     property = processLeafListNode((LeafListSchemaNode) node, schemaContext);
327
328                 } else if (node instanceof ChoiceSchemaNode) {
329                     if (((ChoiceSchemaNode) node).getCases().iterator().hasNext()) {
330                         processChoiceNode(((ChoiceSchemaNode) node).getCases().iterator().next().getChildNodes(),
331                                 parentName, models, schemaContext, isConfig, properties);
332                     }
333                     continue;
334
335                 } else if (node instanceof AnyXmlSchemaNode) {
336                     property = processAnyXMLNode((AnyXmlSchemaNode) node);
337
338                 } else if (node instanceof ContainerSchemaNode) {
339                     property = processDataNodeContainer((ContainerSchemaNode) node, parentName, models, isConfig,
340                             schemaContext);
341
342                 } else {
343                     throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass());
344                 }
345                 property.putOpt(DESCRIPTION_KEY, node.getDescription());
346                 properties.put(topLevelModule.getName() + ":" + name, property);
347             }
348         }
349         return properties;
350     }
351
352     private JSONObject processLeafListNode(final LeafListSchemaNode listNode, final SchemaContext schemaContext) throws JSONException {
353         final JSONObject props = new JSONObject();
354         props.put(TYPE_KEY, ARRAY_TYPE);
355
356         final JSONObject itemsVal = new JSONObject();
357         final ConstraintDefinition constraints = listNode.getConstraints();
358         final Optional<Integer> maxOptional = Optional.fromNullable(constraints.getMaxElements());
359         if (maxOptional.or(2) >= 2) {
360             processTypeDef(listNode.getType(), listNode, itemsVal, schemaContext);
361             processTypeDef(listNode.getType(), listNode, itemsVal, schemaContext);
362         } else {
363             processTypeDef(listNode.getType(), listNode, itemsVal, schemaContext);
364         }
365         props.put(ITEMS_KEY, itemsVal);
366
367
368         processConstraints(constraints, props);
369
370         return props;
371     }
372
373     private void processChoiceNode(final Iterable<DataSchemaNode> nodes, final String moduleName, final JSONObject models,
374                                    final SchemaContext schemaContext, final boolean isConfig, final JSONObject properties)
375             throws JSONException, IOException {
376         for (final DataSchemaNode node : nodes) {
377             final String name = resolveNodesName(node, topLevelModule, schemaContext);
378             final JSONObject property;
379
380             if (node instanceof LeafSchemaNode) {
381                 property = processLeafNode((LeafSchemaNode) node, schemaContext);
382
383             } else if (node instanceof ListSchemaNode) {
384                 property = processDataNodeContainer((ListSchemaNode) node, moduleName, models, isConfig,
385                         schemaContext);
386
387             } else if (node instanceof LeafListSchemaNode) {
388                 property = processLeafListNode((LeafListSchemaNode) node, schemaContext);
389
390             } else if (node instanceof ChoiceSchemaNode) {
391                 if (((ChoiceSchemaNode) node).getCases().iterator().hasNext())
392                     processChoiceNode(((ChoiceSchemaNode) node).getCases().iterator().next().getChildNodes(),
393                             moduleName, models, schemaContext, isConfig, properties);
394                 continue;
395
396             } else if (node instanceof AnyXmlSchemaNode) {
397                 property = processAnyXMLNode((AnyXmlSchemaNode) node);
398
399             } else if (node instanceof ContainerSchemaNode) {
400                 property = processDataNodeContainer((ContainerSchemaNode) node, moduleName, models, isConfig,
401                         schemaContext);
402
403             } else {
404                 throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass());
405             }
406
407             property.putOpt(DESCRIPTION_KEY, node.getDescription());
408             properties.put(name, property);
409         }
410     }
411
412     private static void processConstraints(final ConstraintDefinition constraints, final JSONObject props) throws JSONException {
413         final boolean isMandatory = constraints.isMandatory();
414         props.put(REQUIRED_KEY, isMandatory);
415
416         final Integer minElements = constraints.getMinElements();
417         final Integer maxElements = constraints.getMaxElements();
418         if (minElements != null) {
419             props.put(MIN_ITEMS, minElements);
420         }
421         if (maxElements != null) {
422             props.put(MAX_ITEMS, maxElements);
423         }
424     }
425
426     private JSONObject processLeafNode(final LeafSchemaNode leafNode, final SchemaContext schemaContext) throws JSONException {
427         final JSONObject property = new JSONObject();
428
429         final String leafDescription = leafNode.getDescription();
430         property.put(DESCRIPTION_KEY, leafDescription);
431         processConstraints(leafNode.getConstraints(), property);
432         processTypeDef(leafNode.getType(), leafNode, property, schemaContext);
433
434         return property;
435     }
436
437     private static JSONObject processAnyXMLNode(final AnyXmlSchemaNode leafNode) throws JSONException {
438         final JSONObject property = new JSONObject();
439
440         final String leafDescription = leafNode.getDescription();
441         property.put(DESCRIPTION_KEY, leafDescription);
442
443         processConstraints(leafNode.getConstraints(), property);
444         final String localName = leafNode.getQName().getLocalName();
445         property.put(TYPE_KEY, "example of anyxml " + localName);
446
447         return property;
448     }
449
450     private String processTypeDef(final TypeDefinition<?> leafTypeDef, final DataSchemaNode node,
451                                   final JSONObject property, final SchemaContext schemaContext) throws JSONException {
452         final String jsonType;
453         if (leafTypeDef.getDefaultValue() == null) {
454             if (leafTypeDef instanceof BinaryTypeDefinition) {
455                 jsonType = processBinaryType(property);
456
457             } else if (leafTypeDef instanceof BitsTypeDefinition) {
458                 jsonType = processBitsType((BitsTypeDefinition) leafTypeDef, property);
459
460             } else if (leafTypeDef instanceof EnumTypeDefinition) {
461                 jsonType = processEnumType((EnumTypeDefinition) leafTypeDef, property);
462
463             } else if (leafTypeDef instanceof IdentityrefTypeDefinition) {
464                 final String name = topLevelModule.getName();
465                 jsonType = name + ":" + ((IdentityrefTypeDefinition) leafTypeDef).getIdentity().getQName().getLocalName();
466
467             } else if (leafTypeDef instanceof StringTypeDefinition) {
468                 jsonType = processStringType(leafTypeDef, property, node.getQName().getLocalName());
469
470             } else if (leafTypeDef instanceof UnionTypeDefinition) {
471                 jsonType = processUnionType((UnionTypeDefinition) leafTypeDef, property, schemaContext, node);
472
473             } else if (leafTypeDef instanceof EmptyTypeDefinition) {
474                 jsonType = UNIQUE_EMPTY_IDENTIFIER;
475
476             } else if (leafTypeDef instanceof LeafrefTypeDefinition) {
477                 return processLeafRef(node, property, schemaContext, leafTypeDef);
478
479             } else if (leafTypeDef instanceof BooleanTypeDefinition) {
480                 jsonType = "true";
481
482             } else if (leafTypeDef instanceof DecimalTypeDefinition) {
483                 jsonType = String.valueOf(((DecimalTypeDefinition) leafTypeDef).getRangeConstraints()
484                         .iterator().next().getMin());
485
486             } else if (leafTypeDef instanceof IntegerTypeDefinition) {
487                 jsonType = String.valueOf(((IntegerTypeDefinition) leafTypeDef).getRangeConstraints()
488                         .iterator().next().getMin());
489
490             } else if (leafTypeDef instanceof UnsignedIntegerTypeDefinition) {
491                 jsonType = String.valueOf(((UnsignedIntegerTypeDefinition) leafTypeDef).getRangeConstraints()
492                         .iterator().next().getMin());
493
494             } else {
495                 jsonType = OBJECT_TYPE;
496
497             }
498         } else {
499             jsonType = String.valueOf(leafTypeDef.getDefaultValue());
500         }
501         property.putOpt(TYPE_KEY, jsonType);
502         return jsonType;
503     }
504
505     private String processLeafRef(final DataSchemaNode node, final JSONObject property, final SchemaContext schemaContext,
506                                   final TypeDefinition<?> leafTypeDef) {
507         RevisionAwareXPath xPath = ((LeafrefTypeDefinition) leafTypeDef).getPathStatement();
508         final SchemaNode schemaNode;
509
510         final String xPathString = STRIP_PATTERN.matcher(xPath.toString()).replaceAll("");
511         xPath = new RevisionAwareXPathImpl(xPathString, xPath.isAbsolute());
512
513         final Module module;
514         if (xPath.isAbsolute()) {
515             module = findModule(schemaContext, leafTypeDef.getQName());
516             schemaNode = SchemaContextUtil.findDataSchemaNode(schemaContext, module, xPath);
517         } else {
518             module = findModule(schemaContext, node.getQName());
519             schemaNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, module, node, xPath);
520         }
521
522         return processTypeDef(((TypedSchemaNode) schemaNode).getType(), (DataSchemaNode) schemaNode, property, schemaContext);
523     }
524
525     private static Module findModule(final SchemaContext schemaContext, final QName qName) {
526         return schemaContext.findModuleByNamespaceAndRevision(qName.getNamespace(), qName.getRevision());
527     }
528
529     private static String processBinaryType(final JSONObject property) throws JSONException {
530         final JSONObject media = new JSONObject();
531         media.put(BINARY_ENCODING_KEY, BASE_64);
532         property.put(MEDIA_KEY, media);
533         return "bin1 bin2";
534     }
535
536     private static String processEnumType(final EnumTypeDefinition enumLeafType, final JSONObject property) throws JSONException {
537         final List<EnumPair> enumPairs = enumLeafType.getValues();
538         final List<String> enumNames = new ArrayList<>();
539         for (final EnumPair enumPair : enumPairs) {
540             enumNames.add(enumPair.getName());
541         }
542
543         property.putOpt(ENUM, new JSONArray(enumNames));
544         return enumLeafType.getValues().iterator().next().getName();
545     }
546
547     private static String processBitsType(final BitsTypeDefinition bitsType, final JSONObject property) throws JSONException {
548         property.put(MIN_ITEMS, 0);
549         property.put(UNIQUE_ITEMS_KEY, true);
550         final List<String> enumNames = new ArrayList<>();
551         final List<Bit> bits = bitsType.getBits();
552         for (final Bit bit : bits) {
553             enumNames.add(bit.getName());
554         }
555         property.put(ENUM, new JSONArray(enumNames));
556
557         return enumNames.iterator().next() + " " + enumNames.get(enumNames.size() - 1);
558     }
559
560     private static String processStringType(final TypeDefinition<?> stringType, final JSONObject property, final String nodeName)
561             throws JSONException {
562         StringTypeDefinition type = (StringTypeDefinition) stringType;
563         List<LengthConstraint> lengthConstraints = ((StringTypeDefinition) stringType).getLengthConstraints();
564         while (lengthConstraints.isEmpty() && type.getBaseType() != null) {
565             type = type.getBaseType();
566             lengthConstraints = type.getLengthConstraints();
567         }
568
569         // FIXME: json-schema is not expressive enough to capture min/max laternatives. We should find the true minimum
570         //        and true maximum implied by the constraints and use that.
571         for (final LengthConstraint lengthConstraint : lengthConstraints) {
572             final Number min = lengthConstraint.getMin();
573             final Number max = lengthConstraint.getMax();
574             property.putOpt(MIN_LENGTH_KEY, min);
575             property.putOpt(MAX_LENGTH_KEY, max);
576         }
577         if (type.getPatternConstraints().iterator().hasNext()) {
578             final PatternConstraint pattern = type.getPatternConstraints().iterator().next();
579             String regex = pattern.getRegularExpression();
580             regex = regex.substring(1, regex.length() - 1);
581             final Generex generex = new Generex(regex);
582             return generex.random();
583         } else {
584             return "Some " + nodeName;
585         }
586     }
587
588     private String processUnionType(final UnionTypeDefinition unionType, final JSONObject property,
589                                     final SchemaContext schemaContext, final DataSchemaNode node)
590             throws JSONException {
591         final List<String> unionNames = new ArrayList<>();
592         for (final TypeDefinition<?> typeDef : unionType.getTypes()) {
593             unionNames.add(processTypeDef(typeDef, node, property, schemaContext));
594         }
595         property.put(ENUM, new JSONArray(unionNames));
596         return unionNames.iterator().next();
597     }
598
599     /**
600      * Helper method to generate a pre-filled JSON schema object.
601      */
602     private static JSONObject getSchemaTemplate() throws JSONException {
603         final JSONObject schemaJSON = new JSONObject();
604         schemaJSON.put(SCHEMA_KEY, SCHEMA_URL);
605
606         return schemaJSON;
607     }
608
609 }