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