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