2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.netconf.sal.rest.doc.impl;
10 import static org.opendaylight.netconf.sal.rest.doc.util.RestDocgenUtil.resolveNodesName;
12 import com.fasterxml.jackson.databind.JsonNode;
13 import com.fasterxml.jackson.databind.node.ArrayNode;
14 import com.fasterxml.jackson.databind.node.JsonNodeFactory;
15 import com.fasterxml.jackson.databind.node.ObjectNode;
16 import com.fasterxml.jackson.databind.node.TextNode;
17 import com.google.common.collect.Range;
18 import com.google.common.collect.RangeSet;
19 import com.mifmif.common.regex.Generex;
20 import java.io.IOException;
21 import java.util.List;
22 import java.util.Optional;
24 import java.util.regex.Pattern;
25 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder;
26 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Post;
27 import org.opendaylight.yangtools.yang.common.QName;
28 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
29 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
30 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
35 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.ElementCountConstraint;
37 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.MandatoryAware;
42 import org.opendaylight.yangtools.yang.model.api.Module;
43 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
44 import org.opendaylight.yangtools.yang.model.api.PathExpression;
45 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
46 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
47 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
49 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
51 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
52 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
53 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
54 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
55 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
56 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
57 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
59 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
60 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
61 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
62 import org.opendaylight.yangtools.yang.model.api.type.RangeRestrictedTypeDefinition;
63 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
64 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
65 import org.opendaylight.yangtools.yang.model.util.PathExpressionImpl;
66 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
71 * Generates JSON Schema for data defined in YANG. This class is not thread-safe.
73 public class ModelGenerator {
75 private static final Logger LOG = LoggerFactory.getLogger(ModelGenerator.class);
77 private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
78 private static final String BASE_64 = "base64";
79 private static final String BINARY_ENCODING_KEY = "binaryEncoding";
80 private static final String MEDIA_KEY = "media";
81 private static final String UNIQUE_ITEMS_KEY = "uniqueItems";
82 private static final String MAX_ITEMS = "maxItems";
83 private static final String MIN_ITEMS = "minItems";
84 private static final String SCHEMA_URL = "http://json-schema.org/draft-04/schema";
85 private static final String SCHEMA_KEY = "$schema";
86 private static final String MAX_LENGTH_KEY = "maxLength";
87 private static final String MIN_LENGTH_KEY = "minLength";
88 private static final String REQUIRED_KEY = "required";
89 private static final String REF_KEY = "$ref";
90 private static final String ITEMS_KEY = "items";
91 private static final String TYPE_KEY = "type";
92 private static final String PROPERTIES_KEY = "properties";
93 private static final String DESCRIPTION_KEY = "description";
94 private static final String OBJECT_TYPE = "object";
95 private static final String ARRAY_TYPE = "array";
96 private static final String ENUM = "enum";
97 private static final String ID_KEY = "id";
98 private static final String SUB_TYPES_KEY = "subTypes";
99 private static final String UNIQUE_EMPTY_IDENTIFIER = "unique_empty_identifier";
101 private Module topLevelModule;
103 public ModelGenerator() {
107 * Creates Json models from provided module according to swagger spec.
109 * @param module - Yang module to be converted
110 * @param schemaContext - SchemaContext of all Yang files used by Api Doc
111 * @return ObjectNode containing data used for creating examples and models in Api Doc
112 * @throws IOException if I/O operation fails
114 public ObjectNode convertToJsonSchema(final Module module,
115 final SchemaContext schemaContext) throws IOException {
116 final ObjectNode models = JsonNodeFactory.instance.objectNode();
117 final ObjectNode emptyIdentifier = JsonNodeFactory.instance.objectNode();
118 models.set(UNIQUE_EMPTY_IDENTIFIER, emptyIdentifier);
119 topLevelModule = module;
120 processModules(module, models, schemaContext);
121 processContainersAndLists(module, models, schemaContext);
122 processRPCs(module, models, schemaContext);
123 processIdentities(module, models);
127 private void processModules(final Module module, final ObjectNode models,
128 final SchemaContext schemaContext) {
129 createConcreteModelForPost(models, module.getName() + BaseYangSwaggerGenerator.MODULE_NAME_SUFFIX,
130 createPropertiesForPost(module, schemaContext, module.getName()));
133 private void processContainersAndLists(final Module module, final ObjectNode models,
134 final SchemaContext schemaContext) throws IOException {
135 final String moduleName = module.getName();
137 for (final DataSchemaNode childNode : module.getChildNodes()) {
138 // For every container and list in the module
139 if (childNode instanceof ContainerSchemaNode || childNode instanceof ListSchemaNode) {
140 processDataNodeContainer((DataNodeContainer) childNode, moduleName, models, true, schemaContext);
141 processDataNodeContainer((DataNodeContainer) childNode, moduleName, models, false, schemaContext);
142 processActionNodeContainer(childNode, moduleName, models, schemaContext);
148 * Process the Actions Swagger UI.
150 * @param DataSchemaNode childNode
151 * @param String moduleName
152 * @param ObjectNode models
153 * @param SchemaContext schemaContext
154 * @throws IOException if I/O operation fails
156 private void processActionNodeContainer(final DataSchemaNode childNode, final String moduleName,
157 final ObjectNode models, final SchemaContext schemaContext) throws IOException {
158 for (ActionDefinition actionDef : ((ActionNodeContainer) childNode).getActions()) {
159 processOperations(actionDef, moduleName, models, schemaContext);
164 * Process the RPCs for Swagger UI.
166 * @param Module module
167 * @param ObjectNode models
168 * @param SchemaContext schemaContext
169 * @throws IOException if I/O operation fails
171 private void processRPCs(final Module module, final ObjectNode models, final SchemaContext schemaContext)
173 final String moduleName = module.getName();
174 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
175 processOperations(rpcDefinition, moduleName, models, schemaContext);
180 * Process the Operations for a Module Spits out a file each of the name {@code <operationName>-input.json and
181 * <oprationName>-output.json} for each Operation that contains input & output elements.
183 * @param OperationDefinition operationDef
184 * @param String moduleName
185 * @param ObjectNode models
186 * @param SchemaContext schemaContext
187 * @throws IOException if I/O operation fails
189 private void processOperations(final OperationDefinition operationDef, final String moduleName,
190 final ObjectNode models, final SchemaContext schemaContext) throws IOException {
191 final ContainerSchemaNode input = operationDef.getInput();
192 if (!input.getChildNodes().isEmpty()) {
193 final ObjectNode properties =
194 processChildren(input.getChildNodes(), moduleName, models, true, schemaContext);
196 final String filename = "(" + operationDef.getQName().getLocalName() + ")input";
197 final ObjectNode childSchema = getSchemaTemplate();
198 childSchema.put(TYPE_KEY, OBJECT_TYPE);
199 childSchema.set(PROPERTIES_KEY, properties);
200 childSchema.put(ID_KEY, filename);
201 models.set(filename, childSchema);
203 processTopData(filename, models, input);
206 final ContainerSchemaNode output = operationDef.getOutput();
207 if (!output.getChildNodes().isEmpty()) {
208 final ObjectNode properties =
209 processChildren(output.getChildNodes(), moduleName, models, true, schemaContext);
210 final String filename = "(" + operationDef.getQName().getLocalName() + ")output";
211 final ObjectNode childSchema = getSchemaTemplate();
212 childSchema.put(TYPE_KEY, OBJECT_TYPE);
213 childSchema.set(PROPERTIES_KEY, properties);
214 childSchema.put(ID_KEY, filename);
215 models.set(filename, childSchema);
217 processTopData(filename, models, output);
221 private ObjectNode processTopData(final String filename, final ObjectNode models, final SchemaNode schemaNode) {
222 final ObjectNode items = JsonNodeFactory.instance.objectNode();
224 items.put(REF_KEY, filename);
225 final ObjectNode dataNodeProperties = JsonNodeFactory.instance.objectNode();
226 dataNodeProperties.put(TYPE_KEY, schemaNode instanceof ListSchemaNode ? ARRAY_TYPE : OBJECT_TYPE);
227 dataNodeProperties.set(ITEMS_KEY, items);
229 putIfNonNull(dataNodeProperties, DESCRIPTION_KEY, schemaNode.getDescription().orElse(null));
230 final ObjectNode properties = JsonNodeFactory.instance.objectNode();
231 properties.set(topLevelModule.getName() + ":" + schemaNode.getQName().getLocalName(), dataNodeProperties);
232 final ObjectNode finalChildSchema = getSchemaTemplate();
233 finalChildSchema.put(TYPE_KEY, OBJECT_TYPE);
234 finalChildSchema.set(PROPERTIES_KEY, properties);
235 finalChildSchema.put(ID_KEY, filename + OperationBuilder.TOP);
236 models.set(filename + OperationBuilder.TOP, finalChildSchema);
238 return dataNodeProperties;
242 * Processes the 'identity' statement in a yang model and maps it to a 'model' in the Swagger JSON spec.
244 * @param module The module from which the identity stmt will be processed
245 * @param models The ObjectNode in which the parsed identity will be put as a 'model' obj
247 private static void processIdentities(final Module module, final ObjectNode models) {
249 final String moduleName = module.getName();
250 final Set<IdentitySchemaNode> idNodes = module.getIdentities();
251 LOG.debug("Processing Identities for module {} . Found {} identity statements", moduleName, idNodes.size());
253 for (final IdentitySchemaNode idNode : idNodes) {
254 final ObjectNode identityObj = JsonNodeFactory.instance.objectNode();
255 final String identityName = idNode.getQName().getLocalName();
256 LOG.debug("Processing Identity: {}", identityName);
258 identityObj.put(ID_KEY, identityName);
259 putIfNonNull(identityObj, DESCRIPTION_KEY, idNode.getDescription().orElse(null));
261 final ObjectNode props = JsonNodeFactory.instance.objectNode();
263 if (idNode.getBaseIdentities().isEmpty()) {
265 * This is a base identity. So lets see if it has sub types. If it does, then add them to the model
268 final Set<IdentitySchemaNode> derivedIds = idNode.getDerivedIdentities();
270 if (derivedIds != null) {
271 final ArrayNode subTypes = new ArrayNode(JsonNodeFactory.instance);
272 for (final IdentitySchemaNode derivedId : derivedIds) {
273 subTypes.add(derivedId.getQName().getLocalName());
275 identityObj.set(SUB_TYPES_KEY, subTypes);
280 * This is a derived entity. Add it's base type & move on.
282 props.put(TYPE_KEY, idNode.getBaseIdentities().iterator().next().getQName().getLocalName());
285 // Add the properties. For a base type, this will be an empty object as required by the Swagger spec.
286 identityObj.set(PROPERTIES_KEY, props);
287 models.set(identityName, identityObj);
291 private ObjectNode processDataNodeContainer(
292 final DataNodeContainer dataNode, final String parentName, final ObjectNode models, final boolean isConfig,
293 final SchemaContext schemaContext) throws IOException {
294 if (dataNode instanceof ListSchemaNode || dataNode instanceof ContainerSchemaNode) {
295 final Iterable<DataSchemaNode> containerChildren = dataNode.getChildNodes();
296 final String localName = ((SchemaNode) dataNode).getQName().getLocalName();
297 final ObjectNode properties =
298 processChildren(containerChildren, parentName + "/" + localName, models, isConfig, schemaContext);
299 final String nodeName = parentName + (isConfig ? OperationBuilder.CONFIG : OperationBuilder.OPERATIONAL)
302 final ObjectNode childSchema = getSchemaTemplate();
303 childSchema.put(TYPE_KEY, OBJECT_TYPE);
304 childSchema.set(PROPERTIES_KEY, properties);
306 childSchema.put(ID_KEY, nodeName);
307 models.set(nodeName, childSchema);
310 createConcreteModelForPost(models, localName,
311 createPropertiesForPost(dataNode, schemaContext, parentName + "/" + localName));
314 return processTopData(nodeName, models, (SchemaNode) dataNode);
319 private static void createConcreteModelForPost(final ObjectNode models, final String localName,
320 final JsonNode properties) {
321 final String nodePostName = OperationBuilder.CONFIG + localName + Post.METHOD_NAME;
322 final ObjectNode postSchema = getSchemaTemplate();
323 postSchema.put(TYPE_KEY, OBJECT_TYPE);
324 postSchema.put(ID_KEY, nodePostName);
325 postSchema.set(PROPERTIES_KEY, properties);
326 models.set(nodePostName, postSchema);
329 private JsonNode createPropertiesForPost(final DataNodeContainer dataNodeContainer,
330 final SchemaContext schemaContext, final String parentName) {
331 final ObjectNode properties = JsonNodeFactory.instance.objectNode();
332 for (final DataSchemaNode childNode : dataNodeContainer.getChildNodes()) {
333 if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
334 final ObjectNode items = JsonNodeFactory.instance.objectNode();
335 items.put(REF_KEY, parentName + "(config)" + childNode.getQName().getLocalName());
336 final ObjectNode property = JsonNodeFactory.instance.objectNode();
337 property.put(TYPE_KEY, childNode instanceof ListSchemaNode ? ARRAY_TYPE : OBJECT_TYPE);
338 property.set(ITEMS_KEY, items);
339 properties.set(childNode.getQName().getLocalName(), property);
340 } else if (childNode instanceof LeafSchemaNode) {
341 final ObjectNode property = processLeafNode((LeafSchemaNode) childNode, schemaContext);
342 properties.set(childNode.getQName().getLocalName(), property);
349 * Processes the nodes.
351 private ObjectNode processChildren(
352 final Iterable<DataSchemaNode> nodes, final String parentName, final ObjectNode models,
353 final boolean isConfig, final SchemaContext schemaContext) throws IOException {
354 final ObjectNode properties = JsonNodeFactory.instance.objectNode();
355 for (final DataSchemaNode node : nodes) {
356 if (node.isConfiguration() == isConfig) {
357 final String name = resolveNodesName(node, topLevelModule, schemaContext);
358 final ObjectNode property;
359 if (node instanceof LeafSchemaNode) {
360 property = processLeafNode((LeafSchemaNode) node, schemaContext);
362 } else if (node instanceof ListSchemaNode) {
363 property = processDataNodeContainer((ListSchemaNode) node, parentName, models, isConfig,
366 } else if (node instanceof LeafListSchemaNode) {
367 property = processLeafListNode((LeafListSchemaNode) node, schemaContext);
369 } else if (node instanceof ChoiceSchemaNode) {
370 if (((ChoiceSchemaNode) node).getCases().values().iterator().hasNext()) {
371 processChoiceNode(((ChoiceSchemaNode) node).getCases().values().iterator().next()
372 .getChildNodes(), parentName, models, schemaContext, isConfig, properties);
376 } else if (node instanceof AnyxmlSchemaNode) {
377 property = processAnyXMLNode((AnyxmlSchemaNode) node);
379 } else if (node instanceof AnydataSchemaNode) {
380 property = processAnydataNode((AnydataSchemaNode) node);
382 } else if (node instanceof ContainerSchemaNode) {
383 property = processDataNodeContainer((ContainerSchemaNode) node, parentName, models, isConfig,
387 throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass());
389 putIfNonNull(property, DESCRIPTION_KEY, node.getDescription().orElse(null));
390 properties.set(topLevelModule.getName() + ":" + name, property);
396 private ObjectNode processLeafListNode(final LeafListSchemaNode listNode,
397 final SchemaContext schemaContext) {
398 final ObjectNode props = JsonNodeFactory.instance.objectNode();
399 props.put(TYPE_KEY, ARRAY_TYPE);
401 final ObjectNode itemsVal = JsonNodeFactory.instance.objectNode();
402 final Optional<ElementCountConstraint> optConstraint = listNode.getElementCountConstraint();
404 if (optConstraint.isPresent()) {
405 final Integer constraintMax = optConstraint.get().getMaxElements();
406 max = constraintMax == null ? 2 : constraintMax;
407 processElementCount(optConstraint.get(), props);
413 processTypeDef(listNode.getType(), listNode, itemsVal, schemaContext);
414 processTypeDef(listNode.getType(), listNode, itemsVal, schemaContext);
416 processTypeDef(listNode.getType(), listNode, itemsVal, schemaContext);
418 props.set(ITEMS_KEY, itemsVal);
423 private void processChoiceNode(
424 final Iterable<DataSchemaNode> nodes, final String moduleName, final ObjectNode models,
425 final SchemaContext schemaContext, final boolean isConfig, final ObjectNode properties)
427 for (final DataSchemaNode node : nodes) {
428 final String name = resolveNodesName(node, topLevelModule, schemaContext);
429 final ObjectNode property;
431 if (node instanceof LeafSchemaNode) {
432 property = processLeafNode((LeafSchemaNode) node, schemaContext);
434 } else if (node instanceof ListSchemaNode) {
435 property = processDataNodeContainer((ListSchemaNode) node, moduleName, models, isConfig,
438 } else if (node instanceof LeafListSchemaNode) {
439 property = processLeafListNode((LeafListSchemaNode) node, schemaContext);
441 } else if (node instanceof ChoiceSchemaNode) {
442 if (((ChoiceSchemaNode) node).getCases().values().iterator().hasNext()) {
443 processChoiceNode(((ChoiceSchemaNode) node).getCases().values().iterator().next().getChildNodes(),
444 moduleName, models, schemaContext, isConfig, properties);
448 } else if (node instanceof AnyxmlSchemaNode) {
449 property = processAnyXMLNode((AnyxmlSchemaNode) node);
451 } else if (node instanceof AnydataSchemaNode) {
452 property = processAnydataNode((AnydataSchemaNode) node);
454 } else if (node instanceof ContainerSchemaNode) {
455 property = processDataNodeContainer((ContainerSchemaNode) node, moduleName, models, isConfig,
459 throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass());
462 putIfNonNull(property, DESCRIPTION_KEY, node.getDescription().orElse(null));
463 properties.set(name, property);
467 private static void processElementCount(final ElementCountConstraint constraint, final ObjectNode props) {
468 final Integer minElements = constraint.getMinElements();
469 if (minElements != null) {
470 props.put(MIN_ITEMS, minElements);
472 final Integer maxElements = constraint.getMaxElements();
473 if (maxElements != null) {
474 props.put(MAX_ITEMS, maxElements);
478 private static void processMandatory(final MandatoryAware node, final ObjectNode props) {
479 props.put(REQUIRED_KEY, node.isMandatory());
482 private ObjectNode processLeafNode(final LeafSchemaNode leafNode,
483 final SchemaContext schemaContext) {
484 final ObjectNode property = JsonNodeFactory.instance.objectNode();
486 final String leafDescription = leafNode.getDescription().orElse(null);
487 putIfNonNull(property, DESCRIPTION_KEY, leafDescription);
488 processMandatory(leafNode, property);
489 processTypeDef(leafNode.getType(), leafNode, property, schemaContext);
494 private static ObjectNode processAnydataNode(final AnydataSchemaNode leafNode) {
495 final ObjectNode property = JsonNodeFactory.instance.objectNode();
497 final String leafDescription = leafNode.getDescription().orElse(null);
498 putIfNonNull(property, DESCRIPTION_KEY, leafDescription);
500 processMandatory(leafNode, property);
501 final String localName = leafNode.getQName().getLocalName();
502 property.put(TYPE_KEY, "example of anydata " + localName);
507 private static ObjectNode processAnyXMLNode(final AnyxmlSchemaNode leafNode) {
508 final ObjectNode property = JsonNodeFactory.instance.objectNode();
510 final String leafDescription = leafNode.getDescription().orElse(null);
511 putIfNonNull(property, DESCRIPTION_KEY, leafDescription);
513 processMandatory(leafNode, property);
514 final String localName = leafNode.getQName().getLocalName();
515 property.put(TYPE_KEY, "example of anyxml " + localName);
520 private String processTypeDef(final TypeDefinition<?> leafTypeDef, final DataSchemaNode node,
521 final ObjectNode property, final SchemaContext schemaContext) {
522 final String jsonType;
523 final Object defValue = leafTypeDef.getDefaultValue().orElse(null);
524 if (defValue == null) {
525 if (leafTypeDef instanceof BinaryTypeDefinition) {
526 jsonType = processBinaryType(property);
528 } else if (leafTypeDef instanceof BitsTypeDefinition) {
529 jsonType = processBitsType((BitsTypeDefinition) leafTypeDef, property);
531 } else if (leafTypeDef instanceof EnumTypeDefinition) {
532 jsonType = processEnumType((EnumTypeDefinition) leafTypeDef, property);
534 } else if (leafTypeDef instanceof IdentityrefTypeDefinition) {
535 final String name = topLevelModule.getName();
536 jsonType = name + ":" + ((IdentityrefTypeDefinition) leafTypeDef).getIdentities().iterator().next()
537 .getQName().getLocalName();
539 } else if (leafTypeDef instanceof StringTypeDefinition) {
540 jsonType = processStringType(leafTypeDef, property, node.getQName().getLocalName());
542 } else if (leafTypeDef instanceof UnionTypeDefinition) {
543 jsonType = processUnionType((UnionTypeDefinition) leafTypeDef, property, schemaContext, node);
545 } else if (leafTypeDef instanceof EmptyTypeDefinition) {
546 jsonType = UNIQUE_EMPTY_IDENTIFIER;
548 } else if (leafTypeDef instanceof LeafrefTypeDefinition) {
549 return processLeafRef(node, property, schemaContext, leafTypeDef);
551 } else if (leafTypeDef instanceof BooleanTypeDefinition) {
554 } else if (leafTypeDef instanceof RangeRestrictedTypeDefinition) {
555 final Number maybeLower = ((RangeRestrictedTypeDefinition<?, ?>) leafTypeDef).getRangeConstraint()
556 .map(RangeConstraint::getAllowedRanges).map(RangeSet::span).map(Range::lowerEndpoint)
558 jsonType = String.valueOf(maybeLower);
561 jsonType = OBJECT_TYPE;
565 jsonType = String.valueOf(defValue);
567 putIfNonNull(property, TYPE_KEY, jsonType);
571 private String processLeafRef(final DataSchemaNode node, final ObjectNode property,
572 final SchemaContext schemaContext, final TypeDefinition<?> leafTypeDef) {
573 PathExpression xpath = ((LeafrefTypeDefinition) leafTypeDef).getPathStatement();
574 final SchemaNode schemaNode;
576 final String xPathString = STRIP_PATTERN.matcher(xpath.getOriginalString()).replaceAll("");
577 xpath = new PathExpressionImpl(xPathString, xpath.isAbsolute());
580 if (xpath.isAbsolute()) {
581 module = findModule(schemaContext, leafTypeDef.getQName());
582 schemaNode = SchemaContextUtil.findDataSchemaNode(schemaContext, module, xpath);
584 module = findModule(schemaContext, node.getQName());
585 schemaNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, module, node, xpath);
588 return processTypeDef(((TypedDataSchemaNode) schemaNode).getType(), (DataSchemaNode) schemaNode,
589 property, schemaContext);
592 private static Module findModule(final SchemaContext schemaContext, final QName qualifiedName) {
593 return schemaContext.findModule(qualifiedName.getNamespace(), qualifiedName.getRevision()).orElse(null);
596 private static String processBinaryType(final ObjectNode property) {
597 final ObjectNode media = JsonNodeFactory.instance.objectNode();
598 media.put(BINARY_ENCODING_KEY, BASE_64);
599 property.set(MEDIA_KEY, media);
603 private static String processEnumType(final EnumTypeDefinition enumLeafType,
604 final ObjectNode property) {
605 final List<EnumPair> enumPairs = enumLeafType.getValues();
606 ArrayNode enumNames = new ArrayNode(JsonNodeFactory.instance);
607 for (final EnumPair enumPair : enumPairs) {
608 enumNames.add(new TextNode(enumPair.getName()));
611 property.set(ENUM, enumNames);
612 return enumLeafType.getValues().iterator().next().getName();
615 private static String processBitsType(final BitsTypeDefinition bitsType,
616 final ObjectNode property) {
617 property.put(MIN_ITEMS, 0);
618 property.put(UNIQUE_ITEMS_KEY, true);
619 ArrayNode enumNames = new ArrayNode(JsonNodeFactory.instance);
620 final List<Bit> bits = bitsType.getBits();
621 for (final Bit bit : bits) {
622 enumNames.add(new TextNode(bit.getName()));
624 property.set(ENUM, enumNames);
626 return enumNames.iterator().next() + " " + enumNames.get(enumNames.size() - 1);
629 private static String processStringType(final TypeDefinition<?> stringType,
630 final ObjectNode property, final String nodeName) {
631 StringTypeDefinition type = (StringTypeDefinition) stringType;
632 Optional<LengthConstraint> lengthConstraints = ((StringTypeDefinition) stringType).getLengthConstraint();
633 while (!lengthConstraints.isPresent() && type.getBaseType() != null) {
634 type = type.getBaseType();
635 lengthConstraints = type.getLengthConstraint();
638 if (lengthConstraints.isPresent()) {
639 final Range<Integer> range = lengthConstraints.get().getAllowedRanges().span();
640 putIfNonNull(property, MIN_LENGTH_KEY, range.lowerEndpoint());
641 putIfNonNull(property, MAX_LENGTH_KEY, range.upperEndpoint());
644 if (type.getPatternConstraints().iterator().hasNext()) {
645 final PatternConstraint pattern = type.getPatternConstraints().iterator().next();
646 String regex = pattern.getJavaPatternString();
647 regex = regex.substring(1, regex.length() - 1);
648 final Generex generex = new Generex(regex);
649 return generex.random();
651 return "Some " + nodeName;
655 private String processUnionType(final UnionTypeDefinition unionType, final ObjectNode property,
656 final SchemaContext schemaContext, final DataSchemaNode node) {
657 final ArrayNode unionNames = new ArrayNode(JsonNodeFactory.instance);
658 for (final TypeDefinition<?> typeDef : unionType.getTypes()) {
659 unionNames.add(processTypeDef(typeDef, node, property, schemaContext));
661 property.set(ENUM, unionNames);
662 return unionNames.iterator().next().asText();
666 * Helper method to generate a pre-filled JSON schema object.
668 private static ObjectNode getSchemaTemplate() {
669 final ObjectNode schemaJSON = JsonNodeFactory.instance.objectNode();
670 schemaJSON.put(SCHEMA_KEY, SCHEMA_URL);
675 private static void putIfNonNull(final ObjectNode property, final String key, final Number number) {
676 if (key != null && number != null) {
677 if (number instanceof Double) {
678 property.put(key, (Double) number);
679 } else if (number instanceof Float) {
680 property.put(key, (Float) number);
681 } else if (number instanceof Integer) {
682 property.put(key, (Integer) number);
683 } else if (number instanceof Short) {
684 property.put(key, (Short) number);
685 } else if (number instanceof Long) {
686 property.put(key, (Long) number);
691 private static void putIfNonNull(final ObjectNode property, final String key, final String value) {
692 if (key != null && value != null) {
693 property.put(key, value);